daemon

package
v0.12.20 Latest Latest
Warning

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

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

Documentation

Overview

Package daemon 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 := daemon.NewConn(socketPath)
defer conn.Close()

statusFetcher := overlay.NewStatusFetcher(conn, overlay)
summarizer := overlay.NewSummarizer(conn, config)
bashRunner := overlay.NewBashRunner(conn)

## 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.

Package daemon provides the background daemon for persistent state management.

Package daemon provides the background daemon for persistent state management.

Package daemon provides the background daemon for persistent state management.

Package daemon provides the stateful daemon process that manages processes, proxies, and traffic logs across client connections.

This file provides socket compatibility layer using go-cli-server/socket.

Package daemon provides the background daemon service.

Index

Constants

View Source
const MaxLogBackups = 3

MaxLogBackups is the number of rotated log files to keep.

View Source
const MaxLogSize = 5 * 1024 * 1024

MaxLogSize is the maximum log file size before rotation (5MB).

View Source
const SchedulerStateDir = ".agnt"

SchedulerStateDir is the directory within each project for agnt state.

View Source
const SchedulerStateFile = "scheduled-tasks.json"

SchedulerStateFile is the name of the per-project task state file.

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 BuildTime = ""

BuildTime is the build timestamp (RFC3339 format). Set at build time with: -ldflags "-X github.com/standardbeagle/agnt/internal/daemon.BuildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)"

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.

View Source
var GitCommit = ""

GitCommit is the git commit hash. Set at build time with: -ldflags "-X github.com/standardbeagle/agnt/internal/daemon.GitCommit=$(git rev-parse HEAD)"

View Source
var Version = "0.12.20"

Version is the daemon version. Can be overridden at build time with: -ldflags "-X github.com/standardbeagle/agnt/internal/daemon.Version=x.y.z"

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 DefaultStatePath

func DefaultStatePath() string

DefaultStatePath returns the default state file path.

func FormatRestartDelimiter added in v0.12.8

func FormatRestartDelimiter(events []RestartEvent) string

FormatRestartDelimiter formats restart events as a delimiter string that can be prepended to process output.

func GetLogPath added in v0.11.1

func GetLogPath() string

GetLogPath returns the path to the daemon log file. Uses XDG_STATE_HOME or ~/.local/state/agnt/daemon.log

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 added in v0.6.6

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

UpgradeDaemon is a convenience function for upgrading the daemon. It creates a DaemonUpgrader with the given config and runs the upgrade.

Types

type AlertEntry added in v0.12.0

type AlertEntry struct {
	PatternID   string    `json:"pattern_id"`
	Severity    string    `json:"severity"`
	Category    string    `json:"category"`
	Description string    `json:"description"`
	Line        string    `json:"line"`
	ScriptID    string    `json:"script_id"`
	Timestamp   time.Time `json:"timestamp"`
}

AlertEntry represents a single alert stored in the daemon.

type AlertHub added in v0.11.5

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

AlertHub routes formatted alert messages to available delivery mechanisms: PTY overlay (stdin injection) and/or MCP session notifications.

func NewAlertHub added in v0.11.5

func NewAlertHub() *AlertHub

NewAlertHub creates a new AlertHub.

func (*AlertHub) AddMCPSink added in v0.11.5

func (h *AlertHub) AddMCPSink(sink MCPAlertSink)

AddMCPSink registers an MCP session for alert delivery.

func (*AlertHub) Deliver added in v0.11.5

func (h *AlertHub) Deliver(severity string, formatted string)

Deliver sends a pre-formatted alert message to all available sinks.

func (*AlertHub) RemoveMCPSink added in v0.11.5

func (h *AlertHub) RemoveMCPSink(sink MCPAlertSink)

RemoveMCPSink unregisters an MCP session sink.

func (*AlertHub) SetOverlaySink added in v0.11.5

func (h *AlertHub) SetOverlaySink(sink OverlayAlertSink)

SetOverlaySink sets the overlay (PTY stdin) delivery sink.

type AlertStoreFilter added in v0.12.0

type AlertStoreFilter struct {
	Since     time.Time
	ProcessID string
	Severity  string
	Limit     int
}

AlertStoreFilter is the daemon-side filter for querying alerts.

type AutoRestartConfig added in v0.11.1

type AutoRestartConfig struct {
	Enabled       bool          // Whether auto-restart is enabled
	MaxRestarts   int           // Max restarts within window (0 = unlimited)
	RestartWindow time.Duration // Time window for restart limit (default 1 minute)
	RestartDelay  time.Duration // Delay before restart (default 1 second)
	OnlyOnError   bool          // Only restart if exit code != 0
}

AutoRestartConfig holds auto-restart settings for a process.

func DefaultAutoRestartConfig added in v0.11.1

func DefaultAutoRestartConfig() AutoRestartConfig

DefaultAutoRestartConfig returns sensible defaults.

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 AutostartResult added in v0.7.8

type AutostartResult struct {
	Scripts []string `json:"scripts,omitempty"`
	Proxies []string `json:"proxies,omitempty"`
	Errors  []string `json:"errors,omitempty"`
}

AutostartResult holds the results of an autostart operation.

type BrowserInfo added in v0.11.1

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 added in v0.8.0

func NewClientWithPath(socketPath string) *Client

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

func (*Client) AlertClear added in v0.12.0

func (c *Client) AlertClear() error

AlertClear clears all alerts from the daemon.

func (*Client) AlertQuery added in v0.12.0

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

AlertQuery queries alerts from the daemon.

func (*Client) AlertReport added in v0.12.0

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

AlertReport sends an alert report to the daemon.

func (*Client) AutomationEvaluate added in v0.11.1

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

AutomationEvaluate evaluates JavaScript in an automation session.

func (*Client) AutomationList added in v0.11.1

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

AutomationList lists all active automation sessions.

func (*Client) AutomationNavigate added in v0.11.1

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

AutomationNavigate navigates to a URL in an automation session.

func (*Client) AutomationScreenshot added in v0.11.1

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

AutomationScreenshot takes a screenshot in an automation session.

func (*Client) AutomationStart added in v0.11.1

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

AutomationStart starts a chromedp automation session.

func (*Client) AutomationStatus added in v0.11.1

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

AutomationStatus gets the status of an automation session.

func (*Client) AutomationStop added in v0.11.1

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

AutomationStop stops an automation session.

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 added in v0.8.0

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

BroadcastOutputPreview broadcasts output preview lines to connected browsers via proxies.

func (*Client) BrowserList added in v0.11.1

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

BrowserList lists all active browser instances.

func (*Client) BrowserStart added in v0.11.1

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

BrowserStart starts a browser instance.

func (*Client) BrowserStatus added in v0.11.1

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

BrowserStatus gets the status of a browser instance.

func (*Client) BrowserStop added in v0.11.1

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) 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 STATUS is 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 added in v0.11.1

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

ProcAutoRestart enables, disables, or queries auto-restart for a process. action can be "enable", "disable", or "status".

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 added in v0.8.0

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 added in v0.8.0

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) RestartAll added in v0.8.0

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 added in v0.12.16

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

ScriptGet retrieves full detail for a named script.

