daemonclient

package
v0.13.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 24, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package daemonclient provides client connectivity to the agnt daemon.

Shared Connection Design

The Conn type provides a shared, reusable client connection to the daemon. Instead of each component creating its own client with a socket path, a single Conn is created at startup and shared across all consumers.

## Why This Design?

Previously, each component (StatusFetcher, Summarizer, BashRunner, etc.) independently managed socket paths and created daemon.Client instances. This led to:

  • Redundant socket path passing throughout the codebase
  • Multiple disconnected clients that could get out of sync
  • No ability to batch requests (each client locks independently)
  • Verbose client API with 50+ wrapper methods

## Request Builder Pattern

Instead of method-per-command (client.ProcList(), client.ProxyList(), etc.), Conn exposes a fluent Request builder:

// Single request returning JSON map
result, err := conn.Request("PROC", "LIST").
    WithJSON(filter).
    JSON()

// Request with inline args
output, err := conn.Request("PROC", "OUTPUT", processID).
    WithArgs("tail=50", "stream=combined").
    String()

// Request expecting OK/ERR only
err := conn.Request("PROXY", "STOP", proxyID).OK()

This keeps the API surface small while allowing direct use of protocol verbs.

## Sharing the Connection

Create one Conn at startup and pass it to all components:

conn := daemonclient.NewConn(socketPath)
defer conn.Close()

## Thread Safety

Conn is thread-safe. Multiple goroutines can issue requests concurrently. Requests are serialized internally (the daemon protocol is request-response, not pipelined).

## Auto-Reconnection

If the connection drops, the next request will automatically reconnect. Use EnsureConnected() to explicitly verify connectivity before issuing requests.

Index

Constants

View Source
const SocketName = "devtool-mcp"

SocketName is the socket name used for agnt daemon.

Variables

View Source
var (
	ErrNotConnected = client.ErrNotConnected
	ErrServerError  = client.ErrServerError
)

Re-export error types from go-cli-server for backward compatibility.

View Source
var (
	// ErrReconnecting is returned when an operation is attempted during reconnection.
	ErrReconnecting = goclient.ErrReconnecting
	// ErrShutdown is returned when an operation is attempted after shutdown.
	ErrShutdown = goclient.ErrShutdown
)
View Source
var (
	ErrSocketInUse    = socket.ErrSocketInUse
	ErrSocketNotFound = socket.ErrSocketNotFound
	ErrDaemonRunning  = socket.ErrDaemonRunning
)

Re-export error types from go-cli-server/socket for backward compatibility.

View Source
var ErrConnectionClosed = goclient.ErrConnectionClosed

ErrConnectionClosed is returned when operating on a closed connection. Re-exported from the go-cli-server library for backward compatibility.

Functions

func CleanupZombieDaemons

func CleanupZombieDaemons(socketPath string) int

CleanupZombieDaemons finds and kills zombie daemon processes.

func Connect

func Connect(path string) (net.Conn, error)

Connect attempts to connect to an existing daemon socket.

func DefaultSocketPath

func DefaultSocketPath() string

DefaultSocketPath returns the default socket path for agnt.

func IsDaemonRunning

func IsDaemonRunning(socketPath string) bool

IsDaemonRunning checks if the daemon is running at the given socket path.

func IsRunning

func IsRunning(path string) bool

IsRunning checks if a daemon is running at the given socket path.

func StopDaemon

func StopDaemon(socketPath string) error

StopDaemon connects to a running daemon and requests shutdown.

func UpgradeDaemon

func UpgradeDaemon(ctx context.Context, config UpgradeConfig) error

UpgradeDaemon is a convenience function for upgrading the daemon.

Types

type AutoStartClient

type AutoStartClient struct {
	*Client
	// contains filtered or unexported fields
}

AutoStartClient creates a client that auto-starts the daemon if needed.

func NewAutoStartClient

func NewAutoStartClient(config AutoStartConfig) *AutoStartClient

NewAutoStartClient creates a new auto-start client.

func (*AutoStartClient) Connect

func (c *AutoStartClient) Connect() error

Connect connects to the daemon, starting it if necessary.

type AutoStartConfig

type AutoStartConfig struct {
	// SocketPath is the socket path to connect to.
	SocketPath string
	// DaemonPath is the path to the daemon executable.
	DaemonPath string
	// StartTimeout is how long to wait for the daemon to start.
	StartTimeout time.Duration
	// RetryInterval is how long to wait between connection attempts.
	RetryInterval time.Duration
	// MaxRetries is the maximum number of connection attempts.
	MaxRetries int
}

AutoStartConfig holds configuration for auto-starting the daemon.

func DefaultAutoStartConfig

func DefaultAutoStartConfig() AutoStartConfig

DefaultAutoStartConfig returns sensible defaults.

type BrowserInfo

type BrowserInfo struct {
	Active       int64 `json:"active"`
	TotalStarted int64 `json:"total_started"`
}

BrowserInfo holds browser manager statistics.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a client for communicating with the daemon over the socket. This wraps go-cli-server/client.Conn with agnt-specific methods.

func EnsureDaemonRunning

func EnsureDaemonRunning(config AutoStartConfig) (*Client, error)

EnsureDaemonRunning ensures the daemon is running, starting it if needed. Returns a connected client.

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient creates a new daemon client.

func NewClientWithPath

func NewClientWithPath(socketPath string) *Client

NewClientWithPath creates a new daemon client with a specific socket path.

func (*Client) AlertClear

func (c *Client) AlertClear() error

AlertClear clears all alerts from the daemon.

func (*Client) AlertClearProcess

func (c *Client) AlertClearProcess(processID string) error

AlertClearProcess clears alerts for a specific process (e.g., after a successful build).

func (*Client) AlertQuery

func (c *Client) AlertQuery(filter protocol.AlertQueryFilter) (map[string]interface{}, error)

AlertQuery queries alerts from the daemon.

func (*Client) AlertReport

func (c *Client) AlertReport(payload protocol.AlertReportPayload) error

AlertReport sends an alert report to the daemon.

func (*Client) AutomationEvaluate