func (*Client) ScriptList added in v0.12.16

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

ScriptList lists all scripts for a project directory.

func (*Client) ScriptOutput added in v0.12.16

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

ScriptOutput retrieves output history for a named script.

func (*Client) ScriptRestart added in v0.12.16

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

ScriptRestart restarts a script by name.

func (*Client) ScriptStop added in v0.12.16

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

ScriptStop stops a script by name.

func (*Client) SessionAttach added in v0.7.12

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

SessionAttach attaches to a session found by directory ancestry.

func (*Client) SessionCancel added in v0.7.0

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

SessionCancel cancels a scheduled task.

func (*Client) SessionFind added in v0.7.12

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

SessionFind finds a session by directory ancestry.

func (*Client) SessionGenerateCode added in v0.7.0

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

SessionGenerateCode requests a new session code from the daemon.

func (*Client) SessionGet added in v0.7.0

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

SessionGet retrieves a specific session.

func (*Client) SessionHeartbeat added in v0.7.0

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

SessionHeartbeat sends a heartbeat for a session.

func (*Client) SessionList added in v0.7.0

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

SessionList lists active sessions.

func (*Client) SessionRegister added in v0.7.0

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) SessionSchedule added in v0.7.0

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

SessionSchedule schedules a message for future delivery.

func (*Client) SessionSend added in v0.7.0

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

SessionSend sends an immediate message to a session.

func (*Client) SessionTasks added in v0.7.0

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

SessionTasks lists scheduled tasks.

func (*Client) SessionURL added in v0.8.0

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

SessionURL reports a detected URL from an agnt run session. This triggers proxy creation for any matching proxy configurations.

func (*Client) SessionUnregister added in v0.7.0

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 added in v0.8.0

func (c *Client) SocketPath() string

SocketPath returns the socket path.

func (*Client) StartupLog added in v0.12.15

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

StartupLog queries the startup log from the daemon.

func (*Client) StopAll added in v0.8.0

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

StopAll stops all running processes, proxies, and tunnels.

func (*Client) StoreClear added in v0.8.0

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

StoreClear clears all entries in a scope.

func (*Client) StoreDelete added in v0.8.0

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

StoreDelete deletes a value from the key-value store.

func (*Client) StoreGet added in v0.8.0

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

StoreGet retrieves a value from the key-value store.

func (*Client) StoreGetAll added in v0.8.0

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

StoreGetAll retrieves all key-value pairs in a scope.

func (*Client) StoreList added in v0.8.0

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

StoreList lists all keys in a scope.

func (*Client) StoreSet added in v0.8.0

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

StoreSet stores a value in the key-value store.

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 added in v0.7.8

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 added in v0.7.8

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 added in v0.7.8

func (c *Conn) Close() error

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

func (*Conn) Disconnect added in v0.7.8

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 added in v0.7.8

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 added in v0.7.8

func (c *Conn) IsConnected() bool

IsConnected returns whether the connection is currently established.

func (*Conn) Ping added in v0.7.8

func (c *Conn) Ping() error

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

func (*Conn) Request added in v0.7.8

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

Request creates a new request builder for the given verb and arguments. The verb is the protocol command (e.g., "PROC", "PROXY", "PROXYLOG"). Additional arguments are appended (e.g., "LIST", "STATUS", process ID).

Example:

conn.Request("PROC", "LIST")
conn.Request("PROC", "STATUS", processID)
conn.Request("PROXY", "START", id, targetURL, port)

func (*Conn) SetTimeout added in v0.7.8

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

SetTimeout sets the default timeout for operations.

func (*Conn) SocketPath added in v0.7.8

func (c *Conn) SocketPath() string

SocketPath returns the configured socket path.

type Daemon

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

Daemon is the main daemon process that manages state across client connections. The daemon is built on top of go-cli-server Hub, which owns the ProcessManager and handles session/client lifecycle. Daemon adds agnt-specific functionality: proxy management, tunnel management, URL tracking, and scheduling.

func New

func New(config DaemonConfig) *Daemon

New creates a new daemon instance.

func (*Daemon) AlertStore added in v0.12.0

func (d *Daemon) AlertStore() *ProcessAlertStore

AlertStore returns the process alert store.

func (*Daemon) AutoRestarter added in v0.11.1

func (d *Daemon) AutoRestarter() *ProcessAutoRestarter

AutoRestarter returns the process auto-restart manager.

func (*Daemon) BrowserManager added in v0.11.1

func (d *Daemon) BrowserManager() *browser.Manager

BrowserManager returns the browser manager.

func (*Daemon) CleanupSessionResources added in v0.7.8

func (d *Daemon) CleanupSessionResources(sessionCode string)

CleanupSessionResources stops all processes and proxies for a specific session. This is called when a connection that registered a session disconnects.

func (*Daemon) FlushScriptProxyConnections added in v0.12.8

func (d *Daemon) FlushScriptProxyConnections(scriptID string)

FlushScriptProxyConnections closes idle connections on all proxies linked to a script. Call this when a backend process restarts to avoid stale connection errors.

func (*Daemon) GetSession added in v0.7.0

func (d *Daemon) GetSession(code string) (*Session, bool)

GetSession retrieves a session by code.

func (*Daemon) Info

func (d *Daemon) Info() DaemonInfo

Info returns daemon information.

func (*Daemon) LoadURLMatchersForProcess added in v0.8.0

func (d *Daemon) LoadURLMatchersForProcess(processID string)

LoadURLMatchersForProcess loads URL matchers from agnt.kdl for a process and sets them on the URL tracker. Process ID format: {basename}:{scriptName} (e.g., "my-project:dev") The project path is retrieved from the process's ProjectPath field.

func (*Daemon) OverlayEndpoint

func (d *Daemon) OverlayEndpoint() string

OverlayEndpoint returns the current overlay endpoint URL, or empty string if not set.

func (*Daemon) ProcessManager

func (d *Daemon) ProcessManager() *process.ProcessManager

ProcessManager returns the process manager.

func (*Daemon) ProxyManager

func (d *Daemon) ProxyManager() *proxy.ProxyManager

ProxyManager returns the proxy manager.

func (*Daemon) RunAutostart added in v0.7.8

func (d *Daemon) RunAutostart(ctx context.Context, projectPath string) *AutostartResult

RunAutostart loads .agnt.kdl config from projectPath and starts configured processes/proxies. This is called during SESSION REGISTER to ensure autostart happens once per project. Scripts are started in dependency order using topological sort:

  • Layer 0 scripts (no dependencies) start concurrently
  • Layer 1+ scripts wait for all their dependencies to become ready
  • Readiness is signaled by URL detection or TCP port probe
  • Timeout on dependency wait logs a warning and starts the script anyway

Returns the list of started scripts/proxies and any errors encountered.

func (*Daemon) Scheduler added in v0.7.0

func (d *Daemon) Scheduler() *Scheduler

Scheduler returns the message scheduler.

func (*Daemon) ScriptRegistry added in v0.12.16

func (d *Daemon) ScriptRegistry() *script.Registry

ScriptRegistry returns the script registry.

func (*Daemon) SessionManager added in v0.11.1

func (d *Daemon) SessionManager() *chromedp.SessionManager

SessionManager returns the chromedp session manager.

func (*Daemon) SessionRegistry added in v0.7.0

func (d *Daemon) SessionRegistry() *SessionRegistry

SessionRegistry returns the session registry.

func (*Daemon) SetOverlayEndpoint

func (d *Daemon) SetOverlayEndpoint(endpoint string)

SetOverlayEndpoint sets the overlay endpoint URL and updates all existing proxies. The endpoint should be the full URL, e.g., "http://127.0.0.1:19191". Pass an empty string to disable overlay forwarding.

func (*Daemon) Start

func (d *Daemon) Start() error

Start starts the daemon and begins accepting connections.

func (*Daemon) StartScript added in v0.11.1

func (d *Daemon) StartScript(ctx context.Context, cfg StartScriptConfig) (*StartScriptResult, error)

StartScript starts a script/process with unified behavior: - Pre-flight port cleanup and EADDRINUSE recovery - URL matcher setup for proxy auto-creation - Auto-restart registration for crash recovery

This is the canonical way to start processes in the daemon. Both autostartScript and hub handlers should use this.

func (*Daemon) StartupLogStore added in v0.12.15

func (d *Daemon) StartupLogStore() *StartupLogStore

StartupLogStore returns the startup log store.

func (*Daemon) StateManager

func (d *Daemon) StateManager() *StateManager

StateManager returns the state manager (may be nil if persistence is disabled).

func (*Daemon) Stop

func (d *Daemon) Stop(ctx context.Context) error

Stop gracefully shuts down the daemon.

func (*Daemon) StopAllResources added in v0.7.6

func (d *Daemon) StopAllResources(ctx context.Context)

StopAllResources stops all processes, proxies, and tunnels without shutting down the daemon. Unlike Shutdown, this does NOT prevent new resources from being created afterward. This is typically called explicitly via the daemon management tool, not automatically.

func (*Daemon) TunnelManager

func (d *Daemon) TunnelManager() *tunnel.Manager

TunnelManager returns the tunnel manager.

func (*Daemon) Wait

func (d *Daemon) Wait()

Wait blocks until the daemon stops.

type DaemonConfig

type DaemonConfig struct {
	// Socket configuration
	SocketPath string

	// Process manager configuration
	ProcessConfig process.ManagerConfig

	// Max concurrent clients (0 = unlimited)
	MaxClients int

	// Connection read timeout (0 = no timeout)
	ReadTimeout time.Duration

	// Connection write timeout (0 = no timeout)
	WriteTimeout time.Duration

	// OverlayEndpoint is the URL of the agnt overlay server for forwarding events.
	// Example: "http://127.0.0.1:19191"
	// When set, proxies will forward panel messages, sketches, etc. to the overlay.
	OverlayEndpoint string

	// EnableStatePersistence enables persisting proxy configs for recovery.
	EnableStatePersistence bool

	// StatePath is the path to the state file.
	// If empty, uses default location.
	StatePath string

	// EnableUpdateCheck enables periodic update checking.
	// Default: true
	EnableUpdateCheck bool

	// UpdateCheckInterval is the interval between update checks.
	// Default: 24 hours
	UpdateCheckInterval time.Duration
}

DaemonConfig holds configuration for the daemon.

func DefaultDaemonConfig

func DefaultDaemonConfig() DaemonConfig

DefaultDaemonConfig returns sensible defaults.

type DaemonInfo

type DaemonInfo struct {
	Version       string              `json:"version"`
	BuildTime     string              `json:"build_time,omitempty"` // Build timestamp (RFC3339)
	GitCommit     string              `json:"git_commit,omitempty"` // Git commit hash
	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   SessionInfo         `json:"session_info"`
	SchedulerInfo SchedulerInfo       `json:"scheduler_info"`
	UpdateInfo    *updater.UpdateInfo `json:"update_info,omitempty"` // Update availability info
}

DaemonInfo holds daemon status information.

type DaemonUpgrader added in v0.6.6

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

DaemonUpgrader handles atomic daemon upgrades with locking.

func NewDaemonUpgrader added in v0.6.6

func NewDaemonUpgrader(config UpgradeConfig) *DaemonUpgrader

NewDaemonUpgrader creates a new daemon upgrader.

func (*DaemonUpgrader) Upgrade added in v0.6.6

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 MCPAlertSink added in v0.11.5

type MCPAlertSink interface {
	SendAlert(level string, message string) error
}

MCPAlertSink delivers alert messages via MCP session notifications.

type OverlayAlertSink added in v0.11.5

type OverlayAlertSink interface {
	TypeAlert(text string) error
	IsEnabled() bool
}

OverlayAlertSink delivers alert messages via PTY stdin injection.

type PersistedTaskState added in v0.7.0

type PersistedTaskState struct {
	Version   int              `json:"version"`
	Tasks     []*ScheduledTask `json:"tasks"`
	UpdatedAt string           `json:"updated_at"`
}

PersistedTaskState represents the structure of the task state file.

type PersistentProxyConfig

type PersistentProxyConfig struct {
	ID         string `json:"id"`
	TargetURL  string `json:"target_url"`
	Port       int    `json:"port"`
	MaxLogSize int    `json:"max_log_size"`
	Path       string `json:"path"`
	CreatedAt  string `json:"created_at"`
}

PersistentProxyConfig stores the configuration needed to recreate a proxy.

type PersistentState

type PersistentState struct {
	Version         int                     `json:"version"`
	OverlayEndpoint string                  `json:"overlay_endpoint,omitempty"`
	Proxies         []PersistentProxyConfig `json:"proxies,omitempty"`
	UpdatedAt       string                  `json:"updated_at"`
}

PersistentState stores daemon state that should survive restarts.

type ProcAutoRestartConfig added in v0.11.1

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 ProcessAlertStore added in v0.12.0

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

ProcessAlertStore is a ring buffer store for alert entries. head points to the oldest entry; new entries are written at (head+len) % maxSize.

func NewProcessAlertStore added in v0.12.0

func NewProcessAlertStore(maxSize int) *ProcessAlertStore

NewProcessAlertStore creates a new alert store with the given capacity.

func (*ProcessAlertStore) Add added in v0.12.0

func (s *ProcessAlertStore) Add(entry *AlertEntry)

Add inserts an alert entry into the ring buffer.

func (*ProcessAlertStore) Clear added in v0.12.0

func (s *ProcessAlertStore) Clear()

Clear resets the buffer.

func (*ProcessAlertStore) Len added in v0.12.0

func (s *ProcessAlertStore) Len() int

Len returns the current number of entries.

func (*ProcessAlertStore) Query added in v0.12.0

func (s *ProcessAlertStore) Query(filter AlertStoreFilter) []*AlertEntry

Query returns entries matching the filter, oldest-to-newest.

type ProcessAutoRestarter added in v0.11.1

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

ProcessAutoRestarter manages auto-restart for processes.

func NewProcessAutoRestarter added in v0.11.1

func NewProcessAutoRestarter(d *Daemon) *ProcessAutoRestarter

NewProcessAutoRestarter creates a new auto-restarter.

func (*ProcessAutoRestarter) GetConfig added in v0.11.1