func (c *Client) AutomationEvaluate(config protocol.AutomationEvaluateConfig) (map[string]interface{}, error)

AutomationEvaluate evaluates JavaScript in an automation session.

func (*Client) AutomationList

func (c *Client) AutomationList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

AutomationList lists all active automation sessions.

func (*Client) AutomationNavigate

func (c *Client) AutomationNavigate(config protocol.AutomationNavigateConfig) (map[string]interface{}, error)

AutomationNavigate navigates to a URL in an automation session.

func (*Client) AutomationScreenshot

func (c *Client) AutomationScreenshot(config protocol.AutomationScreenshotConfig) (map[string]interface{}, error)

AutomationScreenshot takes a screenshot in an automation session.

func (*Client) AutomationStart

func (c *Client) AutomationStart(config protocol.AutomationStartConfig) (map[string]interface{}, error)

AutomationStart starts a chromedp automation session.

func (*Client) AutomationStatus

func (c *Client) AutomationStatus(id string) (map[string]interface{}, error)

AutomationStatus gets the status of an automation session.

func (*Client) AutomationStop

func (c *Client) AutomationStop(id string) error

AutomationStop stops an automation session.

func (*Client) AutostartClearPorts

func (c *Client) AutostartClearPorts(projectPath string) (map[string]interface{}, error)

AutostartClearPorts kills port blockers and resumes autostart for a project.

func (*Client) AutostartContinue

func (c *Client) AutostartContinue(projectPath string) (map[string]interface{}, error)

AutostartContinue resumes autostart without killing port blockers.

func (*Client) BroadcastActivity

func (c *Client) BroadcastActivity(active bool, proxyIDs ...string) error

BroadcastActivity broadcasts an activity state update to connected browsers via specified proxies.

func (*Client) BroadcastOutputPreview

func (c *Client) BroadcastOutputPreview(lines []string, proxyIDs ...string) error

BroadcastOutputPreview broadcasts output preview lines to connected browsers via proxies.

func (*Client) BrowserList

func (c *Client) BrowserList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

BrowserList lists all active browser instances.

func (*Client) BrowserStart

func (c *Client) BrowserStart(config protocol.BrowserStartConfig) (map[string]interface{}, error)

BrowserStart starts a browser instance.

func (*Client) BrowserStatus

func (c *Client) BrowserStatus(id string) (map[string]interface{}, error)

BrowserStatus gets the status of a browser instance.

func (*Client) BrowserStop

func (c *Client) BrowserStop(id string) error

BrowserStop stops a running browser instance.

func (*Client) ChaosAddRule

func (c *Client) ChaosAddRule(proxyID string, rule protocol.ChaosRuleConfig) (map[string]interface{}, error)

ChaosAddRule adds a single rule to a proxy's chaos engine.

func (*Client) ChaosClear

func (c *Client) ChaosClear(proxyID string) (map[string]interface{}, error)

ChaosClear clears all chaos rules and resets stats for a proxy.

func (*Client) ChaosDisable

func (c *Client) ChaosDisable(proxyID string) (map[string]interface{}, error)

ChaosDisable disables chaos injection on a proxy.

func (*Client) ChaosEnable

func (c *Client) ChaosEnable(proxyID string) (map[string]interface{}, error)

ChaosEnable enables chaos injection on a proxy.

func (*Client) ChaosListPresets

func (c *Client) ChaosListPresets() (map[string]interface{}, error)

ChaosListPresets returns the list of available chaos presets.

func (*Client) ChaosListRules

func (c *Client) ChaosListRules(proxyID string) (map[string]interface{}, error)

ChaosListRules lists all chaos rules for a proxy.

func (*Client) ChaosPreset

func (c *Client) ChaosPreset(proxyID, preset string) (map[string]interface{}, error)

ChaosPreset applies a preset chaos configuration to a proxy.

func (*Client) ChaosRemoveRule

func (c *Client) ChaosRemoveRule(proxyID, ruleID string) (map[string]interface{}, error)

ChaosRemoveRule removes a rule from a proxy's chaos engine.

func (*Client) ChaosSet

func (c *Client) ChaosSet(proxyID string, config protocol.ChaosConfigPayload) (map[string]interface{}, error)

ChaosSet sets the full chaos configuration on a proxy.

func (*Client) ChaosStats

func (c *Client) ChaosStats(proxyID string) (map[string]interface{}, error)

ChaosStats gets chaos statistics for a proxy.

func (*Client) ChaosStatus

func (c *Client) ChaosStatus(proxyID string) (map[string]interface{}, error)

ChaosStatus gets the chaos status of a proxy.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection to the daemon.

func (*Client) Connect

func (c *Client) Connect() error

Connect connects to the daemon.

func (*Client) CurrentPageClear

func (c *Client) CurrentPageClear(proxyID string) error

CurrentPageClear clears page sessions.

func (*Client) CurrentPageGet

func (c *Client) CurrentPageGet(proxyID, sessionID string) (map[string]interface{}, error)

CurrentPageGet gets details for a specific page session.

func (*Client) CurrentPageList

func (c *Client) CurrentPageList(proxyID string) (map[string]interface{}, error)

CurrentPageList lists active page sessions.

func (*Client) Detect

func (c *Client) Detect(path string) (map[string]interface{}, error)

Detect detects the project type at the given path.

func (*Client) Doctor

func (c *Client) Doctor(projectPath string) (map[string]interface{}, error)

Doctor runs health checks and returns a diagnostic report.

func (*Client) Info

func (c *Client) Info() (*DaemonInfo, error)