func (r *ProcessAutoRestarter) GetConfig(processID string) (AutoRestartConfig, bool)

GetConfig returns the auto-restart config for a process.

func (*ProcessAutoRestarter) GetRestartEvents added in v0.12.8

func (r *ProcessAutoRestarter) GetRestartEvents(processID string) []RestartEvent

GetRestartEvents returns restart event history for a process. Returns nil if the process is not registered or has no restart events.

func (*ProcessAutoRestarter) IsRegistered added in v0.11.1

func (r *ProcessAutoRestarter) IsRegistered(processID string) bool

IsRegistered checks if a process has auto-restart enabled.

func (*ProcessAutoRestarter) Register added in v0.11.1

func (r *ProcessAutoRestarter) Register(processID string, config AutoRestartConfig, command string, args []string, projectPath, workingDir string)

Register enables auto-restart for a process.

func (*ProcessAutoRestarter) Shutdown added in v0.11.1

func (r *ProcessAutoRestarter) Shutdown(ctx context.Context)

Shutdown stops all monitoring goroutines. The provided context bounds how long Shutdown will wait for monitor goroutines to finish. If ctx expires, Shutdown returns immediately (goroutines are still cancelled via r.cancel but may not have exited yet).

func (*ProcessAutoRestarter) Stats added in v0.11.1

func (r *ProcessAutoRestarter) Stats() map[string]interface{}

Stats returns auto-restart statistics.

func (*ProcessAutoRestarter) Unregister added in v0.11.1

func (r *ProcessAutoRestarter) Unregister(processID string)

Unregister disables auto-restart for a process.

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 ProxyEvent added in v0.8.0

type ProxyEvent struct {
	Type     ProxyEventType
	ScriptID string // Process/script ID that triggered the event
	URL      string // Detected URL (for URLDetected events)
	ProxyID  string // Specific proxy ID (for ExplicitStart events)
	Config   *config.ProxyConfig
	Path     string // Project path
}

ProxyEvent represents an event that triggers proxy creation or cleanup.

type ProxyEventType added in v0.8.0

type ProxyEventType int

ProxyEventType represents the type of proxy event.

const (
	// URLDetected indicates a URL was detected from script output
	URLDetected ProxyEventType = iota
	// ExplicitStart indicates a proxy should start with explicit config
	ExplicitStart
	// ScriptStopped indicates a script stopped and its proxies should be cleaned up
	ScriptStopped
)

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 ReadySignaler added in v0.12.8

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

ReadySignaler manages per-process readiness channels. It provides a coordination primitive for waiting until a process (or its port) is ready.

func NewReadySignaler added in v0.12.8

func NewReadySignaler() *ReadySignaler

NewReadySignaler creates a new ReadySignaler.

func (*ReadySignaler) Cleanup added in v0.12.8

func (rs *ReadySignaler) Cleanup(processID string)

Cleanup removes the signal channel and stops any running port probe for processID.

func (*ReadySignaler) GetOrCreate added in v0.12.8

func (rs *ReadySignaler) GetOrCreate(processID string) chan struct{}

GetOrCreate returns the signal channel for processID, creating one if needed.

func (*ReadySignaler) SignalReady added in v0.12.8

func (rs *ReadySignaler) SignalReady(processID string)

SignalReady marks processID as ready by closing its channel. This is idempotent: calling it multiple times is safe and has no effect after the first call.

func (*ReadySignaler) StartPortProbe added in v0.12.8

func (rs *ReadySignaler) StartPortProbe(processID string, port int, ctx context.Context)

StartPortProbe launches a goroutine that polls TCP connect on localhost:port every 500ms. When the port accepts a connection, it calls SignalReady. The probe stops when ctx is cancelled or the port is reached.

func (*ReadySignaler) WaitReady added in v0.12.8

func (rs *ReadySignaler) WaitReady(processID string, timeout time.Duration) error

WaitReady blocks until processID is signaled ready or the timeout elapses. Returns nil if ready, or an error on timeout.

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 added in v0.7.8

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 added in v0.7.8

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

Bytes executes the request and returns the raw JSON response bytes. Use this when you need to handle JSON parsing yourself.

func (*RequestBuilder) Chunked added in v0.7.8

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

Chunked executes the request and collects chunked response data. Use this for commands that return large data (e.g., process output).

data, err := conn.Request("PROC", "OUTPUT", id).WithArgs("tail=100").Chunked()

func (*RequestBuilder) JSON added in v0.7.8

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

JSON executes the request and returns the response as a map. Most daemon commands return JSON responses.

result, err := conn.Request("PROC", "LIST").JSON()
processes := result["processes"].([]interface{})

func (*RequestBuilder) JSONInto added in v0.7.8

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

JSONInto executes the request and unmarshals the response into v.

var info DaemonInfo
err := conn.Request("INFO").JSONInto(&info)

func (*RequestBuilder) OK added in v0.7.8

func (r *RequestBuilder) OK() error

OK executes the request and returns nil on success. Use this for commands that return OK/ERR without data.

err := conn.Request("PROXY", "STOP", proxyID).OK()

func (*RequestBuilder) String added in v0.7.8

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

String executes the request with chunked response and returns as string. Convenience wrapper around Chunked() for text output.

output, err := conn.Request("PROC", "OUTPUT", id).String()

func (*RequestBuilder) WithArgs added in v0.7.8

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

WithArgs appends additional string arguments to the request.

conn.Request("PROC", "OUTPUT", id).WithArgs("tail=50", "stream=stderr")

func (*RequestBuilder) WithData added in v0.7.8

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

WithData sets the request payload as raw bytes.

func (*RequestBuilder) WithJSON added in v0.7.8

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

WithJSON marshals the value as JSON and sets it as the request payload. If marshaling fails, the error is deferred until execution.

conn.Request("PROC", "LIST").WithJSON(protocol.DirectoryFilter{Global: true})

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 added in v0.12.0

func (rc *ResilientClient) AlertClear() error

AlertClear clears all alerts from the daemon.

func (*ResilientClient) AlertQuery added in v0.12.0

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

AlertQuery queries alerts from the daemon.

func (*ResilientClient) AlertReport added in v0.12.0

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

AlertReport sends an alert report to the daemon.

func (*ResilientClient) AutomationEvaluate added in v0.11.1

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

AutomationEvaluate evaluates JavaScript in an automation session.

func (*ResilientClient) AutomationList added in v0.11.1

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

AutomationList lists all active automation sessions.

func (*ResilientClient) AutomationNavigate added in v0.11.1

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

AutomationNavigate navigates to a URL in an automation session.

func (*ResilientClient) AutomationScreenshot added in v0.11.1

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

AutomationScreenshot takes a screenshot in an automation session.

func (*ResilientClient) AutomationStart added in v0.11.1

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

AutomationStart starts a chromedp automation session.

func (*ResilientClient) AutomationStatus added in v0.11.1

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

AutomationStatus gets the status of an automation session.

func (*ResilientClient) AutomationStop added in v0.11.1

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. If proxyIDs is empty, broadcasts to all proxies (backward compatibility).

func (*ResilientClient) BroadcastOutputPreview added in v0.8.0

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

BroadcastOutputPreview sends output preview lines to connected browsers via proxies.

func (*ResilientClient) BrowserList added in v0.11.1

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

BrowserList lists all active browser instances.

func (*ResilientClient) BrowserStart added in v0.11.1

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

BrowserStart starts a browser instance.

func (*ResilientClient) BrowserStatus added in v0.11.1

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

BrowserStatus gets the status of a browser instance.

func (*ResilientClient) BrowserStop added in v0.11.1

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

BrowserStop stops a running browser instance.

func (*ResilientClient) ChaosAddRule added in v0.6.6

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 added in v0.6.6

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

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

func (*ResilientClient) ChaosDisable added in v0.6.6

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

ChaosDisable disables chaos injection on a proxy.

func (*ResilientClient) ChaosEnable added in v0.6.6

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

ChaosEnable enables chaos injection on a proxy.

func (*ResilientClient) ChaosListPresets added in v0.6.6

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

ChaosListPresets returns the list of available chaos presets.

func (*ResilientClient) ChaosListRules added in v0.6.6

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

ChaosListRules lists all chaos rules for a proxy.

func (*ResilientClient) ChaosPreset added in v0.6.6

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

ChaosPreset applies a preset chaos configuration to a proxy.

func (*ResilientClient) ChaosRemoveRule added in v0.6.6

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

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

func (*ResilientClient) ChaosSet added in v0.6.6

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 added in v0.6.6

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

ChaosStats gets chaos statistics for a proxy.

func (*ResilientClient) ChaosStatus added in v0.6.6

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 added in v0.6.6

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

CurrentPageClear clears page sessions.

func (*ResilientClient) CurrentPageGet added in v0.6.6

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

CurrentPageGet gets details for a specific page session.

func (*ResilientClient) CurrentPageList added in v0.6.6

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

CurrentPageList lists active page sessions.

func (*ResilientClient) Detect added in v0.6.6

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

Detect detects the project type at the given path.

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 added in v0.11.1

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 added in v0.6.6

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

ProcCleanupPort kills processes on a specific port.

func (*ResilientClient) ProcList added in v0.6.6

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

ProcList lists all processes.

func (*ResilientClient) ProcOutput added in v0.6.6

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

ProcOutput gets the output of a process.

func (*ResilientClient) ProcRestart added in v0.8.0

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

ProcRestart restarts a process.

func (*ResilientClient) ProcStatus added in v0.6.6

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

ProcStatus gets the status of a process.

func (*ResilientClient) ProcStop added in v0.6.6

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

ProcStop stops a process.

func (*ResilientClient) ProxyExec added in v0.6.6

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 added in v0.6.6

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

ProxyLogClear clears proxy logs.

func (*ResilientClient) ProxyLogQuery added in v0.6.6

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

ProxyLogQuery queries proxy logs.

func (*ResilientClient) ProxyLogStats added in v0.6.6

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

ProxyLogStats gets proxy log statistics.

func (*ResilientClient) ProxyRestart added in v0.8.0

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 added in v0.6.6

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 added in v0.6.6

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 added in v0.6.6

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

ProxyToast sends a toast notification to connected browsers.

func (*ResilientClient) RestartAll added in v0.8.0

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

RestartAll restarts all processes and proxies.

func (*ResilientClient) Run added in v0.6.6

func (rc *ResilientClient) 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 (*ResilientClient) ScriptGet added in v0.12.16

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

ScriptGet retrieves full detail for a named script.

func (*ResilientClient) ScriptList added in v0.12.16

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

ScriptList lists all scripts for a project directory.

func (*ResilientClient) ScriptOutput added in v0.12.16

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

ScriptOutput retrieves output history for a named script.

func (*ResilientClient) SessionAttach added in v0.7.12

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

SessionAttach attaches to a session found by directory ancestry.

func (*ResilientClient) SessionCancel added in v0.7.0

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

SessionCancel cancels a scheduled task.

func (*ResilientClient) SessionFind added in v0.7.12

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

SessionFind finds a session by directory ancestry.

func (*ResilientClient) SessionGenerateCode added in v0.7.0

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

SessionGenerateCode generates a unique session code for a command.

func (*ResilientClient) SessionGet added in v0.7.0

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

SessionGet retrieves details for a specific session.

func (*ResilientClient) SessionHeartbeat added in v0.7.0

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

SessionHeartbeat sends a heartbeat for a session.

func (*ResilientClient) SessionList added in v0.7.0

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

SessionList lists sessions, optionally filtered by directory.

func (*ResilientClient) SessionRegister added in v0.7.0

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) SessionSchedule added in v0.7.0

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

SessionSchedule schedules a message for future delivery.

func (*ResilientClient) SessionSend added in v0.7.0

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

SessionSend sends a message to a session immediately.

func (*ResilientClient) SessionTasks added in v0.7.0

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

SessionTasks lists scheduled tasks, optionally filtered by directory.

func (*ResilientClient) SessionUnregister added in v0.7.0

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

SessionUnregister unregisters a session.

func (*ResilientClient) StartupLog added in v0.12.15

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 added in v0.8.0

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

StopAll stops all processes and proxies.

func (*ResilientClient) StoreClear added in v0.8.0

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

StoreClear clears all entries in a scope.

func (*ResilientClient) StoreDelete added in v0.8.0

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

StoreDelete deletes a value from the key-value store.

func (*ResilientClient) StoreGet added in v0.8.0

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

StoreGet retrieves a value from the key-value store.

func (*ResilientClient) StoreGetAll added in v0.8.0

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

StoreGetAll retrieves all key-value pairs in a scope.

func (*ResilientClient) StoreList added in v0.8.0

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

StoreList lists all keys in a scope.

func (*ResilientClient) StoreSet added in v0.8.0

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

StoreSet stores a value in the key-value store.

func (*ResilientClient) TunnelList added in v0.6.6

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

TunnelList lists all active tunnels.

func (*ResilientClient) TunnelStart added in v0.6.6

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

TunnelStart starts a tunnel for a local port.

func (*ResilientClient) TunnelStatus added in v0.6.6

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

TunnelStatus gets the status of a tunnel.

func (*ResilientClient) TunnelStop added in v0.6.6

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 RestartEvent added in v0.12.8

type RestartEvent struct {
	Timestamp  time.Time     // When the restart occurred
	ExitCode   int           // Exit code of the failed process
	Runtime    time.Duration // How long the process ran before failing
	LastOutput string        // Last N lines of output before crash
}

RestartEvent captures information about a process restart for output display.

type RogueProcessInfo added in v0.10.0

type RogueProcessInfo struct {
	Port       int   // The port being used
	PIDs       []int // PIDs of processes using the port
	IsManaged  bool  // Whether any of the PIDs are managed by agnt
	HasWarning bool  // Whether to show warning
}

RogueProcessInfo contains information about a detected rogue process.

type ScheduledTask added in v0.7.0

type ScheduledTask struct {
	ID          string    `json:"id"`           // Unique task ID (e.g., "task-abc123")
	SessionCode string    `json:"session_code"` // Target session
	Message     string    `json:"message"`      // Message to deliver
	DeliverAt   time.Time `json:"deliver_at"`   // Scheduled delivery time
	CreatedAt   time.Time `json:"created_at"`   // When task was created
	ProjectPath string    `json:"project_path"` // For project-scoped filtering
	// contains filtered or unexported fields
}

ScheduledTask represents a message scheduled for future delivery. All mutable fields use atomic operations for lock-free concurrent access.

func NewScheduledTask added in v0.12.0

func NewScheduledTask(id, sessionCode, message, projectPath string, deliverAt, createdAt time.Time, status TaskStatus) *ScheduledTask

NewScheduledTask creates a ScheduledTask with the given initial status.

func (*ScheduledTask) Attempts added in v0.7.0

func (t *ScheduledTask) Attempts() int

Attempts returns the current attempt count.

func (*ScheduledTask) CompareAndSwapStatus added in v0.12.0

func (t *ScheduledTask) CompareAndSwapStatus(old, new taskStatus) bool

CompareAndSwapStatus atomically transitions from old to new status. Returns true if the swap succeeded.

func (*ScheduledTask) IncrementAttempts added in v0.12.0

func (t *ScheduledTask) IncrementAttempts() int

IncrementAttempts atomically increments and returns the new attempt count.

func (*ScheduledTask) LastError added in v0.7.0

func (t *ScheduledTask) LastError() string

LastError returns the last error message.

func (*ScheduledTask) MarshalJSON added in v0.12.0

func (t *ScheduledTask) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for atomic-safe serialization.

func (*ScheduledTask) SetLastError added in v0.12.0

func (t *ScheduledTask) SetLastError(err string)

SetLastError sets the last error message.

func (*ScheduledTask) SetStatus added in v0.12.0

func (t *ScheduledTask) SetStatus(s TaskStatus)

SetStatus sets the task status.

func (*ScheduledTask) Status added in v0.7.0

func (t *ScheduledTask) Status() TaskStatus

Status returns the current task status as a string.

func (*ScheduledTask) ToJSON added in v0.7.0

func (t *ScheduledTask) ToJSON() map[string]interface{}

ToJSON returns the task as a JSON-serializable map.

func (*ScheduledTask) UnmarshalJSON added in v0.12.0

func (t *ScheduledTask) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for atomic-safe deserialization.

type Scheduler added in v0.7.0

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

Scheduler manages scheduled message delivery.

func NewScheduler added in v0.7.0

func NewScheduler(config SchedulerConfig, registry *SessionRegistry, stateMgr *SchedulerStateManager) *Scheduler

NewScheduler creates a new scheduler.

func (*Scheduler) Cancel added in v0.7.0

func (s *Scheduler) Cancel(taskID string) error

Cancel cancels a scheduled task. Uses atomic CAS to prevent races with concurrent delivery.

func (*Scheduler) GetTask added in v0.7.0

func (s *Scheduler) GetTask(taskID string) (*ScheduledTask, bool)

GetTask retrieves a task by ID.

func (*Scheduler) Info added in v0.7.0

func (s *Scheduler) Info() SchedulerInfo

Info returns statistics about the scheduler.

func (*Scheduler) ListPendingTasks added in v0.7.0

func (s *Scheduler) ListPendingTasks(projectPath string, global bool) []*ScheduledTask

ListPendingTasks returns only pending tasks.

func (*Scheduler) ListTasks added in v0.7.0

func (s *Scheduler) ListTasks(projectPath string, global bool) []*ScheduledTask

ListTasks returns all tasks, optionally filtered by project path.

func (*Scheduler) Schedule added in v0.7.0

func (s *Scheduler) Schedule(sessionCode string, duration time.Duration, message string, projectPath string) (*ScheduledTask, error)

Schedule adds a new task to the scheduler.

func (*Scheduler) Start added in v0.7.0

func (s *Scheduler) Start(ctx context.Context) error

Start begins the scheduler's tick loop.

func (*Scheduler) Stop added in v0.7.0

func (s *Scheduler) Stop(ctx context.Context)

Stop stops the scheduler. The provided context bounds how long Stop will wait for in-flight delivery goroutines to finish. If ctx expires, Stop returns immediately (goroutines are still cancelled via s.cancel but may not have exited yet).

type SchedulerConfig added in v0.7.0

type SchedulerConfig struct {
	// TickInterval is how often the scheduler checks for due tasks.
	TickInterval time.Duration
	// MaxRetries is the maximum number of delivery attempts.
	MaxRetries int
	// RetryDelay is the base delay between retries (exponential backoff).
	RetryDelay time.Duration
	// DeliveryTimeout is the timeout for each delivery attempt.
	DeliveryTimeout time.Duration
	// MaxConcurrentDeliveries limits simultaneous delivery goroutines.
	// Default: 10
	MaxConcurrentDeliveries int64
}

SchedulerConfig configures the scheduler.

func DefaultSchedulerConfig added in v0.7.0

func DefaultSchedulerConfig() SchedulerConfig

DefaultSchedulerConfig returns sensible defaults.

type SchedulerInfo added in v0.7.0

type SchedulerInfo struct {
	TotalScheduled int64 `json:"total_scheduled"`
	TotalDelivered int64 `json:"total_delivered"`
	TotalFailed    int64 `json:"total_failed"`
	TotalCancelled int64 `json:"total_cancelled"`
	PendingCount   int64 `json:"pending_count"`
}

SchedulerInfo contains statistics about the scheduler.

type SchedulerStateManager added in v0.7.0

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

SchedulerStateManager handles persisting scheduled tasks per-project.

func NewSchedulerStateManager added in v0.7.0

func NewSchedulerStateManager() *SchedulerStateManager

NewSchedulerStateManager creates a new scheduler state manager.

func (*SchedulerStateManager) ClearProject added in v0.7.0

func (m *SchedulerStateManager) ClearProject(projectPath string) error

ClearProject removes all tasks for a project.

func (*SchedulerStateManager) ListProjectsWithTasks added in v0.7.0

func (m *SchedulerStateManager) ListProjectsWithTasks() []string

ListProjectsWithTasks returns all known project directories with tasks.

func (*SchedulerStateManager) LoadAllTasks added in v0.7.0

func (m *SchedulerStateManager) LoadAllTasks() []*ScheduledTask

LoadAllTasks loads all tasks from all known project directories.

func (*SchedulerStateManager) LoadTasks added in v0.7.0

func (m *SchedulerStateManager) LoadTasks(projectPath string) ([]*ScheduledTask, error)

LoadTasks loads all tasks for a specific project.

func (*SchedulerStateManager) RegisterProject added in v0.7.0

func (m *SchedulerStateManager) RegisterProject(projectPath string)

RegisterProject registers a project directory for task tracking.

func (*SchedulerStateManager) RemoveTask added in v0.7.0

func (m *SchedulerStateManager) RemoveTask(taskID string, projectPath string) error

RemoveTask removes a task from the project's state file.

func (*SchedulerStateManager) SaveTask added in v0.7.0

func (m *SchedulerStateManager) SaveTask(task *ScheduledTask) error

SaveTask saves or updates a task in the project's state file.

func (*SchedulerStateManager) ScanForProjects added in v0.7.0

func (m *SchedulerStateManager) ScanForProjects(basePaths []string)

ScanForProjects scans directories for existing task state files. This is called at daemon startup to discover persisted tasks.

type Session added in v0.7.0

type Session struct {
	Code        string        `json:"code"`         // Unique session identifier (e.g., "claude-1", "dev")
	OverlayPath string        `json:"overlay_path"` // Unix socket path for overlay
	ProjectPath string        `json:"project_path"` // Directory where session was started
	Command     string        `json:"command"`      // Command being run (e.g., "claude")
	Args        []string      `json:"args"`         // Command arguments
	StartedAt   time.Time     `json:"started_at"`   // When session started
	Status      SessionStatus `json:"status"`       // Current status
	LastSeen    time.Time     `json:"last_seen"`    // Last heartbeat timestamp
	// contains filtered or unexported fields
}

Session represents an active agnt run instance.

func (*Session) GetStatus added in v0.7.0

func (s *Session) GetStatus() SessionStatus

GetStatus returns the current session status.

func (*Session) IsActive added in v0.7.0

func (s *Session) IsActive() bool

IsActive returns true if the session is currently active.

func (*Session) MarshalJSON added in v0.7.0

func (s *Session) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Session.

func (*Session) SetStatus added in v0.7.0

func (s *Session) SetStatus(status SessionStatus)

SetStatus updates the session status.

func (*Session) ToJSON added in v0.7.0

func (s *Session) ToJSON() map[string]interface{}

ToJSON returns the session as a JSON-serializable map.

func (*Session) UpdateLastSeen added in v0.7.0

func (s *Session) UpdateLastSeen()

UpdateLastSeen updates the last seen timestamp and sets status to active.

type SessionInfo added in v0.7.0

type SessionInfo struct {
	ActiveCount       int64 `json:"active_count"`
	TotalRegistered   int64 `json:"total_registered"`
	TotalUnregistered int64 `json:"total_unregistered"`
}

SessionInfo contains statistics about the session registry.

type SessionRegistry added in v0.7.0

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

SessionRegistry manages active sessions with lock-free operations.

func NewSessionRegistry added in v0.7.0

func NewSessionRegistry(heartbeatTimeout time.Duration) *SessionRegistry

NewSessionRegistry creates a new session registry.

func (*SessionRegistry) ActiveCount added in v0.7.0

func (r *SessionRegistry) ActiveCount() int64

ActiveCount returns the number of active sessions.

func (*SessionRegistry) CheckHeartbeats added in v0.7.0

func (r *SessionRegistry) CheckHeartbeats()

CheckHeartbeats marks sessions as disconnected if they haven't sent a heartbeat recently.

func (*SessionRegistry) FindByDirectory added in v0.7.12

func (r *SessionRegistry) FindByDirectory(directory string) (*Session, bool)

FindByDirectory finds an active session whose project path matches the given directory or any of its parent directories. Returns the most specific (deepest) match. This enables auto-attach behavior where MCP clients in subdirectories can find sessions started in parent directories.

func (*SessionRegistry) GenerateSessionCode added in v0.7.0

func (r *SessionRegistry) GenerateSessionCode(command string) string

GenerateSessionCode generates a unique session code based on command name. Returns codes like "claude-1", "claude-2", etc.

func (*SessionRegistry) Get added in v0.7.0

func (r *SessionRegistry) Get(code string) (*Session, bool)

Get retrieves a session by code.

func (*SessionRegistry) Heartbeat added in v0.7.0

func (r *SessionRegistry) Heartbeat(code string) error

Heartbeat updates the last seen time for a session.

func (*SessionRegistry) Info added in v0.7.0

func (r *SessionRegistry) Info() SessionInfo

Info returns statistics about the session registry.

func (*SessionRegistry) List added in v0.7.0

func (r *SessionRegistry) List(projectPath string, global bool) []*Session

List returns all sessions, optionally filtered by project path.

func (*SessionRegistry) ListActive added in v0.7.0

func (r *SessionRegistry) ListActive(projectPath string, global bool) []*Session

ListActive returns only active sessions.

func (*SessionRegistry) Register added in v0.7.0

func (r *SessionRegistry) Register(session *Session) error

Register adds a new session to the registry.

func (*SessionRegistry) TotalRegistered added in v0.7.0

func (r *SessionRegistry) TotalRegistered() int64

TotalRegistered returns the total number of sessions registered.

func (*SessionRegistry) TotalUnregistered added in v0.7.0

func (r *SessionRegistry) TotalUnregistered() int64

TotalUnregistered returns the total number of sessions unregistered.

func (*SessionRegistry) Unregister added in v0.7.0

func (r *SessionRegistry) Unregister(code string) error

Unregister removes a session from the registry.

type SessionStatus added in v0.7.0

type SessionStatus string

SessionStatus represents the current state of a session.

const (
	// SessionStatusActive indicates the session is running and responsive.
	SessionStatusActive SessionStatus = "active"
	// SessionStatusDisconnected indicates the session has not sent a heartbeat recently.
	SessionStatusDisconnected SessionStatus = "disconnected"
)

type SocketConfig

type SocketConfig struct {
	Path string
	Mode os.FileMode
}

SocketConfig holds configuration for socket management. This is a compatibility wrapper around socket.Config.

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. This is a compatibility wrapper around socket.Manager.

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 StartScriptConfig added in v0.11.1

type StartScriptConfig struct {
	// ProcessID is the unique identifier for the process
	ProcessID string
	// ProjectPath is the root project directory (where .agnt.kdl is located).
	// Used for session association and proxy event handling.
	// If empty, defaults to WorkingDir.
	ProjectPath string
	// WorkingDir is the working directory for the process (may differ from ProjectPath
	// when script has cwd configured)
	WorkingDir string
	// Command is the executable to run
	Command string
	// Args are the command arguments
	Args []string
	// Env are environment variables (KEY=VALUE format)
	Env []string
	// ExpectedPorts are the ports the process is expected to use (for pre-flight cleanup and EADDRINUSE recovery)
	ExpectedPorts []int
	// URLMatchers are patterns for URL detection in output
	URLMatchers []string
	// AutoRestart enables automatic restart on process exit
	AutoRestart bool
	// AutoRestartConfig is optional custom restart configuration
	AutoRestartConfig *AutoRestartConfig
}

StartScriptConfig holds configuration for starting a script/process. This unified config is used by both autostartScript and hub handlers to ensure consistent behavior (EADDRINUSE recovery, URL tracking, auto-restart).

type StartScriptResult added in v0.11.1

type StartScriptResult struct {
	Process *process.ManagedProcess
	Reused  bool // True if an existing process was reused
}

StartScriptResult holds the result of starting a script.

type StartupError added in v0.8.0

type StartupError struct {
	ProcessID string
	Port      int
	ErrorType string // "EADDRINUSE", "generic"
	Message   string
	Output    string // Last lines of process output (for user-facing diagnostics)
	Retried   bool
}

StartupError represents a startup failure with recovery information.

func (*StartupError) Error added in v0.8.0

func (e *StartupError) Error() string

type StartupLogEntry added in v0.12.15

type StartupLogEntry struct {
	ProcessID  string    `json:"process_id"`
	ScriptName string    `json:"script_name"` // Name without project prefix
	Level      string    `json:"level"`       // "info", "warning", "error"
	EventType  string    `json:"event_type"`  // "started", "EADDRINUSE", "start_failed", "cleanup_failed", "port_cleanup", "dependency_wait", "skipped"
	Message    string    `json:"message"`
	Output     string    `json:"output,omitempty"` // Last lines of process output (errors only)
	Port       int       `json:"port,omitempty"`
	Timestamp  time.Time `json:"timestamp"`
}

StartupLogEntry records a startup event (success or failure) with diagnostic context.

type StartupLogFilter added in v0.12.15

type StartupLogFilter struct {
	Since     time.Time
	ProcessID string
	Level     string // "info", "warning", "error", or "" for all
	Limit     int
}

StartupLogFilter controls which entries are returned by Query.

type StartupLogStore added in v0.12.15

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

StartupLogStore is a ring buffer of recent startup events. Survives process cleanup so logs remain queryable after processes are removed from the registry.

func NewStartupLogStore added in v0.12.15

func NewStartupLogStore(maxSize int) *StartupLogStore

NewStartupLogStore creates a new store with the given capacity.

func (*StartupLogStore) Add added in v0.12.15

func (s *StartupLogStore) Add(entry *StartupLogEntry)

Add inserts a startup log entry into the ring buffer.

func (*StartupLogStore) Clear added in v0.12.15

func (s *StartupLogStore) Clear()

Clear removes all entries.

func (*StartupLogStore) Error added in v0.12.15

func (s *StartupLogStore) Error(processID, scriptName, eventType, message string)

Error adds an error log entry.

func (*StartupLogStore) Info added in v0.12.15

func (s *StartupLogStore) Info(processID, scriptName, eventType, message string)

Info adds an informational log entry.

func (*StartupLogStore) Len added in v0.12.15

func (s *StartupLogStore) Len() int

Len returns the current number of entries.

func (*StartupLogStore) Query added in v0.12.15

func (s *StartupLogStore) Query(filter StartupLogFilter) []*StartupLogEntry

Query returns matching entries ordered oldest to newest.

func (*StartupLogStore) Recent added in v0.12.15

func (s *StartupLogStore) Recent(d time.Duration, limit int) []*StartupLogEntry

Recent returns entries from the last duration, up to limit.

type StateManager

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

StateManager handles persisting and restoring daemon state.

func NewStateManager

func NewStateManager(config StateManagerConfig) *StateManager

NewStateManager creates a new state manager.

func (*StateManager) AddProxy

func (sm *StateManager) AddProxy(config PersistentProxyConfig)

AddProxy adds a proxy configuration to state.

func (*StateManager) Clear

func (sm *StateManager) Clear() error

Clear removes all state.

func (*StateManager) Flush

func (sm *StateManager) Flush() error

Flush ensures any pending saves are written immediately.

func (*StateManager) GetOverlayEndpoint

func (sm *StateManager) GetOverlayEndpoint() string

GetOverlayEndpoint returns the persisted overlay endpoint.

func (*StateManager) GetProxies

func (sm *StateManager) GetProxies() []PersistentProxyConfig

GetProxies returns all persisted proxy configurations.

func (*StateManager) GetProxy

func (sm *StateManager) GetProxy(id string) (PersistentProxyConfig, bool)

GetProxy returns a specific proxy configuration.

func (*StateManager) Load

func (sm *StateManager) Load() error

Load loads state from disk.

func (*StateManager) RemoveProxy

func (sm *StateManager) RemoveProxy(id string)

RemoveProxy removes a proxy configuration from state.

func (*StateManager) Save

func (sm *StateManager) Save() error

Save saves state to disk.

func (*StateManager) SaveDebounced

func (sm *StateManager) SaveDebounced()

SaveDebounced saves state with debouncing to avoid excessive writes.

func (*StateManager) SetOverlayEndpoint

func (sm *StateManager) SetOverlayEndpoint(endpoint string)

SetOverlayEndpoint updates the overlay endpoint in state.

func (*StateManager) State

func (sm *StateManager) State() PersistentState

State returns a copy of the current state.

type StateManagerConfig

type StateManagerConfig struct {
	// StatePath is the path to the state file.
	// If empty, uses default location.
	StatePath string

	// SaveInterval is the minimum time between saves (debouncing).
	SaveInterval time.Duration

	// AutoLoad loads state on creation if true.
	AutoLoad bool
}

StateManagerConfig configures the state manager.

func DefaultStateManagerConfig

func DefaultStateManagerConfig() StateManagerConfig

DefaultStateManagerConfig returns sensible defaults.

type TaskStatus added in v0.7.0

type TaskStatus string

TaskStatus represents the string form of a task status for JSON serialization.

const (
	// TaskStatusPending indicates the task is waiting to be delivered.
	TaskStatusPending TaskStatus = "pending"
	// TaskStatusDelivering indicates the task is currently being delivered.
	TaskStatusDelivering TaskStatus = "delivering"
	// TaskStatusDelivered indicates the task was successfully delivered.
	TaskStatusDelivered TaskStatus = "delivered"
	// TaskStatusFailed indicates the task failed after max retries.
	TaskStatusFailed TaskStatus = "failed"
	// TaskStatusCancelled indicates the task was cancelled.
	TaskStatusCancelled TaskStatus = "cancelled"
)

type TunnelInfo

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

TunnelInfo holds tunnel manager statistics.

type URLTracker added in v0.8.0

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

URLTracker monitors process output and extracts dev server URLs. Focused on capturing localhost URLs from dev server startup (e.g., pnpm dev). URLs are stored persistently per process ID so they survive buffer overflow.

func NewURLTracker added in v0.8.0

func NewURLTracker(pm *process.ProcessManager, config URLTrackerConfig) *URLTracker

NewURLTracker creates a new URL tracker.

func (*URLTracker) ClearProcess added in v0.8.0

func (t *URLTracker) ClearProcess(processID string)

ClearProcess removes URL tracking for a process.

func (*URLTracker) GetURLs added in v0.8.0

func (t *URLTracker) GetURLs(processID string) []string

GetURLs returns the detected URLs for a process.

func (*URLTracker) SetURLMatchers added in v0.8.0

func (t *URLTracker) SetURLMatchers(processID string, matchers []string)

SetURLMatchers sets URL matcher patterns for a specific process. Matchers support patterns like "Local:\\s*{url}" or "(Local|Network):\\s*{url}".

func (*URLTracker) Start added in v0.8.0

func (t *URLTracker) Start(ctx context.Context)

Start begins periodic URL scanning.

type URLTrackerConfig added in v0.8.0

type URLTrackerConfig struct {
	// ScanInterval is how often to scan process output for URLs.
	// Default: 500ms (fast for quick startup detection)
	ScanInterval time.Duration
}

URLTrackerConfig configures the URL tracker.

func DefaultURLTrackerConfig added in v0.8.0

func DefaultURLTrackerConfig() URLTrackerConfig

DefaultURLTrackerConfig returns sensible defaults.

type UpgradeConfig added in v0.6.6

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
}

UpgradeConfig holds configuration for daemon upgrades.

func DefaultUpgradeConfig added in v0.6.6

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