Info retrieves daemon information. Uses STATUS command to get full daemon info (Hub's INFO is minimal). Falls back to INFO if not available (for backwards compatibility).

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the client is connected.

func (*Client) OverlayClear

func (c *Client) OverlayClear() error

OverlayClear clears the overlay endpoint configuration.

func (*Client) OverlayGet

func (c *Client) OverlayGet() (map[string]interface{}, error)

OverlayGet gets the current overlay endpoint configuration.

func (*Client) OverlaySet

func (c *Client) OverlaySet(endpoint string) (map[string]interface{}, error)

OverlaySet sets the overlay endpoint URL.

func (*Client) Ping

func (c *Client) Ping() error

Ping sends a ping to the daemon and waits for a pong response.

func (*Client) ProcAutoRestart

func (c *Client) ProcAutoRestart(processID, action string, config *ProcAutoRestartConfig) (map[string]interface{}, error)

ProcAutoRestart enables, disables, or queries auto-restart for a process.

func (*Client) ProcCleanupPort

func (c *Client) ProcCleanupPort(port int) (map[string]interface{}, error)

ProcCleanupPort kills processes on a specific port.

func (*Client) ProcList

func (c *Client) ProcList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

ProcList lists all processes.

func (*Client) ProcOutput

func (c *Client) ProcOutput(processID string, filter protocol.OutputFilter) (string, error)

ProcOutput gets the output of a process.

func (*Client) ProcRestart

func (c *Client) ProcRestart(processID string) (map[string]interface{}, error)

ProcRestart restarts a single process by ID.

func (*Client) ProcStatus

func (c *Client) ProcStatus(processID string) (map[string]interface{}, error)

ProcStatus gets the status of a process.

func (*Client) ProcStop

func (c *Client) ProcStop(processID string, force bool) (map[string]interface{}, error)

ProcStop stops a process.

func (*Client) ProxyExec

func (c *Client) ProxyExec(id, code string) (map[string]interface{}, error)

ProxyExec executes JavaScript in connected browsers.

func (*Client) ProxyList

func (c *Client) ProxyList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

ProxyList lists all proxies.

func (*Client) ProxyLogClear

func (c *Client) ProxyLogClear(proxyID string) error

ProxyLogClear clears proxy logs.

func (*Client) ProxyLogQuery

func (c *Client) ProxyLogQuery(proxyID string, filter protocol.LogQueryFilter) (map[string]interface{}, error)

ProxyLogQuery queries proxy logs.

func (*Client) ProxyLogStats

func (c *Client) ProxyLogStats(proxyID string) (map[string]interface{}, error)

ProxyLogStats gets proxy log statistics.

func (*Client) ProxyRestart

func (c *Client) ProxyRestart(id string) (map[string]interface{}, error)

ProxyRestart restarts a single proxy by ID.

func (*Client) ProxyStart

func (c *Client) ProxyStart(id, targetURL string, port, maxLogSize int, path string) (map[string]interface{}, error)

ProxyStart starts a reverse proxy.

func (*Client) ProxyStartWithConfig

func (c *Client) ProxyStartWithConfig(id, targetURL string, port, maxLogSize int, config ProxyStartConfig) (map[string]interface{}, error)

ProxyStartWithConfig starts a reverse proxy with extended configuration.

func (*Client) ProxyStatus

func (c *Client) ProxyStatus(id string) (map[string]interface{}, error)

ProxyStatus gets the status of a proxy.

func (*Client) ProxyStop

func (c *Client) ProxyStop(id string) error

ProxyStop stops a reverse proxy.

func (*Client) ProxyToast

func (c *Client) ProxyToast(id string, toast protocol.ToastConfig) (map[string]interface{}, error)

ProxyToast sends a toast notification to connected browsers.

func (*Client) RawConn

func (c *Client) RawConn() *client.Conn

RawConn returns the underlying go-cli-server connection. This is intended for internal/test use only.

func (*Client) RestartAll

func (c *Client) RestartAll() (map[string]interface{}, error)

RestartAll restarts all running processes and proxies with their original configurations.

func (*Client) Run

func (c *Client) Run(config interface{}) (map[string]interface{}, error)

Run starts a process on the daemon. The config is marshaled to JSON and can be protocol.RunConfig or any struct that embeds it (e.g., with additional fields like no_auto_restart).

func (*Client) ScriptGet

func (c *Client) ScriptGet(name, projectPath string) (map[string]interface{}, error)

ScriptGet retrieves full detail for a named script.

func (*Client) ScriptList

func (c *Client) ScriptList(projectPath string) (map[string]interface{}, error)

ScriptList lists all scripts for a project directory.

func (*Client) ScriptOutput

func (c *Client) ScriptOutput(name, projectPath string, tail int) (map[string]interface{}, error)

ScriptOutput retrieves output history for a named script.

func (*Client) ScriptRestart

func (c *Client) ScriptRestart(name, projectPath string) (map[string]interface{}, error)

ScriptRestart restarts a script by name.

func (*Client) ScriptStop

func (c *Client) ScriptStop(name, projectPath string) (map[string]interface{}, error)

ScriptStop stops a script by name.

func (*Client) SessionAttach

func (c *Client) SessionAttach(directory string) (map[string]interface{}, error)

SessionAttach attaches to a session found by directory ancestry.

func (*Client) SessionCancel

func (c *Client) SessionCancel(taskID string) error

SessionCancel cancels a scheduled task.

func (*Client) SessionFind

func (c *Client) SessionFind(directory string) (map[string]interface{}, error)

SessionFind finds a session by directory ancestry.

func (*Client) SessionGenerateCode

func (c *Client) SessionGenerateCode(command string) (string, error)

SessionGenerateCode requests a new session code from the daemon.

func (*Client) SessionGet

func (c *Client) SessionGet(code string) (map[string]interface{}, error)

SessionGet retrieves a specific session.

func (*Client) SessionHeartbeat

func (c *Client) SessionHeartbeat(code string) error

SessionHeartbeat sends a heartbeat for a session.

func (*Client) SessionList

func (c *Client) SessionList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

SessionList lists active sessions.

func (*Client) SessionRegister

func (c *Client) SessionRegister(code string, overlayPath string, projectPath string, command string, args []string) (map[string]interface{}, error)

SessionRegister registers a new session with the daemon.

func (*Client) SessionRegisterWithPGID added in v0.12.41

func (c *Client) SessionRegisterWithPGID(code string, overlayPath string, projectPath string, command string, args []string, sessionPGID int) (map[string]interface{}, error)

SessionRegisterWithPGID registers a new session and reports the POSIX process group ID of the PTY child (the session leader). See the daemon package's equivalent method for details.

func (*Client) SessionSchedule

func (c *Client) SessionSchedule(code string, duration string, message string) (map[string]interface{}, error)

SessionSchedule schedules a message for future delivery.

func (*Client) SessionSend

func (c *Client) SessionSend(code string, message string) (map[string]interface{}, error)

SessionSend sends an immediate message to a session.

func (*Client) SessionTasks

func (c *Client) SessionTasks(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

SessionTasks lists scheduled tasks.

func (*Client) SessionURL

func (c *Client) SessionURL(code string, url string, scriptName string) (map[string]interface{}, error)

SessionURL reports a detected URL from an agnt run session.

func (*Client) SessionUnregister

func (c *Client) SessionUnregister(code string) error

SessionUnregister unregisters a session from the daemon.

func (*Client) Shutdown

func (c *Client) Shutdown() error

Shutdown requests the daemon to shut down.

func (*Client) SocketPath

func (c *Client) SocketPath() string

SocketPath returns the socket path.

func (*Client) StartupLog

func (c *Client) StartupLog(limit int) (map[string]interface{}, error)

StartupLog queries the startup log from the daemon.

func (*Client) StopAll

func (c *Client) StopAll() (map[string]interface{}, error)

StopAll stops all running processes, proxies, and tunnels.

func (*Client) StoreClear

func (c *Client) StoreClear(req protocol.StoreClearRequest) error

StoreClear clears all entries in a scope.

func (*Client) StoreDelete

func (c *Client) StoreDelete(req protocol.StoreDeleteRequest) error

StoreDelete deletes a value from the key-value store.

func (*Client) StoreGet

func (c *Client) StoreGet(req protocol.StoreGetRequest) (map[string]interface{}, error)

StoreGet retrieves a value from the key-value store.

func (*Client) StoreGetAll

func (c *Client) StoreGetAll(req protocol.StoreGetAllRequest) (map[string]interface{}, error)

StoreGetAll retrieves all key-value pairs in a scope.

func (*Client) StoreList

func (c *Client) StoreList(req protocol.StoreListRequest) (map[string]interface{}, error)

StoreList lists all keys in a scope.

func (*Client) StoreSet

func (c *Client) StoreSet(req protocol.StoreSetRequest) error

StoreSet stores a value in the key-value store.

func (*Client) StreamEvents

func (c *Client) StreamEvents(ctx context.Context, filter protocol.StreamEventFilter, handler func(proxy.LogEntry) error) error

StreamEvents opens a long-lived event stream from the daemon. It creates a dedicated connection (not the shared pool connection) and calls handler for each event received. The stream runs until ctx is cancelled or the connection drops. Returns the first error encountered, or nil if ctx was cancelled.

func (*Client) TunnelList

func (c *Client) TunnelList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

TunnelList lists all active tunnels.

func (*Client) TunnelStart

func (c *Client) TunnelStart(config protocol.TunnelStartConfig) (map[string]interface{}, error)

TunnelStart starts a tunnel for a local port.

func (*Client) TunnelStatus

func (c *Client) TunnelStatus(id string) (map[string]interface{}, error)

TunnelStatus gets the status of a tunnel.

func (*Client) TunnelStop

func (c *Client) TunnelStop(id string) error

TunnelStop stops a running tunnel.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures a Client.

func WithSocketPath

func WithSocketPath(path string) ClientOption

WithSocketPath sets the socket path for the client.

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout sets the default timeout for operations.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn provides a shared, reusable client connection to the daemon. Create one Conn and share it across all components that need to communicate with the daemon.

Conn is distinct from Connection (server-side handler in connection.go).

func NewConn

func NewConn(socketPath string) *Conn

NewConn creates a new shared daemon connection. The connection is not established until the first request or EnsureConnected().

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection permanently. After Close, the Conn cannot be reused.

func (*Conn) Disconnect

func (c *Conn) Disconnect() error

Disconnect closes the current connection but allows reconnection. Use this to release resources temporarily while keeping the Conn usable.

func (*Conn) EnsureConnected

func (c *Conn) EnsureConnected() error

EnsureConnected ensures the connection is established. If already connected, returns nil immediately. If not connected, attempts to connect.

func (*Conn) IsConnected

func (c *Conn) IsConnected() bool

IsConnected returns whether the connection is currently established.

func (*Conn) Ping

func (c *Conn) Ping() error

Ping sends a ping to the daemon and waits for a pong response.

func (*Conn) RawConn

func (c *Conn) RawConn() *goclient.Conn

RawConn returns the underlying go-cli-server connection. This is intended for internal/test use only.

func (*Conn) Request

func (c *Conn) Request(verb string, args ...string) *RequestBuilder

Request creates a new request builder for the given verb and arguments.

func (*Conn) SetTimeout

func (c *Conn) SetTimeout(d time.Duration)

SetTimeout sets the default timeout for operations.

func (*Conn) SocketPath

func (c *Conn) SocketPath() string

SocketPath returns the configured socket path.

type DaemonInfo

type DaemonInfo struct {
	Version       string                  `json:"version"`
	BuildTime     string                  `json:"build_time,omitempty"`
	GitCommit     string                  `json:"git_commit,omitempty"`
	SocketPath    string                  `json:"socket_path"`
	Uptime        time.Duration           `json:"uptime"`
	ClientCount   int64                   `json:"client_count"`
	ProcessInfo   ProcessInfo             `json:"process_info"`
	ProxyInfo     ProxyInfo               `json:"proxy_info"`
	TunnelInfo    TunnelInfo              `json:"tunnel_info"`
	BrowserInfo   BrowserInfo             `json:"browser_info"`
	SessionInfo   session.SessionInfo     `json:"session_info"`
	SchedulerInfo scheduler.SchedulerInfo `json:"scheduler_info"`
	UpdateInfo    *updater.UpdateInfo     `json:"update_info,omitempty"`
}

DaemonInfo holds daemon status information.

type DaemonUpgrader

type DaemonUpgrader struct {
	// contains filtered or unexported fields
}

DaemonUpgrader handles atomic daemon upgrades with locking.

func NewDaemonUpgrader

func NewDaemonUpgrader(config UpgradeConfig) *DaemonUpgrader

NewDaemonUpgrader creates a new daemon upgrader.

func (*DaemonUpgrader) Upgrade

func (u *DaemonUpgrader) Upgrade(ctx context.Context) error

Upgrade performs an atomic daemon upgrade with the following steps:

  1. Acquire upgrade lock (prevents concurrent upgrades)
  2. Connect to running daemon and get current version
  3. Request graceful shutdown (stops all processes)
  4. Wait for daemon to exit
  5. Clean up stale socket/PID files
  6. Start new daemon binary
  7. Wait for new daemon to be ready
  8. Verify new daemon version
  9. Release upgrade lock

type ProcAutoRestartConfig

type ProcAutoRestartConfig struct {
	MaxRestarts    int  `json:"max_restarts,omitempty"`
	OnlyOnError    bool `json:"only_on_error,omitempty"`
	RestartDelayMs int  `json:"restart_delay_ms,omitempty"`
}

ProcAutoRestartConfig holds configuration for process auto-restart.

type ProcessInfo

type ProcessInfo struct {
	Active       int64 `json:"active"`
	TotalStarted int64 `json:"total_started"`
	TotalFailed  int64 `json:"total_failed"`
}

ProcessInfo holds process manager statistics.

type ProxyInfo

type ProxyInfo struct {
	Active       int64 `json:"active"`
	TotalStarted int64 `json:"total_started"`
}

ProxyInfo holds proxy manager statistics.

type ProxyStartConfig

type ProxyStartConfig struct {
	Path          string                 `json:"path,omitempty"`
	BindAddress   string                 `json:"bind_address,omitempty"`
	AllowExternal bool                   `json:"allow_external,omitempty"`
	PublicURL     string                 `json:"public_url,omitempty"`
	SkipTLSVerify bool                   `json:"skip_tls_verify,omitempty"`
	Tunnel        *protocol.TunnelConfig `json:"tunnel,omitempty"`
}

ProxyStartConfig holds configuration for starting a proxy.

type ReconnectCallback

type ReconnectCallback func(client *Client) error

ReconnectCallback is called after successful reconnection. It should restore any state that needs to be re-registered with the daemon.

type RequestBuilder

type RequestBuilder struct {
	// contains filtered or unexported fields
}

RequestBuilder builds and executes requests to the daemon. Use Conn.Request() to create a RequestBuilder.

func (*RequestBuilder) Bytes

func (r *RequestBuilder) Bytes() ([]byte, error)

Bytes executes the request and returns the raw JSON response bytes.

func (*RequestBuilder) Chunked

func (r *RequestBuilder) Chunked() ([]byte, error)

Chunked executes the request and collects chunked response data.

func (*RequestBuilder) JSON

func (r *RequestBuilder) JSON() (map[string]interface{}, error)

JSON executes the request and returns the response as a map.

func (*RequestBuilder) JSONInto

func (r *RequestBuilder) JSONInto(v interface{}) error

JSONInto executes the request and unmarshals the response into v.

func (*RequestBuilder) OK

func (r *RequestBuilder) OK() error

OK executes the request and returns nil on success.

func (*RequestBuilder) String

func (r *RequestBuilder) String() (string, error)

String executes the request with chunked response and returns as string.

func (*RequestBuilder) WithArgs

func (r *RequestBuilder) WithArgs(args ...string) *RequestBuilder

WithArgs appends additional string arguments to the request.

func (*RequestBuilder) WithData

func (r *RequestBuilder) WithData(data []byte) *RequestBuilder

WithData sets the request payload as raw bytes.

func (*RequestBuilder) WithJSON

func (r *RequestBuilder) WithJSON(v interface{}) *RequestBuilder

WithJSON marshals the value as JSON and sets it as the request payload.

type ResilientClient

type ResilientClient struct {
	// contains filtered or unexported fields
}

ResilientClient wraps client.ResilientConn with automatic reconnection and health monitoring. It provides agnt-specific wrapper methods for convenience.

func NewResilientClient

func NewResilientClient(config ResilientClientConfig) *ResilientClient

NewResilientClient creates a new resilient client.

func (*ResilientClient) AlertClear

func (rc *ResilientClient) AlertClear() error

AlertClear clears all alerts from the daemon.

func (*ResilientClient) AlertClearProcess

func (rc *ResilientClient) AlertClearProcess(processID string) error

AlertClearProcess clears alerts for a specific process (e.g., after a successful build).

func (*ResilientClient) AlertQuery

func (rc *ResilientClient) AlertQuery(filter protocol.AlertQueryFilter) (map[string]interface{}, error)

AlertQuery queries alerts from the daemon.

func (*ResilientClient) AlertReport

func (rc *ResilientClient) AlertReport(payload protocol.AlertReportPayload) error

AlertReport sends an alert report to the daemon.

func (*ResilientClient) AutomationEvaluate

func (rc *ResilientClient) AutomationEvaluate(config protocol.AutomationEvaluateConfig) (map[string]interface{}, error)

AutomationEvaluate evaluates JavaScript in an automation session.

func (*ResilientClient) AutomationList

func (rc *ResilientClient) AutomationList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

AutomationList lists all active automation sessions.

func (*ResilientClient) AutomationNavigate

func (rc *ResilientClient) AutomationNavigate(config protocol.AutomationNavigateConfig) (map[string]interface{}, error)

AutomationNavigate navigates to a URL in an automation session.

func (*ResilientClient) AutomationScreenshot

func (rc *ResilientClient) AutomationScreenshot(config protocol.AutomationScreenshotConfig) (map[string]interface{}, error)

AutomationScreenshot takes a screenshot in an automation session.

func (*ResilientClient) AutomationStart

func (rc *ResilientClient) AutomationStart(config protocol.AutomationStartConfig) (map[string]interface{}, error)

AutomationStart starts a chromedp automation session.

func (*ResilientClient) AutomationStatus

func (rc *ResilientClient) AutomationStatus(id string) (map[string]interface{}, error)

AutomationStatus gets the status of an automation session.

func (*ResilientClient) AutomationStop

func (rc *ResilientClient) AutomationStop(id string) error

AutomationStop stops an automation session.

func (*ResilientClient) BroadcastActivity

func (rc *ResilientClient) BroadcastActivity(active bool, proxyIDs ...string) error

BroadcastActivity sends an activity state update to connected browsers via specified proxies.

func (*ResilientClient) BroadcastOutputPreview

func (rc *ResilientClient) BroadcastOutputPreview(lines []string, proxyIDs ...string) error

BroadcastOutputPreview sends output preview lines to connected browsers via proxies.

func (*ResilientClient) BrowserList

func (rc *ResilientClient) BrowserList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

BrowserList lists all active browser instances.

func (*ResilientClient) BrowserStart

func (rc *ResilientClient) BrowserStart(config protocol.BrowserStartConfig) (map[string]interface{}, error)

BrowserStart starts a browser instance.

func (*ResilientClient) BrowserStatus

func (rc *ResilientClient) BrowserStatus(id string) (map[string]interface{}, error)

BrowserStatus gets the status of a browser instance.

func (*ResilientClient) BrowserStop

func (rc *ResilientClient) BrowserStop(id string) error

BrowserStop stops a running browser instance.

func (*ResilientClient) ChaosAddRule

func (rc *ResilientClient) ChaosAddRule(proxyID string, rule protocol.ChaosRuleConfig) (map[string]interface{}, error)

ChaosAddRule adds a single rule to a proxy's chaos engine.

func (*ResilientClient) ChaosClear

func (rc *ResilientClient) ChaosClear(proxyID string) (map[string]interface{}, error)

ChaosClear clears all chaos rules and resets stats for a proxy.

func (*ResilientClient) ChaosDisable

func (rc *ResilientClient) ChaosDisable(proxyID string) (map[string]interface{}, error)

ChaosDisable disables chaos injection on a proxy.

func (*ResilientClient) ChaosEnable

func (rc *ResilientClient) ChaosEnable(proxyID string) (map[string]interface{}, error)

ChaosEnable enables chaos injection on a proxy.

func (*ResilientClient) ChaosListPresets

func (rc *ResilientClient) ChaosListPresets() (map[string]interface{}, error)

ChaosListPresets returns the list of available chaos presets.

func (*ResilientClient) ChaosListRules

func (rc *ResilientClient) ChaosListRules(proxyID string) (map[string]interface{}, error)

ChaosListRules lists all chaos rules for a proxy.

func (*ResilientClient) ChaosPreset

func (rc *ResilientClient) ChaosPreset(proxyID, preset string) (map[string]interface{}, error)

ChaosPreset applies a preset chaos configuration to a proxy.

func (*ResilientClient) ChaosRemoveRule

func (rc *ResilientClient) ChaosRemoveRule(proxyID, ruleID string) (map[string]interface{}, error)

ChaosRemoveRule removes a rule from a proxy's chaos engine.

func (*ResilientClient) ChaosSet

func (rc *ResilientClient) ChaosSet(proxyID string, config protocol.ChaosConfigPayload) (map[string]interface{}, error)

ChaosSet sets the full chaos configuration on a proxy.

func (*ResilientClient) ChaosStats

func (rc *ResilientClient) ChaosStats(proxyID string) (map[string]interface{}, error)

ChaosStats gets chaos statistics for a proxy.

func (*ResilientClient) ChaosStatus

func (rc *ResilientClient) ChaosStatus(proxyID string) (map[string]interface{}, error)

ChaosStatus gets the chaos status of a proxy.

func (*ResilientClient) Client

func (rc *ResilientClient) Client() *Client

Client returns the underlying client for direct access. Returns nil if not connected.

func (*ResilientClient) Close

func (rc *ResilientClient) Close() error

Close shuts down the resilient client.

func (*ResilientClient) Connect

func (rc *ResilientClient) Connect() error

Connect establishes the initial connection to the daemon.

func (*ResilientClient) CurrentPageClear

func (rc *ResilientClient) CurrentPageClear(proxyID string) error

CurrentPageClear clears page sessions.

func (*ResilientClient) CurrentPageGet

func (rc *ResilientClient) CurrentPageGet(proxyID, sessionID string) (map[string]interface{}, error)

CurrentPageGet gets details for a specific page session.

func (*ResilientClient) CurrentPageList

func (rc *ResilientClient) CurrentPageList(proxyID string) (map[string]interface{}, error)

CurrentPageList lists active page sessions.

func (*ResilientClient) Detect

func (rc *ResilientClient) Detect(path string) (map[string]interface{}, error)

Detect detects the project type at the given path.

func (*ResilientClient) Doctor

func (rc *ResilientClient) Doctor(projectPath string) (map[string]interface{}, error)

Doctor runs health checks and returns a diagnostic report.

func (*ResilientClient) Info

func (rc *ResilientClient) Info() (*DaemonInfo, error)

Info retrieves daemon information.

func (*ResilientClient) IsConnected

func (rc *ResilientClient) IsConnected() bool

IsConnected returns whether the client is currently connected.

func (*ResilientClient) IsReconnecting

func (rc *ResilientClient) IsReconnecting() bool

IsReconnecting returns whether the client is currently reconnecting.

func (*ResilientClient) OverlaySet

func (rc *ResilientClient) OverlaySet(endpoint string) (map[string]interface{}, error)

OverlaySet sets the overlay endpoint.

func (*ResilientClient) Ping

func (rc *ResilientClient) Ping() error

Ping sends a ping to the daemon.

func (*ResilientClient) ProcAutoRestart

func (rc *ResilientClient) ProcAutoRestart(processID, action string, config *ProcAutoRestartConfig) (map[string]interface{}, error)

ProcAutoRestart enables, disables, or queries auto-restart for a process.

func (*ResilientClient) ProcCleanupPort

func (rc *ResilientClient) ProcCleanupPort(port int) (map[string]interface{}, error)

ProcCleanupPort kills processes on a specific port.

func (*ResilientClient) ProcList

func (rc *ResilientClient) ProcList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

ProcList lists all processes.

func (*ResilientClient) ProcOutput

func (rc *ResilientClient) ProcOutput(processID string, filter protocol.OutputFilter) (string, error)

ProcOutput gets the output of a process.

func (*ResilientClient) ProcRestart

func (rc *ResilientClient) ProcRestart(processID string) (map[string]interface{}, error)

ProcRestart restarts a process.

func (*ResilientClient) ProcStatus

func (rc *ResilientClient) ProcStatus(processID string) (map[string]interface{}, error)

ProcStatus gets the status of a process.

func (*ResilientClient) ProcStop

func (rc *ResilientClient) ProcStop(processID string, force bool) (map[string]interface{}, error)

ProcStop stops a process.

func (*ResilientClient) ProxyExec

func (rc *ResilientClient) ProxyExec(id, code string) (map[string]interface{}, error)

ProxyExec executes JavaScript in connected browsers.

func (*ResilientClient) ProxyList

func (rc *ResilientClient) ProxyList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

ProxyList lists all proxies.

func (*ResilientClient) ProxyLogClear

func (rc *ResilientClient) ProxyLogClear(proxyID string) error

ProxyLogClear clears proxy logs.

func (*ResilientClient) ProxyLogQuery

func (rc *ResilientClient) ProxyLogQuery(proxyID string, filter protocol.LogQueryFilter) (map[string]interface{}, error)

ProxyLogQuery queries proxy logs.

func (*ResilientClient) ProxyLogStats

func (rc *ResilientClient) ProxyLogStats(proxyID string) (map[string]interface{}, error)

ProxyLogStats gets proxy log statistics.

func (*ResilientClient) ProxyRestart

func (rc *ResilientClient) ProxyRestart(id string) (map[string]interface{}, error)

ProxyRestart restarts a proxy.

func (*ResilientClient) ProxyStart

func (rc *ResilientClient) ProxyStart(id, targetURL string, port, maxLogSize int, path string) (map[string]interface{}, error)

ProxyStart starts a reverse proxy.

func (*ResilientClient) ProxyStartWithConfig

func (rc *ResilientClient) ProxyStartWithConfig(id, targetURL string, port, maxLogSize int, config ProxyStartConfig) (map[string]interface{}, error)

ProxyStartWithConfig starts a reverse proxy with extended configuration.

func (*ResilientClient) ProxyStatus

func (rc *ResilientClient) ProxyStatus(id string) (map[string]interface{}, error)

ProxyStatus gets the status of a proxy.

func (*ResilientClient) ProxyStop

func (rc *ResilientClient) ProxyStop(id string) error

ProxyStop stops a reverse proxy.

func (*ResilientClient) ProxyToast

func (rc *ResilientClient) ProxyToast(id string, toast protocol.ToastConfig) (map[string]interface{}, error)

ProxyToast sends a toast notification to connected browsers.

func (*ResilientClient) RestartAll

func (rc *ResilientClient) RestartAll() (map[string]interface{}, error)

RestartAll restarts all processes and proxies.

func (*ResilientClient) Run

func (rc *ResilientClient) Run(config interface{}) (map[string]interface{}, error)

Run starts a process on the daemon.

func (*ResilientClient) ScriptGet

func (rc *ResilientClient) ScriptGet(name, projectPath string) (map[string]interface{}, error)

ScriptGet retrieves full detail for a named script.

func (*ResilientClient) ScriptList

func (rc *ResilientClient) ScriptList(projectPath string) (map[string]interface{}, error)

ScriptList lists all scripts for a project directory.

func (*ResilientClient) ScriptOutput

func (rc *ResilientClient) ScriptOutput(name, projectPath string, tail int) (map[string]interface{}, error)

ScriptOutput retrieves output history for a named script.

func (*ResilientClient) SessionAttach

func (rc *ResilientClient) SessionAttach(directory string) (map[string]interface{}, error)

SessionAttach attaches to a session found by directory ancestry.

func (*ResilientClient) SessionCancel

func (rc *ResilientClient) SessionCancel(taskID string) error

SessionCancel cancels a scheduled task.

func (*ResilientClient) SessionFind

func (rc *ResilientClient) SessionFind(directory string) (map[string]interface{}, error)

SessionFind finds a session by directory ancestry.

func (*ResilientClient) SessionGenerateCode

func (rc *ResilientClient) SessionGenerateCode(command string) (string, error)

SessionGenerateCode generates a unique session code for a command.

func (*ResilientClient) SessionGet

func (rc *ResilientClient) SessionGet(code string) (map[string]interface{}, error)

SessionGet retrieves details for a specific session.

func (*ResilientClient) SessionHeartbeat

func (rc *ResilientClient) SessionHeartbeat(code string) error

SessionHeartbeat sends a heartbeat for a session.

func (*ResilientClient) SessionList

func (rc *ResilientClient) SessionList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

SessionList lists sessions, optionally filtered by directory.

func (*ResilientClient) SessionRegister

func (rc *ResilientClient) SessionRegister(code, overlayPath, projectPath, command string, args []string) (map[string]interface{}, error)

SessionRegister registers a new session with the daemon.

func (*ResilientClient) SessionRegisterWithPGID added in v0.12.41

func (rc *ResilientClient) SessionRegisterWithPGID(code, overlayPath, projectPath, command string, args []string, sessionPGID int) (map[string]interface{}, error)

SessionRegisterWithPGID registers a new session and reports the POSIX process group ID of the PTY child (the session leader). See Client's equivalent method for details.

func (*ResilientClient) SessionSchedule

func (rc *ResilientClient) SessionSchedule(code, duration, message string) (map[string]interface{}, error)

SessionSchedule schedules a message for future delivery.

func (*ResilientClient) SessionSend

func (rc *ResilientClient) SessionSend(code, message string) (map[string]interface{}, error)

SessionSend sends a message to a session immediately.

func (*ResilientClient) SessionTasks

func (rc *ResilientClient) SessionTasks(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

SessionTasks lists scheduled tasks, optionally filtered by directory.

func (*ResilientClient) SessionUnregister

func (rc *ResilientClient) SessionUnregister(code string) error

SessionUnregister unregisters a session.

func (*ResilientClient) StartupLog

func (rc *ResilientClient) StartupLog(limit int) (map[string]interface{}, error)

StartupLog queries the startup log from the daemon.

func (*ResilientClient) Stats

func (rc *ResilientClient) Stats() map[string]interface{}

Stats returns connection statistics.

func (*ResilientClient) StopAll

func (rc *ResilientClient) StopAll() (map[string]interface{}, error)

StopAll stops all processes and proxies.

func (*ResilientClient) StoreClear

func (rc *ResilientClient) StoreClear(req protocol.StoreClearRequest) error

StoreClear clears all entries in a scope.

func (*ResilientClient) StoreDelete

func (rc *ResilientClient) StoreDelete(req protocol.StoreDeleteRequest) error

StoreDelete deletes a value from the key-value store.

func (*ResilientClient) StoreGet

func (rc *ResilientClient) StoreGet(req protocol.StoreGetRequest) (map[string]interface{}, error)

StoreGet retrieves a value from the key-value store.

func (*ResilientClient) StoreGetAll

func (rc *ResilientClient) StoreGetAll(req protocol.StoreGetAllRequest) (map[string]interface{}, error)

StoreGetAll retrieves all key-value pairs in a scope.

func (*ResilientClient) StoreList

func (rc *ResilientClient) StoreList(req protocol.StoreListRequest) (map[string]interface{}, error)

StoreList lists all keys in a scope.

func (*ResilientClient) StoreSet

func (rc *ResilientClient) StoreSet(req protocol.StoreSetRequest) error

StoreSet stores a value in the key-value store.

func (*ResilientClient) TunnelList

func (rc *ResilientClient) TunnelList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

TunnelList lists all active tunnels.

func (*ResilientClient) TunnelStart

func (rc *ResilientClient) TunnelStart(config protocol.TunnelStartConfig) (map[string]interface{}, error)

TunnelStart starts a tunnel for a local port.

func (*ResilientClient) TunnelStatus

func (rc *ResilientClient) TunnelStatus(id string) (map[string]interface{}, error)

TunnelStatus gets the status of a tunnel.

func (*ResilientClient) TunnelStop

func (rc *ResilientClient) TunnelStop(id string) error

TunnelStop stops a running tunnel.

func (*ResilientClient) WithClient

func (rc *ResilientClient) WithClient(fn func(*Client) error) error

WithClient executes a function with the client, handling reconnection.

type ResilientClientConfig

type ResilientClientConfig struct {
	// AutoStartConfig for daemon auto-start
	AutoStartConfig AutoStartConfig

	// HeartbeatInterval is how often to send heartbeats (0 disables)
	HeartbeatInterval time.Duration

	// HeartbeatTimeout is how long to wait for heartbeat response
	HeartbeatTimeout time.Duration

	// ReconnectBackoffMin is the minimum backoff between reconnection attempts
	ReconnectBackoffMin time.Duration

	// ReconnectBackoffMax is the maximum backoff between reconnection attempts
	ReconnectBackoffMax time.Duration

	// MaxReconnectAttempts limits reconnection attempts (0 = unlimited)
	MaxReconnectAttempts int

	// OnReconnect is called after successful reconnection
	OnReconnect ReconnectCallback

	// OnDisconnect is called when connection is lost
	OnDisconnect func(err error)

	// OnReconnectFailed is called when reconnection fails permanently
	OnReconnectFailed func(err error)

	// ClientVersion is the expected daemon version (strict matching).
	// If empty, version checking is skipped.
	ClientVersion string

	// OnVersionMismatch is called when client and daemon versions don't match.
	// If nil and versions mismatch, Connect() returns an error.
	// If non-nil, the callback can handle the mismatch (e.g., trigger upgrade).
	// Return nil to proceed with mismatched versions, or error to fail connection.
	OnVersionMismatch func(clientVer, daemonVer string) error
}

ResilientClientConfig configures a ResilientClient.

func DefaultResilientClientConfig

func DefaultResilientClientConfig() ResilientClientConfig

DefaultResilientClientConfig returns sensible defaults.

type SocketConfig

type SocketConfig struct {
	Path string
	Mode os.FileMode
}

SocketConfig holds configuration for socket management.

func DefaultSocketConfig

func DefaultSocketConfig() SocketConfig

DefaultSocketConfig returns the default socket configuration.

type SocketManager

type SocketManager struct {
	// contains filtered or unexported fields
}

SocketManager handles socket lifecycle.

func NewSocketManager

func NewSocketManager(config SocketConfig) *SocketManager

NewSocketManager creates a new socket manager.

func (*SocketManager) Close

func (sm *SocketManager) Close() error

Close closes the socket and removes files.

func (*SocketManager) Listen

func (sm *SocketManager) Listen() (net.Listener, error)

Listen creates and binds the socket.

func (*SocketManager) Path

func (sm *SocketManager) Path() string

Path returns the socket path.

type TunnelInfo

type TunnelInfo struct {
	Active int64 `json:"active"`
}

TunnelInfo holds tunnel manager statistics.

type UpgradeConfig

type UpgradeConfig struct {
	// SocketPath is the socket path to connect to the daemon.
	// If empty, uses DefaultSocketPath().
	SocketPath string

	// NewBinaryPath is the path to the new daemon binary.
	// If empty, uses the current executable.
	NewBinaryPath string

	// Timeout is the maximum time for the entire upgrade process.
	// Default: 30 seconds.
	Timeout time.Duration

	// GracefulTimeout is the timeout for graceful daemon shutdown.
	// Default: 5 seconds.
	GracefulTimeout time.Duration

	// Force bypasses version checks and performs upgrade even if versions match.
	Force bool

	// Verbose enables detailed logging during upgrade.
	Verbose bool

	// CurrentVersion is the version of the current binary (caller must set).
	// Used when NewBinaryPath is empty to determine the new version.
	CurrentVersion string
}

UpgradeConfig holds configuration for daemon upgrades.

func DefaultUpgradeConfig

func DefaultUpgradeConfig() UpgradeConfig

DefaultUpgradeConfig returns sensible defaults.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL