Documentation
¶
Overview ¶
Package daemon implements the agnt background service.
go-cli-server Boundary ¶
The daemon is built on top of github.com/standardbeagle/go-cli-server, which provides the core IPC hub, process management, and script registry. The boundary between the two packages is:
go-cli-server owns:
- hub.Hub — socket server, client lifecycle, session management
- hub.Connection — per-client connection handler
- process.ProcessManager — process creation, monitoring, termination
- process.ManagedProcess — individual process state machine
- script.Registry — per-script state that persists across process restarts
- protocol.Command — parsed IPC command (Verb, SubVerb, Args)
- protocol.StructuredError — typed error responses
- client.Conn — client-side IPC connection
- socket.Manager — Unix socket / named pipe lifecycle
agnt/daemon owns:
- Daemon — composes hub.Hub with agnt-specific managers (proxy, tunnel, browser, etc.)
- proxy.ProxyManager — reverse proxy lifecycle
- tunnel.Manager — cloudflare/ngrok tunnel management
- browser.Manager — browser instance management
- SessionRegistry — agnt session tracking (distinct from hub sessions)
- URLTracker — URL detection from process output
- All hub_*.go handlers — agnt-specific command implementations
- Conn / RequestBuilder — shared client connection wrapper (see conn.go)
Import convention within this package:
- hubpkg = go-cli-server/hub
- goprocess = go-cli-server/process
- hubproto = go-cli-server/protocol
- goclient = go-cli-server/client
- Direct imports for go-cli-server/script (no alias needed)
No go-cli-server types are re-exported from this package. A small number of error sentinel values are re-exported for internal convenience (see socket_compat.go, conn.go). Consumers that need go-cli-server types should import go-cli-server directly.
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 background daemon service.
Index ¶
- Constants
- Variables
- func CleanupZombieDaemons(socketPath string) int
- func Connect(path string) (net.Conn, error)
- func DefaultSocketPath() string
- func DefaultStatePath() string
- func FingerprintForEntry(entry proxy.LogEntry) string
- func FormatRestartDelimiter(events []RestartEvent) string
- func GetLogPath() string
- func IsDaemonRunning(socketPath string) bool
- func IsRunning(path string) bool
- func RunLifecycleHook(cmd, scriptID, event string, scriptCfg *config.ScriptConfig, exitCode int) error
- func StopDaemon(socketPath string) error
- func UpgradeDaemon(ctx context.Context, config UpgradeConfig) error
- type AlertEntry
- type AlertHub
- func (h *AlertHub) AddHookSink(sink HookEventSink)
- func (h *AlertHub) AddMCPSink(sink MCPAlertSink)
- func (h *AlertHub) AddStreamSink(filter streamFilter) *StreamSink
- func (h *AlertHub) BroadcastHookEvent(ev HookEvent)
- func (h *AlertHub) BroadcastLogEntry(entry proxy.LogEntry, proxyID string)
- func (h *AlertHub) BroadcastProcessOutput(entry proxy.LogEntry)
- func (h *AlertHub) Deliver(severity string, formatted string)
- func (h *AlertHub) DriftMetrics() *DriftMetricsSnapshot
- func (h *AlertHub) IncrNewPath()
- func (h *AlertHub) RegisterProxyPath(proxyID, projectPath string)
- func (h *AlertHub) RemoveHookSink(sink HookEventSink)
- func (h *AlertHub) RemoveMCPSink(sink MCPAlertSink)
- func (h *AlertHub) RemoveStreamSink(sink *StreamSink)
- func (h *AlertHub) SetIncidentBus(bus incident.Bus)
- func (h *AlertHub) SetIncidentPipeline(enabled bool)
- func (h *AlertHub) SetOverlaySink(sink OverlayAlertSink)
- func (h *AlertHub) SetProxyBroadcaster(pb ProxyBroadcaster)
- func (h *AlertHub) SetPushConfig(pc *config.PushConfig)
- type AlertStoreFilter
- type AutoRestartConfig
- type AutoStartClient
- type AutoStartConfig
- type AutostartBroadcastFunc
- type AutostartHandle
- type AutostartManager
- func (m *AutostartManager) Cancel(projectPath string)
- func (m *AutostartManager) CancelAll()
- func (m *AutostartManager) Get(projectPath string) *AutostartHandle
- func (m *AutostartManager) GetOrCreate(projectPath string, startFn AutostartStartFunc) *AutostartHandle
- func (m *AutostartManager) Progress(projectPath string) []AutostartProgress
- func (m *AutostartManager) Remove(projectPath string)
- type AutostartPhase
- type AutostartProgress
- type AutostartResult
- type AutostartStartFunc
- type BrowserInfo
- type CheckResult
- type CleanupResult
- type Client
- func (c *Client) AlertClear() error
- func (c *Client) AlertQuery(filter protocol.AlertQueryFilter) (map[string]interface{}, error)
- func (c *Client) AlertReport(payload protocol.AlertReportPayload) error
- func (c *Client) AutomationEvaluate(config protocol.AutomationEvaluateConfig) (map[string]interface{}, error)
- func (c *Client) AutomationList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (c *Client) AutomationNavigate(config protocol.AutomationNavigateConfig) (map[string]interface{}, error)
- func (c *Client) AutomationScreenshot(config protocol.AutomationScreenshotConfig) (map[string]interface{}, error)
- func (c *Client) AutomationStart(config protocol.AutomationStartConfig) (map[string]interface{}, error)
- func (c *Client) AutomationStatus(id string) (map[string]interface{}, error)
- func (c *Client) AutomationStop(id string) error
- func (c *Client) AutostartClearPorts(projectPath string) (map[string]interface{}, error)
- func (c *Client) AutostartContinue(projectPath string) (map[string]interface{}, error)
- func (c *Client) AutostartRun(projectPath string) (map[string]interface{}, error)
- func (c *Client) BroadcastActivity(active bool, proxyIDs ...string) error
- func (c *Client) BroadcastOutputPreview(lines []string, proxyIDs ...string) error
- func (c *Client) BrowserList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (c *Client) BrowserStart(config protocol.BrowserStartConfig) (map[string]interface{}, error)
- func (c *Client) BrowserStatus(id string) (map[string]interface{}, error)
- func (c *Client) BrowserStop(id string) error
- func (c *Client) ChaosAddRule(proxyID string, rule protocol.ChaosRuleConfig) (map[string]interface{}, error)
- func (c *Client) ChaosClear(proxyID string) (map[string]interface{}, error)
- func (c *Client) ChaosDisable(proxyID string) (map[string]interface{}, error)
- func (c *Client) ChaosEnable(proxyID string) (map[string]interface{}, error)
- func (c *Client) ChaosListPresets() (map[string]interface{}, error)
- func (c *Client) ChaosListRules(proxyID string) (map[string]interface{}, error)
- func (c *Client) ChaosPreset(proxyID, preset string) (map[string]interface{}, error)
- func (c *Client) ChaosRemoveRule(proxyID, ruleID string) (map[string]interface{}, error)
- func (c *Client) ChaosSet(proxyID string, config protocol.ChaosConfigPayload) (map[string]interface{}, error)
- func (c *Client) ChaosStats(proxyID string) (map[string]interface{}, error)
- func (c *Client) ChaosStatus(proxyID string) (map[string]interface{}, error)
- func (c *Client) Close() error
- func (c *Client) Connect() error
- func (c *Client) CurrentPageClear(proxyID string) error
- func (c *Client) CurrentPageGet(proxyID, sessionID string) (map[string]interface{}, error)
- func (c *Client) CurrentPageList(proxyID string) (map[string]interface{}, error)
- func (c *Client) Detect(path string) (map[string]interface{}, error)
- func (c *Client) Doctor(projectPath string) (map[string]interface{}, error)
- func (c *Client) HookSend(ctx context.Context, event string, payloadJSON json.RawMessage, ...) error
- func (c *Client) IncidentQuery(filter protocol.IncidentQueryFilter) (*protocol.IncidentQueryResult, error)
- func (c *Client) Info() (*DaemonInfo, error)
- func (c *Client) IsConnected() bool
- func (c *Client) OverlayClear() error
- func (c *Client) OverlayGet() (map[string]interface{}, error)
- func (c *Client) OverlaySet(endpoint string) (map[string]interface{}, error)
- func (c *Client) Ping() error
- func (c *Client) ProcAutoRestart(processID, action string, config *ProcAutoRestartConfig) (map[string]interface{}, error)
- func (c *Client) ProcCleanupPort(port int) (map[string]interface{}, error)
- func (c *Client) ProcList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (c *Client) ProcOutput(processID string, filter protocol.OutputFilter) (string, error)
- func (c *Client) ProcRestart(processID string) (map[string]interface{}, error)
- func (c *Client) ProcRun(name string, cfg ProcRunConfig) (map[string]interface{}, error)
- func (c *Client) ProcRunGroup(cfg ProcRunGroupConfig) (map[string]interface{}, error)
- func (c *Client) ProcStatus(processID string) (map[string]interface{}, error)
- func (c *Client) ProcStop(processID string, force bool) (map[string]interface{}, error)
- func (c *Client) ProxyExec(id, code string) (map[string]interface{}, error)
- func (c *Client) ProxyList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (c *Client) ProxyLogClear(proxyID string) error
- func (c *Client) ProxyLogQuery(proxyID string, filter protocol.LogQueryFilter) (map[string]interface{}, error)
- func (c *Client) ProxyLogStats(proxyID string) (map[string]interface{}, error)
- func (c *Client) ProxyRestart(id string) (map[string]interface{}, error)
- func (c *Client) ProxyStart(id, targetURL string, port, maxLogSize int, path string) (map[string]interface{}, error)
- func (c *Client) ProxyStartWithConfig(id, targetURL string, port, maxLogSize int, config ProxyStartConfig) (map[string]interface{}, error)
- func (c *Client) ProxyStatus(id string) (map[string]interface{}, error)
- func (c *Client) ProxyStop(id string) error
- func (c *Client) ProxyToast(id string, toast protocol.ToastConfig) (map[string]interface{}, error)
- func (c *Client) RestartAll() (map[string]interface{}, error)
- func (c *Client) Run(config interface{}) (map[string]interface{}, error)
- func (c *Client) ScriptGet(name, projectPath string) (map[string]interface{}, error)
- func (c *Client) ScriptList(projectPath string) (map[string]interface{}, error)
- func (c *Client) ScriptOutput(name, projectPath string, tail int) (map[string]interface{}, error)
- func (c *Client) ScriptRestart(name, projectPath string) (map[string]interface{}, error)
- func (c *Client) ScriptStop(name, projectPath string) (map[string]interface{}, error)
- func (c *Client) SessionAttach(directory string) (map[string]interface{}, error)
- func (c *Client) SessionCancel(taskID string) error
- func (c *Client) SessionFind(directory string) (map[string]interface{}, error)
- func (c *Client) SessionGenerateCode(command string) (string, error)
- func (c *Client) SessionGet(code string) (map[string]interface{}, error)
- func (c *Client) SessionHeartbeat(code string) error
- func (c *Client) SessionList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (c *Client) SessionRegister(code string, overlayPath string, projectPath string, command string, ...) (map[string]interface{}, error)
- func (c *Client) SessionRegisterWithContainment(code string, overlayPath string, projectPath string, command string, ...) (map[string]interface{}, error)
- func (c *Client) SessionRegisterWithPGID(code string, overlayPath string, projectPath string, command string, ...) (map[string]interface{}, error)
- func (c *Client) SessionSchedule(code string, duration string, message string) (map[string]interface{}, error)
- func (c *Client) SessionSend(code string, message string) (map[string]interface{}, error)
- func (c *Client) SessionTasks(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (c *Client) SessionURL(code string, url string, scriptName string) (map[string]interface{}, error)
- func (c *Client) SessionUnregister(code string) error
- func (c *Client) Shutdown() error
- func (c *Client) SocketPath() string
- func (c *Client) StartupLog(limit int) (map[string]interface{}, error)
- func (c *Client) StopAll() (map[string]interface{}, error)
- func (c *Client) StoreClear(req protocol.StoreClearRequest) error
- func (c *Client) StoreDelete(req protocol.StoreDeleteRequest) error
- func (c *Client) StoreGet(req protocol.StoreGetRequest) (map[string]interface{}, error)
- func (c *Client) StoreGetAll(req protocol.StoreGetAllRequest) (map[string]interface{}, error)
- func (c *Client) StoreList(req protocol.StoreListRequest) (map[string]interface{}, error)
- func (c *Client) StoreSet(req protocol.StoreSetRequest) error
- func (c *Client) StreamEvents(ctx context.Context, filter protocol.StreamEventFilter, ...) error
- func (c *Client) TunnelList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (c *Client) TunnelStart(config protocol.TunnelStartConfig) (map[string]interface{}, error)
- func (c *Client) TunnelStatus(id string) (map[string]interface{}, error)
- func (c *Client) TunnelStop(id string) error
- type ClientOption
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) Disconnect() error
- func (c *Conn) EnsureConnected() error
- func (c *Conn) IsConnected() bool
- func (c *Conn) Ping() error
- func (c *Conn) Request(verb string, args ...string) *RequestBuilder
- func (c *Conn) SetTimeout(d time.Duration)
- func (c *Conn) SocketPath() string
- type Daemon
- func (d *Daemon) AlertHub() *AlertHub
- func (d *Daemon) AlertStore() *ProcessAlertStore
- func (d *Daemon) ApplyAlertsConfig(cfg *config.AlertsConfig)
- func (d *Daemon) AutoRestarter() *ProcessAutoRestarter
- func (d *Daemon) BrowserManager() *browser.Manager
- func (d *Daemon) CleanupSessionResources(sessionCode string)
- func (d *Daemon) CleanupSessionResourcesDeferred(sessionCode string)
- func (d *Daemon) FlushScriptProxyConnections(scriptID string)
- func (d *Daemon) GetSession(code string) (*Session, bool)
- func (d *Daemon) IncidentBus() *incident.MPSCBus
- func (d *Daemon) Info() DaemonInfo
- func (d *Daemon) LoadURLMatchersForProcess(processID string)
- func (d *Daemon) OverlayEndpoint() string
- func (d *Daemon) ProcessManager() *process.ProcessManager
- func (d *Daemon) ProxyManager() *proxy.ProxyManager
- func (d *Daemon) RunAutostart(ctx context.Context, projectPath string) *AutostartResult
- func (d *Daemon) RunAutostartAsync(ctx context.Context, projectPath string, progress chan<- AutostartProgress) *AutostartResult
- func (d *Daemon) RunAutostartNonInteractive(ctx context.Context, projectPath string) *AutostartResult
- func (d *Daemon) RunDoctor(ctx context.Context, projectPath string) *DoctorReport
- func (d *Daemon) Scheduler() *Scheduler
- func (d *Daemon) ScriptRegistry() *script.Registry
- func (d *Daemon) SessionManager() *chromedp.SessionManager
- func (d *Daemon) SessionRegistry() *SessionRegistry
- func (d *Daemon) SetOnShutdown(fn func())
- func (d *Daemon) SetOverlayEndpoint(endpoint string)
- func (d *Daemon) Start() error
- func (d *Daemon) StartProcessGroup(ctx context.Context, projectPath string, processes []GroupProcess, ...) GroupResult
- func (d *Daemon) StartProcessWithDeps(ctx context.Context, name string, scriptCfg *config.ScriptConfig, ...) StartProcessResult
- func (d *Daemon) StartScript(ctx context.Context, cfg StartScriptConfig) (*StartScriptResult, error)
- func (d *Daemon) StartScriptExplicit(ctx context.Context, name string, scriptCfg *config.ScriptConfig, ...) error
- func (d *Daemon) StartupLogStore() *StartupLogStore
- func (d *Daemon) StateManager() *StateManager
- func (d *Daemon) Stop(ctx context.Context) error
- func (d *Daemon) StopAllResources(ctx context.Context)
- func (d *Daemon) TunnelManager() *tunnel.Manager
- func (d *Daemon) Wait()
- type DaemonConfig
- type DaemonInfo
- type DaemonUpgrader
- type DoctorReport
- type DriftMetricsSnapshot
- type DuplicateGroup
- type DuplicateScanner
- type GroupProcess
- type GroupResult
- type HealthTracker
- func (h *HealthTracker) Forget(processID string)
- func (h *HealthTracker) ForgetProxy(proxyID string)
- func (h *HealthTracker) IsDaemonInitiatedStop(processID string) bool
- func (h *HealthTracker) IsInSuppressionWindow(proxyID, linkedProcessID string) bool
- func (h *HealthTracker) IsProxyInTransportOutage(proxyID string) bool
- func (h *HealthTracker) LastHealthyAt(processID string) time.Time
- func (h *HealthTracker) LastObservedState(processID string) goprocess.ProcessState
- func (h *HealthTracker) LastRebuildSignal(processID string) time.Time
- func (h *HealthTracker) MarkDaemonInitiatedStop(processID string)
- func (h *HealthTracker) MaybeCloseGraceWindow(proxyID, linkedProcessID string)
- func (h *HealthTracker) OutageStartedAt(processID string) time.Time
- func (h *HealthTracker) PreviousObservedState(processID string) goprocess.ProcessState
- func (h *HealthTracker) RecordRebuildSignal(processID string)
- func (h *HealthTracker) RecordRecoverySignal(proxyID string, ts time.Time)
- func (h *HealthTracker) RecordTransportError(proxyID string, ts time.Time)
- func (h *HealthTracker) SetOnTransportRecovery(fn func(proxyID string))
- func (h *HealthTracker) SetTransportConfig(cfg TransportConfig)
- type HoldBuffer
- type HoldEmitFn
- type HookEvent
- type HookEventSink
- type KillResult
- type KilledProcess
- type MCPAlertSink
- type OutageClassifier
- func (c *OutageClassifier) Classify(processID string) OutageType
- func (c *OutageClassifier) ClassifyProxy(proxyID, linkedProcessID string) OutageType
- func (c *OutageClassifier) Forget(processID string)
- func (c *OutageClassifier) NoteOutageOnset(processID string, ts time.Time)
- func (c *OutageClassifier) SuppressionMode(processID string) SuppressionMode
- func (c *OutageClassifier) SuppressionModeProxy(proxyID, linkedProcessID string) SuppressionMode
- type OutageType
- type OverlayAlertSink
- type PendingProcess
- type PendingProcessState
- type PendingProcessTracker
- func (t *PendingProcessTracker) Get(processID string) (PendingProcess, bool)
- func (t *PendingProcessTracker) ListByProject(projectPath string) []PendingProcess
- func (t *PendingProcessTracker) MarkFailed(processID, dep string)
- func (t *PendingProcessTracker) MarkReady(processID, dep string) int
- func (t *PendingProcessTracker) Register(p PendingProcess, deps []string) PendingProcess
- func (t *PendingProcessTracker) Remove(processID string)
- type PersistedTaskState
- type PersistentProxyConfig
- type PersistentState
- type PortConflict
- type ProcAutoRestartConfig
- type ProcRunConfig
- type ProcRunGroupConfig
- type ProcessAlertStore
- type ProcessAutoRestarter
- func (r *ProcessAutoRestarter) GetConfig(processID string) (AutoRestartConfig, bool)
- func (r *ProcessAutoRestarter) GetRestartEvents(processID string) []RestartEvent
- func (r *ProcessAutoRestarter) IsRegistered(processID string) bool
- func (r *ProcessAutoRestarter) Register(processID string, config AutoRestartConfig, command string, args []string, ...)
- func (r *ProcessAutoRestarter) Shutdown(ctx context.Context)
- func (r *ProcessAutoRestarter) Stats() map[string]interface{}
- func (r *ProcessAutoRestarter) Unregister(processID string)
- type ProcessExitInfo
- type ProcessInfo
- type ProxyBroadcaster
- type ProxyEvent
- type ProxyEventType
- type ProxyInfo
- type ProxyStartConfig
- type ReadySignaler
- func (rs *ReadySignaler) Cleanup(processID string)
- func (rs *ReadySignaler) GetOrCreate(processID string) chan struct{}
- func (rs *ReadySignaler) SignalReady(processID string)
- func (rs *ReadySignaler) StartPortProbe(processID string, port int, ctx context.Context)
- func (rs *ReadySignaler) WaitReady(processID string, timeout time.Duration) error
- func (rs *ReadySignaler) WaitReadyCtx(processID string, ctx context.Context) error
- type ReconnectCallback
- type RequestBuilder
- func (r *RequestBuilder) Bytes() ([]byte, error)
- func (r *RequestBuilder) Chunked() ([]byte, error)
- func (r *RequestBuilder) JSON() (map[string]interface{}, error)
- func (r *RequestBuilder) JSONInto(v interface{}) error
- func (r *RequestBuilder) OK() error
- func (r *RequestBuilder) String() (string, error)
- func (r *RequestBuilder) WithArgs(args ...string) *RequestBuilder
- func (r *RequestBuilder) WithData(data []byte) *RequestBuilder
- func (r *RequestBuilder) WithJSON(v interface{}) *RequestBuilder
- type ResilientClient
- func (rc *ResilientClient) AlertClear() error
- func (rc *ResilientClient) AlertQuery(filter protocol.AlertQueryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) AlertReport(payload protocol.AlertReportPayload) error
- func (rc *ResilientClient) AutomationEvaluate(config protocol.AutomationEvaluateConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) AutomationList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) AutomationNavigate(config protocol.AutomationNavigateConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) AutomationScreenshot(config protocol.AutomationScreenshotConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) AutomationStart(config protocol.AutomationStartConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) AutomationStatus(id string) (map[string]interface{}, error)
- func (rc *ResilientClient) AutomationStop(id string) error
- func (rc *ResilientClient) BroadcastActivity(active bool, proxyIDs ...string) error
- func (rc *ResilientClient) BroadcastOutputPreview(lines []string, proxyIDs ...string) error
- func (rc *ResilientClient) BrowserList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) BrowserStart(config protocol.BrowserStartConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) BrowserStatus(id string) (map[string]interface{}, error)
- func (rc *ResilientClient) BrowserStop(id string) error
- func (rc *ResilientClient) ChaosAddRule(proxyID string, rule protocol.ChaosRuleConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosClear(proxyID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosDisable(proxyID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosEnable(proxyID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosListPresets() (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosListRules(proxyID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosPreset(proxyID, preset string) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosRemoveRule(proxyID, ruleID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosSet(proxyID string, config protocol.ChaosConfigPayload) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosStats(proxyID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ChaosStatus(proxyID string) (map[string]interface{}, error)
- func (rc *ResilientClient) Client() *Client
- func (rc *ResilientClient) Close() error
- func (rc *ResilientClient) Connect() error
- func (rc *ResilientClient) CurrentPageClear(proxyID string) error
- func (rc *ResilientClient) CurrentPageGet(proxyID, sessionID string) (map[string]interface{}, error)
- func (rc *ResilientClient) CurrentPageList(proxyID string) (map[string]interface{}, error)
- func (rc *ResilientClient) Detect(path string) (map[string]interface{}, error)
- func (rc *ResilientClient) Doctor(projectPath string) (map[string]interface{}, error)
- func (rc *ResilientClient) IncidentQuery(filter protocol.IncidentQueryFilter) (*protocol.IncidentQueryResult, error)
- func (rc *ResilientClient) Info() (*DaemonInfo, error)
- func (rc *ResilientClient) IsConnected() bool
- func (rc *ResilientClient) IsReconnecting() bool
- func (rc *ResilientClient) OverlaySet(endpoint string) (map[string]interface{}, error)
- func (rc *ResilientClient) Ping() error
- func (rc *ResilientClient) ProcAutoRestart(processID, action string, config *ProcAutoRestartConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) ProcCleanupPort(port int) (map[string]interface{}, error)
- func (rc *ResilientClient) ProcList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) ProcOutput(processID string, filter protocol.OutputFilter) (string, error)
- func (rc *ResilientClient) ProcRestart(processID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ProcRun(name string, cfg ProcRunConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) ProcRunGroup(cfg ProcRunGroupConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) ProcStatus(processID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ProcStop(processID string, force bool) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyExec(id, code string) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyLogClear(proxyID string) error
- func (rc *ResilientClient) ProxyLogQuery(proxyID string, filter protocol.LogQueryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyLogStats(proxyID string) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyRestart(id string) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyStart(id, targetURL string, port, maxLogSize int, path string) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyStartWithConfig(id, targetURL string, port, maxLogSize int, config ProxyStartConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyStatus(id string) (map[string]interface{}, error)
- func (rc *ResilientClient) ProxyStop(id string) error
- func (rc *ResilientClient) ProxyToast(id string, toast protocol.ToastConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) RestartAll() (map[string]interface{}, error)
- func (rc *ResilientClient) Run(config interface{}) (map[string]interface{}, error)
- func (rc *ResilientClient) ScriptGet(name, projectPath string) (map[string]interface{}, error)
- func (rc *ResilientClient) ScriptList(projectPath string) (map[string]interface{}, error)
- func (rc *ResilientClient) ScriptOutput(name, projectPath string, tail int) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionAttach(directory string) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionCancel(taskID string) error
- func (rc *ResilientClient) SessionFind(directory string) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionGenerateCode(command string) (string, error)
- func (rc *ResilientClient) SessionGet(code string) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionHeartbeat(code string) error
- func (rc *ResilientClient) SessionList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionRegister(code, overlayPath, projectPath, command string, args []string) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionRegisterWithContainment(code, overlayPath, projectPath, command string, args []string, sessionPGID int, ...) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionRegisterWithPGID(code, overlayPath, projectPath, command string, args []string, sessionPGID int) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionSchedule(code, duration, message string) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionSend(code, message string) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionTasks(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) SessionUnregister(code string) error
- func (rc *ResilientClient) StartupLog(limit int) (map[string]interface{}, error)
- func (rc *ResilientClient) Stats() map[string]interface{}
- func (rc *ResilientClient) StopAll() (map[string]interface{}, error)
- func (rc *ResilientClient) StoreClear(req protocol.StoreClearRequest) error
- func (rc *ResilientClient) StoreDelete(req protocol.StoreDeleteRequest) error
- func (rc *ResilientClient) StoreGet(req protocol.StoreGetRequest) (map[string]interface{}, error)
- func (rc *ResilientClient) StoreGetAll(req protocol.StoreGetAllRequest) (map[string]interface{}, error)
- func (rc *ResilientClient) StoreList(req protocol.StoreListRequest) (map[string]interface{}, error)
- func (rc *ResilientClient) StoreSet(req protocol.StoreSetRequest) error
- func (rc *ResilientClient) TunnelList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
- func (rc *ResilientClient) TunnelStart(config protocol.TunnelStartConfig) (map[string]interface{}, error)
- func (rc *ResilientClient) TunnelStatus(id string) (map[string]interface{}, error)
- func (rc *ResilientClient) TunnelStop(id string) error
- func (rc *ResilientClient) WithClient(fn func(*Client) error) error
- type ResilientClientConfig
- type RestartEvent
- type RogueProcessInfo
- type ScheduledTask
- func (t *ScheduledTask) Attempts() int
- func (t *ScheduledTask) CompareAndSwapStatus(old, new taskStatus) bool
- func (t *ScheduledTask) IncrementAttempts() int
- func (t *ScheduledTask) LastError() string
- func (t *ScheduledTask) MarshalJSON() ([]byte, error)
- func (t *ScheduledTask) SetLastError(err string)
- func (t *ScheduledTask) SetStatus(s TaskStatus)
- func (t *ScheduledTask) Status() TaskStatus
- func (t *ScheduledTask) ToJSON() map[string]interface{}
- func (t *ScheduledTask) UnmarshalJSON(data []byte) error
- type Scheduler
- func (s *Scheduler) Cancel(taskID string) error
- func (s *Scheduler) GetTask(taskID string) (*ScheduledTask, bool)
- func (s *Scheduler) Info() SchedulerInfo
- func (s *Scheduler) ListPendingTasks(projectPath string, global bool) []*ScheduledTask
- func (s *Scheduler) ListTasks(projectPath string, global bool) []*ScheduledTask
- func (s *Scheduler) Schedule(sessionCode string, duration time.Duration, message string, projectPath string) (*ScheduledTask, error)
- func (s *Scheduler) Start(ctx context.Context) error
- func (s *Scheduler) Stop(ctx context.Context)
- type SchedulerConfig
- type SchedulerInfo
- type SchedulerStateManager
- func (m *SchedulerStateManager) ClearProject(projectPath string) error
- func (m *SchedulerStateManager) Close() error
- func (m *SchedulerStateManager) Flush() error
- func (m *SchedulerStateManager) ListProjectsWithTasks() []string
- func (m *SchedulerStateManager) LoadAllTasks() []*ScheduledTask
- func (m *SchedulerStateManager) LoadTasks(projectPath string) ([]*ScheduledTask, error)
- func (m *SchedulerStateManager) RegisterProject(projectPath string)
- func (m *SchedulerStateManager) RemoveTask(taskID string, projectPath string) error
- func (m *SchedulerStateManager) SaveTask(task *ScheduledTask) error
- func (m *SchedulerStateManager) ScanForProjects(basePaths []string)
- type ScriptKind
- type Session
- type SessionInfo
- type SessionRegistry
- func (r *SessionRegistry) ActiveCount() int64
- func (r *SessionRegistry) CheckHeartbeats()
- func (r *SessionRegistry) FindByDirectory(directory string) (*Session, bool)
- func (r *SessionRegistry) GenerateSessionCode(command string) string
- func (r *SessionRegistry) Get(code string) (*Session, bool)
- func (r *SessionRegistry) Heartbeat(code string) error
- func (r *SessionRegistry) Info() SessionInfo
- func (r *SessionRegistry) List(projectPath string, global bool) []*Session
- func (r *SessionRegistry) ListActive(projectPath string, global bool) []*Session
- func (r *SessionRegistry) Register(session *Session) error
- func (r *SessionRegistry) TotalRegistered() int64
- func (r *SessionRegistry) TotalUnregistered() int64
- func (r *SessionRegistry) Unregister(code string) error
- type SessionStatus
- type SocketConfig
- type SocketManager
- type StartProcessResult
- type StartScriptConfig
- type StartScriptResult
- type StartupError
- type StartupLogEntry
- type StartupLogFilter
- type StartupLogStore
- func (s *StartupLogStore) Add(entry *StartupLogEntry)
- func (s *StartupLogStore) Clear()
- func (s *StartupLogStore) Error(processID, scriptName, eventType, message string)
- func (s *StartupLogStore) Info(processID, scriptName, eventType, message string)
- func (s *StartupLogStore) Len() int
- func (s *StartupLogStore) Query(filter StartupLogFilter) []*StartupLogEntry
- func (s *StartupLogStore) Recent(d time.Duration, limit int) []*StartupLogEntry
- type StateManager
- func (sm *StateManager) AddProxy(config PersistentProxyConfig)
- func (sm *StateManager) Clear() error
- func (sm *StateManager) Close() error
- func (sm *StateManager) Flush() error
- func (sm *StateManager) GetOverlayEndpoint() string
- func (sm *StateManager) GetProxies() []PersistentProxyConfig
- func (sm *StateManager) GetProxy(id string) (PersistentProxyConfig, bool)
- func (sm *StateManager) Load() error
- func (sm *StateManager) RemoveProxy(id string)
- func (sm *StateManager) Save() error
- func (sm *StateManager) SaveDebounced()
- func (sm *StateManager) SetOverlayEndpoint(endpoint string)
- func (sm *StateManager) State() PersistentState
- type StateManagerConfig
- type StreamSink
- type SuppressionMode
- type TaskStatus
- type TransportConfig
- type TunnelInfo
- type URLTracker
- type URLTrackerConfig
- type UpgradeConfig
Constants ¶
const ( StatusOK = "ok" StatusWarning = "warning" StatusError = "error" )
Status constants for health check results.
const CategoryProcessLifecycle = "process_lifecycle"
CategoryProcessLifecycle is the AlertEntry category used for process-death events. Keeping it distinct from the AlertScanner-derived "process error" / "compile error" / etc. categories lets dedup in get_errors collapse a single death into exactly one unified error rather than merging it with unrelated output.
const DefaultDependsOnTimeout = 30 * time.Second
DefaultDependsOnTimeout is the per-process default deadline applied when a PROC RUN payload supplies `depends_on` without an explicit `depends_on_timeout` value. Matches the spec's documented 30s default.
This default applies only to the MCP tool surface — the autostart (.agnt.kdl) path continues to default to "wait indefinitely" per .claude/rules/daemon-lifecycle.md, which is correct for that path because the parent context is the session lifetime. The MCP tool surface needs a hard upper bound so an agent that mistypes a dependency name does not strand the dependent forever.
const MaxLogBackups = 3
MaxLogBackups is the number of rotated log files to keep.
const MaxLogSize = 5 * 1024 * 1024
MaxLogSize is the maximum log file size before rotation (5MB).
const SchedulerStateDir = ".agnt"
SchedulerStateDir is the directory within each project for agnt state.
const SchedulerStateFile = "scheduled-tasks.json"
SchedulerStateFile is the name of the per-project task state file.
const SocketName = "devtool-mcp"
SocketName is the socket name used for agnt daemon.
const SuppressionGracePeriod = 5 * time.Second
SuppressionGracePeriod is the time after a process returns to Running during which its linked proxies still suppress error broadcasts. This covers the race window where the browser retries failed fetches a few hundred ms after the new process binds.
Variables ¶
var ( // RebuildShortWindow is the maximum outage duration that still // qualifies as a fast rebuild. Outages longer than this transition // to LongRebuild. RebuildShortWindow = 15 * time.Second // RebuildLongWindow is the absolute upper bound on rebuild // suppression. Past this point the classifier returns // OutageExpiredRebuild and the gate stops suppressing. RebuildLongWindow = 30 * time.Second // RebuildSignalGrace is the lookback window for AlertScanner rebuild // signals. A rebuild pattern matched within this many seconds before // the outage start is treated as evidence of an intentional restart. RebuildSignalGrace = 5 * time.Second // CrashRateLimit and CrashRateWindow define the chronic-crash check. // More than CrashRateLimit outages within CrashRateWindow forces a // crash classification regardless of other signals (matches the // auto-restarter's rate limit by default). CrashRateLimit = 5 CrashRateWindow = time.Minute // LongRebuildHeartbeat is how often the long-rebuild diagnostic // emitter fires while suppression is active in the LongRebuild band. LongRebuildHeartbeat = 10 * time.Second )
Tunables. These are package-level vars rather than constants so tests can shrink them, but production code never modifies them.
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 )
var ( ErrSocketInUse = socket.ErrSocketInUse ErrSocketNotFound = socket.ErrSocketNotFound ErrDaemonRunning = socket.ErrDaemonRunning )
Socket errors re-exported from go-cli-server/socket for convenience. These are used by cmd/agnt when checking daemon status before startup.
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)"
var DefaultTransportConfig = TransportConfig{ Threshold: 1, Window: time.Second, RecoveryDebounce: 500 * time.Millisecond, }
DefaultTransportConfig is what HealthTracker uses when no transport config has been set. Mirrors the OutageHoldConfig defaults.
var ErrConnectionClosed = goclient.ErrConnectionClosed
ErrConnectionClosed is returned when operating on a closed connection. Re-exported from go-cli-server/client for use within this package.
var ErrHookDaemonDown = errors.New("agnt hook: daemon not reachable")
ErrHookDaemonDown is returned from HookSend when the daemon socket is not reachable (connection refused, socket file missing, etc). The CLI maps this to silent exit 0 — hooks are fire-and-forget and a missing daemon is not a user-visible failure.
var ErrHookDeadline = errors.New("agnt hook: daemon enqueue deadline exceeded")
ErrHookDeadline is returned from HookSend when the write or ack did not complete inside hookSendDeadline. The CLI maps this to silent exit 0 — dropping a hook silently is far better than blocking Claude's tool call.
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)"
var Version = "0.13.8"
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 ¶
CleanupZombieDaemons finds and kills zombie daemon processes.
func DefaultSocketPath ¶
func DefaultSocketPath() string
DefaultSocketPath returns the default socket path for agnt. Deliberately ignores XDG_RUNTIME_DIR: agnt daemon is a long-running background service that outlives login sessions. XDG_RUNTIME_DIR is cleaned up by pam_systemd on logout, which would silently delete our socket mid-session. The /tmp/<name>-<uid> form persists across sessions and is deterministic regardless of shell environment.
func DefaultStatePath ¶
func DefaultStatePath() string
DefaultStatePath returns the default state file path.
func FingerprintForEntry ¶ added in v0.13.7
FingerprintForEntry computes a stable fingerprint for a proxy log entry within the hold-buffer scope. Same shape entries collapse onto one held record.
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
func IsDaemonRunning ¶
IsDaemonRunning checks if the daemon is running at the given socket path.
func RunLifecycleHook ¶ added in v0.13.4
func RunLifecycleHook(cmd, scriptID, event string, scriptCfg *config.ScriptConfig, exitCode int) error
RunLifecycleHook executes a lifecycle hook command for a script, blocking up to hookTimeout (5s). Returns an error on timeout or non-zero exit; callers log the error and continue — hook failure never stops the lifecycle transition.
cmd is a shell command string (same as ScriptConfig.Run). scriptID is the script name. event is one of: start, stop, crash, restart. exitCode is the process exit code (meaningful for stop/crash events).
Env: os.Environ() + script Env block overrides + injected AGNT_* vars.
func StopDaemon ¶
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 = alert.AlertEntry
AlertEntry is an alias for alert.AlertEntry. The canonical type lives in internal/alert; this alias keeps daemon-internal code readable without a package qualifier.
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), MCP session notifications, and stream sinks.
func NewAlertHub ¶ added in v0.11.5
func NewAlertHub() *AlertHub
NewAlertHub creates a new AlertHub.
func (*AlertHub) AddHookSink ¶ added in v0.12.44
func (h *AlertHub) AddHookSink(sink HookEventSink)
AddHookSink registers a hook event sink. Safe to call while the drain goroutine is running — registration takes the write lock, broadcast takes the read lock, so the sink starts seeing events on the next push after this call returns.
func (*AlertHub) AddMCPSink ¶ added in v0.11.5
func (h *AlertHub) AddMCPSink(sink MCPAlertSink)
AddMCPSink registers an MCP session for alert delivery.
func (*AlertHub) AddStreamSink ¶ added in v0.12.36
func (h *AlertHub) AddStreamSink(filter streamFilter) *StreamSink
AddStreamSink registers a stream sink and returns it. The caller reads from sink.Ch until it is closed.
func (*AlertHub) BroadcastHookEvent ¶ added in v0.12.44
BroadcastHookEvent fans a single HookEvent out to every registered hook sink. Called exclusively from drainHooks on the dedicated drain goroutine, so ordering is preserved: sinks see events in the order they were pushed into the ring buffer.
The sink slice is copied under the read lock and emission happens outside the lock so a slow sink cannot block registration. Sinks are contracted to be non-blocking; if that contract is violated the drain goroutine stalls and ring buffer overflow kicks in — which is the right failure mode (surfaced via hookRing.OverflowCount).
func (*AlertHub) BroadcastLogEntry ¶ added in v0.12.36
BroadcastLogEntry sends a log entry to all matching stream sinks. Called from the TrafficLogger callback when a new entry is logged.
The send into sink.Ch is wrapped by sendToStreamSinkSafe so that a sink removed between the RLock snapshot and the send does not panic with send-on-closed-channel. RemoveStreamSink closes sink.Ch under the write lock; a BroadcastLogEntry goroutine that already snapshotted the slice before the remove will hold a dangling pointer and would otherwise crash the daemon on the next send.
func (*AlertHub) BroadcastProcessOutput ¶ added in v0.12.36
BroadcastProcessOutput sends a process output line to all matching stream sinks. This reuses the same sink mechanism as BroadcastLogEntry so process events flow through the unified STREAM-EVENTS channel alongside proxy events.
Uses sendToStreamSinkSafe for the same close-during-broadcast protection documented on BroadcastLogEntry.
func (*AlertHub) Deliver ¶ added in v0.11.5
Deliver sends a pre-formatted alert message to all available sinks. Checks the push config to determine which channels are enabled.
When incidentPipeline is true (Phase A: flag-enabled mode), both MCPAlertSink and OverlayAlertSink fan-out are suppressed; delivery is handled by the incident.Bus Pinger instead. StreamSink is NOT gated here — it receives events via BroadcastLogEntry regardless of the flag.
When incidentPipeline is false (default), the old path fires and oldPathCount is incremented for drift monitoring.
func (*AlertHub) DriftMetrics ¶ added in v0.13.0
func (h *AlertHub) DriftMetrics() *DriftMetricsSnapshot
DriftMetrics returns a snapshot of the dual-path event counters. OldPathCount reflects Deliver() calls that reached legacy sinks (flag=false only). NewPathCount reflects IncrNewPath() calls from the incident adapter.
func (*AlertHub) IncrNewPath ¶ added in v0.13.0
func (h *AlertHub) IncrNewPath()
IncrNewPath increments the new-path event counter. Called by the incident adapter layer after it successfully publishes an event to the incident.Bus. Enables drift detection by comparing with OldPathCount.
func (*AlertHub) RegisterProxyPath ¶ added in v0.12.51
RegisterProxyPath records the project directory for a proxy so that project-scoped stream filters (projectPath != "") can exclude events from proxies belonging to other projects. Call once from wireProxyLogger. Entries are never removed because proxyIDs are unique and a stopped proxy cannot generate new LogEntry events.
func (*AlertHub) RemoveHookSink ¶ added in v0.12.44
func (h *AlertHub) RemoveHookSink(sink HookEventSink)
RemoveHookSink unregisters a hook event sink. No-op if the sink was never registered. Matching is by interface identity (pointer equality for pointer receivers).
func (*AlertHub) RemoveMCPSink ¶ added in v0.11.5
func (h *AlertHub) RemoveMCPSink(sink MCPAlertSink)
RemoveMCPSink unregisters an MCP session sink.
func (*AlertHub) RemoveStreamSink ¶ added in v0.12.36
func (h *AlertHub) RemoveStreamSink(sink *StreamSink)
RemoveStreamSink unregisters a stream sink and closes its channel.
The close path is serialized against in-flight sends via the closed/refs atomics on StreamSink. We set closed=true first so any new producer observes it and exits cheaply, then spin-wait for refs==0 so any producer that was mid-flight before the closed flip can complete its send and decrement before we close(Ch). The spin yields the scheduler every iteration so we don't burn a core under contention.
Idempotent: a second call to RemoveStreamSink on the same sink is a no-op (the sink is no longer in the slice, so the close path is not re-entered).
func (*AlertHub) SetIncidentBus ¶ added in v0.13.0
SetIncidentBus wires the incident.Bus for dual-path mode. When the bus is non-nil and incidentPipeline is false, both paths run in parallel. When incidentPipeline is true, only the bus path is active for Deliver. A nil bus is valid (NopBus semantics — old path is unaffected).
func (*AlertHub) SetIncidentPipeline ¶ added in v0.13.0
SetIncidentPipeline sets the incident pipeline flag. When true, Deliver suppresses MCPAlertSink and OverlayAlertSink fan-out; StreamSink is unaffected. Default is false (old behaviour, dual-path observability mode).
func (*AlertHub) SetOverlaySink ¶ added in v0.11.5
func (h *AlertHub) SetOverlaySink(sink OverlayAlertSink)
SetOverlaySink sets the overlay (PTY stdin) delivery sink.
func (*AlertHub) SetProxyBroadcaster ¶ added in v0.13.0
func (h *AlertHub) SetProxyBroadcaster(pb ProxyBroadcaster)
SetProxyBroadcaster registers a broadcaster for sending alert toasts to connected browser overlays. A nil value disables proxy broadcasts.
func (*AlertHub) SetPushConfig ¶ added in v0.12.36
func (h *AlertHub) SetPushConfig(pc *config.PushConfig)
SetPushConfig sets the push channel configuration. When set, Deliver checks each channel before dispatching. A nil config means all channels are enabled (universal default).
type AlertStoreFilter ¶ added in v0.12.0
type AlertStoreFilter = alert.AlertStoreFilter
AlertStoreFilter is an alias for alert.AlertStoreFilter.
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. Auto-restart is disabled by default — users restart manually from the overlay or via MCP tools. Enable explicitly in .agnt.kdl with `auto-restart true`.
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 AutostartBroadcastFunc ¶ added in v0.12.40
type AutostartBroadcastFunc func(projectPath string, event AutostartProgress)
AutostartBroadcastFunc receives a stamped progress event for fan-out to external observers (alert hub, monitor stream, etc.). It is invoked from the manager's drain goroutine while holding no locks. The function MUST be non-blocking and MUST NOT panic — the manager treats it as a fire-and forget sink and does not recover.
projectPath is the normalized handle key. event has ProjectPath and Timestamp fields already populated by the manager.
type AutostartHandle ¶ added in v0.12.40
type AutostartHandle struct {
// contains filtered or unexported fields
}
AutostartHandle represents a single in-flight (or completed) autostart run for a specific project path. Handles are returned by AutostartManager and can be shared between multiple callers via GetOrCreate.
A handle goes through exactly one lifetime: created, running, done. Once Done() has fired, Result() and Progress() remain stable and safe to read.
func (*AutostartHandle) Cancel ¶ added in v0.12.40
func (h *AutostartHandle) Cancel()
Cancel cancels the in-flight autostart context. Calling Cancel on a handle whose run has already completed is a safe no-op.
func (*AutostartHandle) Done ¶ added in v0.12.40
func (h *AutostartHandle) Done() <-chan struct{}
Done returns a channel that is closed once the autostart run has finished. Callers can use this to block until completion or to poll via select.
func (*AutostartHandle) Progress ¶ added in v0.12.40
func (h *AutostartHandle) Progress() []AutostartProgress
Progress returns a defensive copy of all progress events observed so far. Late joiners calling this after completion receive the full history.
func (*AutostartHandle) ProjectPath ¶ added in v0.12.40
func (h *AutostartHandle) ProjectPath() string
ProjectPath returns the normalized project path this handle tracks.
func (*AutostartHandle) Result ¶ added in v0.12.40
func (h *AutostartHandle) Result() *AutostartResult
Result returns the final AutostartResult once the run has completed. Returns nil if the run is still in flight.
type AutostartManager ¶ added in v0.12.40
type AutostartManager struct {
// contains filtered or unexported fields
}
AutostartManager coordinates at-most-one autostart run per project path. Callers invoke GetOrCreate with a startFn; the first caller for a given path starts the run, and subsequent callers receive the same handle.
All operations are safe for concurrent use. The registry itself is lock-free: it relies on sync.Map.LoadOrStore for exactly-once semantics.
If a non-nil broadcast callback was provided to NewAutostartManagerWith Broadcast, the drain goroutine invokes it for every progress event (including the synthetic PhaseDone) AFTER recording the event in the handle. This ordering means a subscriber that observes a PhaseDone broadcast and immediately reads handle.Result() is guaranteed to see a populated result. The callback is invoked while holding no handle locks so subscribers cannot deadlock with Progress()/Result() callers.
func NewAutostartManager ¶ added in v0.12.40
func NewAutostartManager() *AutostartManager
NewAutostartManager returns a ready-to-use AutostartManager with no broadcast callback. Equivalent to NewAutostartManagerWithBroadcast(nil).
func NewAutostartManagerWithBroadcast ¶ added in v0.12.40
func NewAutostartManagerWithBroadcast(broadcast AutostartBroadcastFunc) *AutostartManager
NewAutostartManagerWithBroadcast returns an AutostartManager that fans every stamped progress event out to the supplied broadcast callback. Pass nil to disable broadcasting (equivalent to NewAutostartManager).
func (*AutostartManager) Cancel ¶ added in v0.12.40
func (m *AutostartManager) Cancel(projectPath string)
Cancel cancels the handle for projectPath, if one exists. No-op if no handle is registered or the handle has already completed.
func (*AutostartManager) CancelAll ¶ added in v0.12.51
func (m *AutostartManager) CancelAll()
CancelAll cancels every in-flight autostart handle. Called by Daemon.Stop to unblock goroutines that are waiting inside RunAutostartAsync before the ProcessManager shuts down, preventing a data race between the autostart goroutine's ProcessManager.Start call and ProcessManager.Shutdown.
func (*AutostartManager) Get ¶ added in v0.12.40
func (m *AutostartManager) Get(projectPath string) *AutostartHandle
Get returns the handle for projectPath, or nil if none exists.
func (*AutostartManager) GetOrCreate ¶ added in v0.12.40
func (m *AutostartManager) GetOrCreate(projectPath string, startFn AutostartStartFunc) *AutostartHandle
GetOrCreate returns the existing handle for projectPath if one is present, otherwise creates a new handle and launches startFn in a background goroutine.
Exactly-once start is guaranteed: concurrent callers with the same projectPath all receive the same handle, but startFn is invoked only once.
startFn receives:
- a cancellable context (cancelled via Cancel or handle.Cancel)
- a buffered progress channel; callers should emit via emitProgress and MUST NOT close the channel themselves (the manager closes it after startFn returns).
The returned handle is not guaranteed to be done: use handle.Done() to wait for completion.
func (*AutostartManager) Progress ¶ added in v0.12.40
func (m *AutostartManager) Progress(projectPath string) []AutostartProgress
Progress returns a snapshot of progress events for projectPath, or nil if no handle exists for that path.
func (*AutostartManager) Remove ¶ added in v0.12.40
func (m *AutostartManager) Remove(projectPath string)
Remove deletes the handle for projectPath from the registry. The handle itself is not cancelled; call Cancel separately if that is desired. This is intended for session-cleanup paths that want the next session to start fresh.
type AutostartPhase ¶ added in v0.12.40
type AutostartPhase int
AutostartPhase identifies the phase of an autostart progress event.
const ( // PhaseInitiated is emitted immediately when the autostart run begins, // before any scanning or config loading. Allows late-joiner tests and // observers to distinguish "not started yet" from "in progress". PhaseInitiated AutostartPhase = iota // PhaseScriptStarting is emitted when a script's launch goroutine begins. PhaseScriptStarting // PhaseDependencyWaitStart is emitted when a script begins waiting for // a declared dependency to become ready. PhaseDependencyWaitStart // PhaseDependencyReady is emitted when a declared dependency signals ready. PhaseDependencyReady // PhaseScriptStarted is emitted after the process is successfully started. PhaseScriptStarted // PhaseScriptFailed is emitted when a script fails to start. PhaseScriptFailed // PhaseLayerComplete is emitted after every script in a topological layer // has finished its start attempt (success or failure). PhaseLayerComplete // PhaseDone is emitted once by the AutostartManager goroutine after the // whole autostart run has returned and the final result is stored. PhaseDone )
type AutostartProgress ¶ added in v0.12.40
type AutostartProgress struct {
ProjectPath string // Normalized project path (stamped by handle)
Phase AutostartPhase
Script string // Script name (empty for layer-level events)
Dependency string // Dependency name (for dependency phases)
Layer int // Topological layer index
Err error // Non-nil for PhaseScriptFailed
Timestamp time.Time // Stamped by handle on receive
}
AutostartProgress reports progress during asynchronous autostart.
It is populated by emitProgress and, when routed through an AutostartHandle, has ProjectPath and Timestamp stamped automatically by the handle's drain goroutine.
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"`
PortConflicts []PortConflict `json:"port_conflicts,omitempty"`
PortsCleared []PortConflict `json:"ports_cleared,omitempty"`
}
type AutostartStartFunc ¶ added in v0.12.40
type AutostartStartFunc func(ctx context.Context, progress chan<- AutostartProgress) *AutostartResult
AutostartStartFunc is the signature used by AutostartManager to kick off an autostart run. It receives a context that will be cancelled when AutostartManager.Cancel is called, and a progress channel that the callee should close when it is done emitting events. The returned result becomes the handle's final Result() value.
type BrowserInfo ¶ added in v0.11.1
BrowserInfo holds browser manager statistics.
type CheckResult ¶ added in v0.12.21
type CheckResult struct {
Name string `json:"name"`
Status string `json:"status"`
Message string `json:"message"`
Details interface{} `json:"details,omitempty"`
Fix string `json:"fix,omitempty"`
}
CheckResult is a single health check outcome.
type CleanupResult ¶ added in v0.12.36
type CleanupResult struct {
Killed []KilledProcess
}
CleanupResult describes what happened during a cleanup pass.
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
NewClientWithPath creates a new daemon client with a specific socket path.
func (*Client) AlertClear ¶ added in v0.12.0
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
AutomationStatus gets the status of an automation session.
func (*Client) AutomationStop ¶ added in v0.11.1
AutomationStop stops an automation session.
func (*Client) AutostartClearPorts ¶ added in v0.12.36
AutostartClearPorts kills port blockers and resumes autostart for a project.
func (*Client) AutostartContinue ¶ added in v0.12.36
AutostartContinue resumes autostart without killing port blockers.
func (*Client) AutostartRun ¶ added in v0.12.44
AutostartRun triggers a non-interactive autostart run for a project path. Used by the MCP InitializedHandler in channel mode. The daemon-side handler overrides port-conflict "prompt" to "skip" because there is no stdin.
func (*Client) BroadcastActivity ¶
BroadcastActivity broadcasts an activity state update to connected browsers via specified proxies.
func (*Client) BroadcastOutputPreview ¶ added in v0.8.0
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
BrowserStatus gets the status of a browser instance.
func (*Client) BrowserStop ¶ added in v0.11.1
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 ¶
ChaosClear clears all chaos rules and resets stats for a proxy.
func (*Client) ChaosDisable ¶
ChaosDisable disables chaos injection on a proxy.
func (*Client) ChaosEnable ¶
ChaosEnable enables chaos injection on a proxy.
func (*Client) ChaosListPresets ¶
ChaosListPresets returns the list of available chaos presets.
func (*Client) ChaosListRules ¶
ChaosListRules lists all chaos rules for a proxy.
func (*Client) ChaosPreset ¶
ChaosPreset applies a preset chaos configuration to a proxy.
func (*Client) ChaosRemoveRule ¶
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 ¶
ChaosStats gets chaos statistics for a proxy.
func (*Client) ChaosStatus ¶
ChaosStatus gets the chaos status of a proxy.
func (*Client) CurrentPageClear ¶
CurrentPageClear clears page sessions.
func (*Client) CurrentPageGet ¶
CurrentPageGet gets details for a specific page session.
func (*Client) CurrentPageList ¶
CurrentPageList lists active page sessions.
func (*Client) Doctor ¶ added in v0.12.21
Doctor runs health checks and returns a diagnostic report.
func (*Client) HookSend ¶ added in v0.12.44
func (c *Client) HookSend(ctx context.Context, event string, payloadJSON json.RawMessage, tags map[string]string) error
HookSend enqueues a Claude Code hook event in the daemon's ring buffer and returns as fast as possible. The protocol is fire-and-ack: the daemon's verb handler pushes the event into an in-memory ring buffer and replies OK synchronously off the drain path, so the CLI's wall-clock cost is dominated by the connect + write + single-line read.
The total operation is bounded by hookSendDeadline. On deadline, refused connection, or EAGAIN we return a typed sentinel error so the CLI can map it to silent exit 0 — hooks must never block Claude's tool call with a visible error.
Unlike the rest of this client HookSend does NOT reuse Client.conn. The shared Conn does not expose SetWriteDeadline on its underlying socket, and the hook hot path needs a deadline strictly scoped to this one call so that a slow or wedged daemon on a previous request cannot stretch into the hook. A dedicated short-lived socket is the cleanest way to get that containment on both Unix and Windows.
func (*Client) IncidentQuery ¶ added in v0.13.0
func (c *Client) IncidentQuery(filter protocol.IncidentQueryFilter) (*protocol.IncidentQueryResult, error)
IncidentQuery queries the incident inbox for the current session.
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 ¶
IsConnected returns whether the client is connected.
func (*Client) OverlayClear ¶
OverlayClear clears the overlay endpoint configuration.
func (*Client) OverlayGet ¶
OverlayGet gets the current overlay endpoint configuration.
func (*Client) OverlaySet ¶
OverlaySet sets the overlay endpoint URL.
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 ¶
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 ¶
ProcOutput gets the output of a process.
func (*Client) ProcRestart ¶ added in v0.8.0
ProcRestart restarts a single process by ID.
func (*Client) ProcRun ¶ added in v0.12.51
func (c *Client) ProcRun(name string, cfg ProcRunConfig) (map[string]interface{}, error)
ProcRun starts an admin-aware process via PROC RUN. Unlike the top-level RUN verb (Client.Run), PROC RUN routes through the daemon's StartScriptExplicit so the new process becomes a process-kind admin registry entry visible in SCRIPT LIST and the overlay admin screen.
func (*Client) ProcRunGroup ¶ added in v0.13.5
func (c *Client) ProcRunGroup(cfg ProcRunGroupConfig) (map[string]interface{}, error)
ProcRunGroup launches a multi-process startup group via PROC RUN-GROUP. Cycle detection runs before any process launches; on cycle detection the request returns ErrInvalidArgs with the cycle description. Per- process kickoff results are returned in declaration order; agents poll PROC STATUS to observe individual processes transitioning from "pending" → "starting" → "running".
func (*Client) ProcStatus ¶
ProcStatus gets the status of a process.
func (*Client) ProxyList ¶
func (c *Client) ProxyList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)
ProxyList lists all proxies.
func (*Client) ProxyLogClear ¶
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 ¶
ProxyLogStats gets proxy log statistics.
func (*Client) ProxyRestart ¶ added in v0.8.0
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 ¶
ProxyStatus gets the status of a proxy.
func (*Client) ProxyToast ¶
ProxyToast sends a toast notification to connected browsers.
func (*Client) RestartAll ¶ added in v0.8.0
RestartAll restarts all running processes and proxies with their original configurations.
func (*Client) Run ¶
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) ScriptList ¶ added in v0.12.16
ScriptList lists all scripts for a project directory.
func (*Client) ScriptOutput ¶ added in v0.12.16
ScriptOutput retrieves output history for a named script.
func (*Client) ScriptRestart ¶ added in v0.12.16
ScriptRestart restarts a script by name.
func (*Client) ScriptStop ¶ added in v0.12.16
ScriptStop stops a script by name.
func (*Client) SessionAttach ¶ added in v0.7.12
SessionAttach attaches to a session found by directory ancestry.
func (*Client) SessionCancel ¶ added in v0.7.0
SessionCancel cancels a scheduled task.
func (*Client) SessionFind ¶ added in v0.7.12
SessionFind finds a session by directory ancestry.
func (*Client) SessionGenerateCode ¶ added in v0.7.0
SessionGenerateCode requests a new session code from the daemon.
func (*Client) SessionGet ¶ added in v0.7.0
SessionGet retrieves a specific session.
func (*Client) SessionHeartbeat ¶ added in v0.7.0
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) SessionRegisterWithContainment ¶ added in v0.12.41
func (c *Client) SessionRegisterWithContainment(code string, overlayPath string, projectPath string, command string, args []string, sessionPGID int, sessionJobHandle uint64) (map[string]interface{}, error)
SessionRegisterWithContainment registers a new session and reports both the Unix session pgid and the Windows Job Object handle for the PTY child subtree. Callers on Unix pass sessionPGID and 0 for sessionJobHandle; callers on Windows pass 0 for sessionPGID and the uint64 form of a windows.Handle for sessionJobHandle. The daemon invokes whichever containment path matches the running OS at cleanup time; both are safe no-ops when their corresponding field is unset.
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). On session shutdown the daemon will `killpg(sessionPGID, SIGTERM)` to reap every descendant the session produced — including background jobs the coding agent spawned via non-interactive bash. Pass 0 for the PGID on Windows or when the caller has no pgid to share.
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
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
SessionUnregister unregisters a session from the daemon.
func (*Client) SocketPath ¶ added in v0.8.0
SocketPath returns the socket path.
func (*Client) StartupLog ¶ added in v0.12.15
StartupLog queries the startup log from the daemon.
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) StreamEvents ¶ added in v0.12.36
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 and calls handler for each event received. The stream runs until ctx is cancelled or the connection drops.
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 ¶
TunnelStatus gets the status of a tunnel.
func (*Client) TunnelStop ¶
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 wraps go-cli-server/client.Conn. Use this type instead of importing go-cli-server/client directly to share a single connection across components.
Conn is distinct from Connection (server-side handler in connection.go).
Request Builder ¶
Conn exposes a fluent request builder instead of per-command methods:
result, err := conn.Request("PROC", "LIST").WithJSON(filter).JSON()
err := conn.Request("PROXY", "STOP", proxyID).OK()
Thread Safety ¶
Conn is thread-safe. Multiple goroutines can issue requests concurrently.
Auto-Reconnection ¶
If the connection drops, the next request will automatically reconnect.
func NewConn ¶ added in v0.7.8
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
Close closes the connection permanently. After Close, the Conn cannot be reused.
func (*Conn) Disconnect ¶ added in v0.7.8
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
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
IsConnected returns whether the connection is currently established.
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
SetTimeout sets the default timeout for operations.
func (*Conn) SocketPath ¶ added in v0.7.8
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 NewForTest ¶ added in v0.13.0
func NewForTest(t *testing.T, cfg DaemonConfig) *Daemon
NewForTest constructs a Daemon and brings it up via the minimum wiring shared with Start() (registerCommands, hub start, scheduler, URL tracker, proxy event loop, hook drain), then registers a t.Cleanup that calls Stop with a 5s timeout.
The function takes *testing.T so it can ONLY be linked from _test.go files. That signature is the build-time fence — no production caller can construct a *testing.T, so a build tag is unnecessary. Callers outside test code that try to invoke NewForTest will fail compilation at the testing.T parameter.
Test startup contract — what NewForTest SKIPS vs Start():
setupDebugLogging — skipped: tests don't need the rotated log file
cleanupOrphans — skipped: walks the host PID tracker, can kill
unrelated processes owned by the same uid
startupPortCleanup — skipped: scans persisted proxy state and
issues kill(2) on whatever PID owns the port
startupOrphanPGIDScan — skipped: walks /proc looking for pgids whose
leader is dead but members are alive (already
gated by OrphanScanEnabled which defaults to
false for tests; this skip is belt-and-braces)
restoreProxies — skipped: replays persisted ProxyConfigs into
a fresh proxy manager, which a fresh test
daemon almost never wants
updateChecker.Start — skipped: spawns a 24h ticker goroutine that
contacts GitHub
Test startup contract — what NewForTest STILL RUNS:
registerCommands — required: the hub needs every agnt verb
registered before it accepts connections
SetSessionCleanup — required: tests that drop sessions need the
deferred-cleanup callback wired
hub.Start — required: opens the unix socket / named pipe
and starts the accept loop
scheduler.Start — required: tests that exercise the scheduler
need it running; cheap and idempotent
urlTracker.Start — required: feeds the proxy event channel
handleProxyEvents — required: drains d.proxyEvents
drainHooks — required: drains hookRing for hook-event tests
Production Start() runs the same bootstrap() helper plus the four skipped startup tasks plus updateChecker.Start, so production behavior is byte-identical with or without this split.
See .claude/rules/daemon-architecture.md "Test startup contract" for the rationale and invariants this split must preserve.
func (*Daemon) AlertStore ¶ added in v0.12.0
func (d *Daemon) AlertStore() *ProcessAlertStore
AlertStore returns the process alert store.
func (*Daemon) ApplyAlertsConfig ¶ added in v0.13.7
func (d *Daemon) ApplyAlertsConfig(cfg *config.AlertsConfig)
ApplyAlertsConfig pushes the alerts block from a project's AgntConfig into the daemon's runtime alert subsystems: the HoldBuffer's per-proxy hold window and cascade patterns, and the HealthTracker's transport outage thresholds. Safe to call multiple times — the latest values win. A nil cfg restores defaults.
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
BrowserManager returns the browser manager.
func (*Daemon) CleanupSessionResources ¶ added in v0.7.8
CleanupSessionResources performs immediate session resource cleanup. Used for explicit UNREGISTER and direct calls. For connection drops, use CleanupSessionResourcesDeferred instead.
func (*Daemon) CleanupSessionResourcesDeferred ¶ added in v0.12.36
CleanupSessionResourcesDeferred schedules resource cleanup with a grace period. Called when a connection drops unexpectedly. The ResilientClient may reconnect and re-register the same session within seconds — the grace period prevents killing processes during that window. If the session is re-registered before the timer fires, the cleanup is cancelled entirely.
func (*Daemon) FlushScriptProxyConnections ¶ added in v0.12.8
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
GetSession retrieves a session by code.
func (*Daemon) IncidentBus ¶ added in v0.13.0
IncidentBus returns the incident event bus.
func (*Daemon) LoadURLMatchersForProcess ¶ added in v0.8.0
func (*Daemon) OverlayEndpoint ¶
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 synchronously. It delegates to RunAutostartAsync with a nil progress channel.
func (*Daemon) RunAutostartAsync ¶ added in v0.12.40
func (d *Daemon) RunAutostartAsync( ctx context.Context, projectPath string, progress chan<- AutostartProgress, ) *AutostartResult
RunAutostartAsync loads .agnt.kdl config from projectPath and starts configured processes/proxies. Progress events are emitted to the progress channel (if non-nil) after each milestone: script start, dependency wait, dependency ready, script failure, and layer completion.
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
- Context cancellation replaces fixed dependency timeouts
func (*Daemon) RunAutostartNonInteractive ¶ added in v0.12.44
func (d *Daemon) RunAutostartNonInteractive(ctx context.Context, projectPath string) *AutostartResult
RunAutostartNonInteractive runs autostart for a non-interactive caller (the MCP InitializedHandler). It is identical to RunAutostart except that the "prompt" port-conflict policy falls back to "skip" because there is no stdin for the interactive prompt. A warning is logged for each conflict that is skipped.
func (*Daemon) RunDoctor ¶ added in v0.12.21
func (d *Daemon) RunDoctor(ctx context.Context, projectPath string) *DoctorReport
RunDoctor runs all health checks concurrently and returns a structured report.
func (*Daemon) ScriptRegistry ¶ added in v0.12.16
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) SetOnShutdown ¶ added in v0.12.23
func (d *Daemon) SetOnShutdown(fn func())
SetOnShutdown registers a callback invoked when the hub receives a remote SHUTDOWN command. The host process typically uses this to cancel its own signal context so it exits cleanly instead of lingering (important on Windows where Unix signals are not delivered).
func (*Daemon) SetOverlayEndpoint ¶
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) StartProcessGroup ¶ added in v0.13.5
func (d *Daemon) StartProcessGroup( ctx context.Context, projectPath string, processes []GroupProcess, timeout time.Duration, ) GroupResult
StartProcessGroup orchestrates a PROC RUN-GROUP launch.
Performs cycle detection FIRST via config.TopologicalSort. If a cycle is detected, returns immediately with Err set — no process is launched. If a process declares a dep that does not exist in the group, that is also a fatal error reported through Err.
Otherwise, all processes are kicked off via StartProcessWithDeps. Layer-zero processes (no deps) start synchronously; processes with deps spawn goroutines that wait on the readySignaler. The function returns when all kickoffs have been initiated — actual readiness is observed via PROC STATUS polling.
timeout applies as the per-process default depends-on timeout when a GroupProcess does not specify its own. Pass 0 to use DefaultDependsOnTimeout.
func (*Daemon) StartProcessWithDeps ¶ added in v0.13.5
func (d *Daemon) StartProcessWithDeps( ctx context.Context, name string, scriptCfg *config.ScriptConfig, projectPath string, deps []string, timeout time.Duration, ) StartProcessResult
StartProcessWithDeps starts a process via PROC RUN, optionally gated on `depends_on` dependencies.
If deps is empty: delegates synchronously to StartScriptExplicit. If deps is non-empty: registers a pending entry, spawns a wait goroutine, and returns immediately with State == "pending".
timeout applies to the entire dependency wait window. Zero means use DefaultDependsOnTimeout. Negative means wait indefinitely (parent ctx only) — only intended for callers that explicitly want autostart-style "wait until session dies" semantics.
The launch goroutine resolves dependencies in declaration order. The per-dep wait uses a derived context that is cancelled by either the per-process deadline or the parent ctx. On dependency timeout, the pending entry is marked PendingFailed with reason "dependency_timeout:<dep>" and the script registry entry transitions to StateFailed before the goroutine exits. The dependent process is NOT launched on timeout.
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) StartScriptExplicit ¶ added in v0.12.51
func (d *Daemon) StartScriptExplicit(ctx context.Context, name string, scriptCfg *config.ScriptConfig, projectPath string, proxyConfigs map[string]*config.ProxyConfig) error
StartScriptExplicit starts a single script by config. Canonical entrypoint shared by the autostart path (via autostartScript) and the MCP PROC RUN hub handler. Owns: scriptConfigs cache, scriptRegistry.Register, command resolution (Run / Command / package-manager detection), state transitions, expectedPorts resolution, and the StartScript call. On failure, sets ScriptEntry.State = StateFailed, records LastError, increments FailCount, and returns a formatted error that includes the resolved command, working directory, and (when available) the trailing process output.
proxyConfigs is used only for port resolution via getExpectedPortsForScript. Callers that don't have a proxyConfigs map (MCP ad-hoc processes) pass nil; the helper tolerates nil and falls back to command-line / PORT env scanning.
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) StopAllResources ¶ added in v0.7.6
func (*Daemon) TunnelManager ¶
TunnelManager returns the tunnel manager.
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
// CleanupGracePeriod is how long to wait before cleaning up session
// resources after a connection drops. Allows ResilientClient reconnects
// to cancel the cleanup. Set to 0 for immediate cleanup (tests).
// Default: 5s
CleanupGracePeriod time.Duration
// StartupMonitorTimeout is how long monitorStartupFailure watches a newly
// started process for early exit before declaring it healthy. Set to a
// short value in tests to avoid the 3s × N-scripts wall-clock cost.
// Default: 3s
StartupMonitorTimeout time.Duration
// OrphanScanEnabled gates startupOrphanPGIDScan. Default zero-value
// (false) is the test-safe default: tests must NEVER walk host /proc
// or issue real kill(2) syscalls against pgids owned by other host
// processes under the same uid.
//
// Production sets this to true explicitly in cmd/agnt/daemon.go.
// One production site vs 40+ test constructors made positive naming +
// explicit-production the better trade than negative naming +
// explicit-tests.
//
// Replaces the legacy AGNT_DISABLE_ORPHAN_SCAN env var fence; see iter 15
// (task 6btkGG5QUGTL) for the migration. Never expose this field to end
// users — it is an internal test-safety knob, not a product feature.
OrphanScanEnabled bool
}
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"`
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 SessionInfo `json:"session_info"`
SchedulerInfo SchedulerInfo `json:"scheduler_info"`
UpdateInfo *updater.UpdateInfo `json:"update_info,omitempty"`
}
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:
- Acquire upgrade lock (prevents concurrent upgrades)
- Connect to running daemon and get current version
- Request graceful shutdown (stops all processes)
- Wait for daemon to exit
- Clean up stale socket/PID files
- Start new daemon binary
- Wait for new daemon to be ready
- Verify new daemon version
- Release upgrade lock
type DoctorReport ¶ added in v0.12.21
type DoctorReport struct {
Status string `json:"status"`
Checks []CheckResult `json:"checks"`
}
DoctorReport is the aggregate of all health checks.
type DriftMetricsSnapshot ¶ added in v0.13.0
DriftMetricsSnapshot holds a point-in-time snapshot of the dual-path event counters. OldPathCount counts Deliver() calls that reached legacy sinks; NewPathCount counts events acknowledged via IncrNewPath() (called by the incident adapter layer). The two counts converge over time when both paths are active. A growing delta indicates a bug in adapter wiring.
type DuplicateGroup ¶ added in v0.12.36
DuplicateGroup holds processes grouped by (command, projectPath).
type DuplicateScanner ¶ added in v0.12.36
type DuplicateScanner struct {
// Notification callback — sends a message to the AI agent via PTY overlay.
// Set by the caller (pty_common.go integration point).
OnNotify func(message string)
// contains filtered or unexported fields
}
DuplicateScanner detects and kills duplicate dev server processes that are not managed by the daemon.
func NewDuplicateScanner ¶ added in v0.12.36
func NewDuplicateScanner(d *Daemon) *DuplicateScanner
NewDuplicateScanner creates a new scanner bound to a daemon instance.
func (*DuplicateScanner) LastScanAt ¶ added in v0.12.40
func (s *DuplicateScanner) LastScanAt() time.Time
LastScanAt returns the timestamp of the most recent completed scan.
func (*DuplicateScanner) ScanAndCleanup ¶ added in v0.12.36
func (s *DuplicateScanner) ScanAndCleanup(projectPath string) *CleanupResult
ScanAndCleanup scans for duplicates and kills them. If projectPath is non-empty, only processes under that path are considered. If projectPath is empty, all active project paths are scanned.
The lock is held only during the scan phase (process listing + duplicate detection). Kills happen outside the lock to avoid blocking concurrent callers during SIGTERM + grace period waits.
func (*DuplicateScanner) ScanForProject ¶ added in v0.12.36
func (s *DuplicateScanner) ScanForProject(projectPath string) *CleanupResult
ScanForProject runs a scan for a specific project path. Returns the cleanup result. The caller is responsible for notification.
func (*DuplicateScanner) Start ¶ added in v0.12.36
func (s *DuplicateScanner) Start()
Start begins the periodic duplicate scan (every 30 seconds).
func (*DuplicateScanner) Stop ¶ added in v0.12.36
func (s *DuplicateScanner) Stop()
Stop cancels the periodic scan and waits for the goroutine to finish.
type GroupProcess ¶ added in v0.13.5
type GroupProcess struct {
Name string `json:"name"`
Run string `json:"run,omitempty"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Cwd string `json:"cwd,omitempty"`
Env map[string]string `json:"env,omitempty"`
URLMatchers []string `json:"url_matchers,omitempty"`
AutoRestart bool `json:"auto_restart,omitempty"`
DependsOn []string `json:"depends_on,omitempty"`
}
GroupProcess describes a single process inside a PROC RUN-GROUP payload. Mirrors procRunPayload but adds Name (which PROC RUN takes as a positional verb arg).
type GroupResult ¶ added in v0.13.5
type GroupResult struct {
// Processes lists per-process kickoff results, in declaration order.
Processes []StartProcessResult
// Err is set when group launch failed before any process started
// (cycle detection, missing deps). When non-nil, Processes is empty.
Err error
}
GroupResult captures the outcome of a PROC RUN-GROUP launch.
type HealthTracker ¶ added in v0.12.41
type HealthTracker struct {
// contains filtered or unexported fields
}
HealthTracker observes process state for the purpose of gating proxy error broadcasts. It is owned by the Daemon and populated lazily.
func NewHealthTracker ¶ added in v0.12.41
func NewHealthTracker(procLookup func(string) (*goprocess.ManagedProcess, error), emit func(proxy.LogEntry, string)) *HealthTracker
NewHealthTracker constructs a HealthTracker with production lookups. Either argument may be nil for tests that supply their own.
func (*HealthTracker) Forget ¶ added in v0.12.41
func (h *HealthTracker) Forget(processID string)
Forget drops tracking for a process. Called when the daemon cleans up a script (ScriptStopped event). Bounded by sync.Map.Delete.
func (*HealthTracker) ForgetProxy ¶ added in v0.13.7
func (h *HealthTracker) ForgetProxy(proxyID string)
ForgetProxy drops transport-tracking state for proxyID. Called when a proxy is fully cleaned up.
func (*HealthTracker) IsDaemonInitiatedStop ¶ added in v0.12.41
func (h *HealthTracker) IsDaemonInitiatedStop(processID string) bool
IsDaemonInitiatedStop reports whether MarkDaemonInitiatedStop was called for processID and the flag has not been consumed yet.
func (*HealthTracker) IsInSuppressionWindow ¶ added in v0.12.41
func (h *HealthTracker) IsInSuppressionWindow(proxyID, linkedProcessID string) bool
IsInSuppressionWindow returns true when proxyID's linked process is in a transient/unhealthy state and its error broadcasts should be suppressed.
Behaviour matrix (see also .claude/rules/daemon-lifecycle.md):
Process state broadcast? Pending yes (proxy hasn't seen its first start yet) Starting no (suppress: rebuild in progress) Running, within grace no (suppress: 5s post-return-to-healthy) Running, past grace yes Stopping no (suppress: restart triggered) Failed no (suppress: brief failure window) Stopped yes (Dead — errors ARE the story)
linkedProcessID may be empty for unlinked proxies, in which case the check returns false unconditionally (no suppression).
This call is on the hot path of every proxy log entry. It is lock-free for the steady-state Running case (just two atomic loads). The slow path runs only when an edge is detected, and is bounded by a per-process mutex (no global locks).
func (*HealthTracker) IsProxyInTransportOutage ¶ added in v0.13.7
func (h *HealthTracker) IsProxyInTransportOutage(proxyID string) bool
IsProxyInTransportOutage reports whether the proxy is currently in synthetic transport outage. Lock-free single atomic load.
func (*HealthTracker) LastHealthyAt ¶ added in v0.12.41
func (h *HealthTracker) LastHealthyAt(processID string) time.Time
LastHealthyAt returns the wall-clock time processID most recently transitioned INTO Running, or the zero time if it never has.
func (*HealthTracker) LastObservedState ¶ added in v0.12.41
func (h *HealthTracker) LastObservedState(processID string) goprocess.ProcessState
LastObservedState returns the most recent process state observed by the tracker. Returns the zero value (StatePending) if no state has been observed yet — the caller should treat that as "unknown".
func (*HealthTracker) LastRebuildSignal ¶ added in v0.12.41
func (h *HealthTracker) LastRebuildSignal(processID string) time.Time
LastRebuildSignal returns the most recent rebuild-signal timestamp for processID, or the zero time if none has been recorded.
func (*HealthTracker) MarkDaemonInitiatedStop ¶ added in v0.12.41
func (h *HealthTracker) MarkDaemonInitiatedStop(processID string)
MarkDaemonInitiatedStop records that the daemon (not the OS, not the child) is about to stop or restart processID. The flag is consumed by the OutageClassifier — while set, a subsequent outage is biased toward "Rebuild" rather than "Crash". Callers MUST set this immediately before issuing the stop, never after, otherwise the classifier may observe the stop edge before the flag is set.
Safe to call before any state has been observed for the process: this creates the per-process tracker entry on demand.
func (*HealthTracker) MaybeCloseGraceWindow ¶ added in v0.12.41
func (h *HealthTracker) MaybeCloseGraceWindow(proxyID, linkedProcessID string)
MaybeCloseGraceWindow inspects the linked process and, if it is now Running with the grace period expired, emits the close marker. This is called by the broadcast gate just before allowing an entry through, so the marker reaches the agent at the same instant suppression actually stops. Idempotent — only emits once per close edge.
func (*HealthTracker) OutageStartedAt ¶ added in v0.12.41
func (h *HealthTracker) OutageStartedAt(processID string) time.Time
OutageStartedAt returns the wall-clock time processID most recently LEFT the Running state, or the zero time if it is currently healthy or has never been observed.
func (*HealthTracker) PreviousObservedState ¶ added in v0.12.41
func (h *HealthTracker) PreviousObservedState(processID string) goprocess.ProcessState
PreviousObservedState returns the state observed immediately before the current LastObservedState. Used by the classifier to detect direct Running → Failed transitions without a Stopping intermediate. Returns StatePending if the process has never transitioned.
func (*HealthTracker) RecordRebuildSignal ¶ added in v0.12.41
func (h *HealthTracker) RecordRebuildSignal(processID string)
RecordRebuildSignal stamps the current time as the most recent moment the AlertScanner detected a rebuild/compile pattern in processID's output. Read by the OutageClassifier as evidence the next stop edge is part of an in-progress rebuild rather than a crash.
func (*HealthTracker) RecordRecoverySignal ¶ added in v0.13.7
func (h *HealthTracker) RecordRecoverySignal(proxyID string, ts time.Time)
RecordRecoverySignal records a successful upstream interaction (HTTP 2xx/3xx, WS open) for proxyID. If the proxy is in synthetic outage and the recovery debounce has elapsed since outage entry, the proxy exits outage and onTransportRecovery fires. Calls outside outage are cheap no-ops.
func (*HealthTracker) RecordTransportError ¶ added in v0.13.7
func (h *HealthTracker) RecordTransportError(proxyID string, ts time.Time)
RecordTransportError records a transport-layer error timestamp for proxyID and flips the proxy into synthetic outage if the err count within the configured window meets the threshold. Hot path is a single map load and a per-proxy mutex hold bounded by transportErrRingSize.
func (*HealthTracker) SetOnTransportRecovery ¶ added in v0.13.7
func (h *HealthTracker) SetOnTransportRecovery(fn func(proxyID string))
SetOnTransportRecovery registers a callback fired when a proxy exits synthetic transport outage. The callback runs synchronously inside the per-proxy mutex; it must be non-blocking. Pass nil to clear.
func (*HealthTracker) SetTransportConfig ¶ added in v0.13.7
func (h *HealthTracker) SetTransportConfig(cfg TransportConfig)
SetTransportConfig replaces the transport-signal config. Safe to call at any point; readers see the new config on subsequent transport signals.
type HoldBuffer ¶ added in v0.13.7
type HoldBuffer struct {
// contains filtered or unexported fields
}
HoldBuffer suppresses transport-cascade noise during proxy outages. One instance is shared across all proxies in the daemon; per-proxy state lives in the entries map keyed by (proxyID|fingerprint).
func NewHoldBuffer ¶ added in v0.13.7
func NewHoldBuffer(cfg *config.OutageHoldConfig, emit HoldEmitFn) *HoldBuffer
NewHoldBuffer constructs a buffer with the given config and emit callback. The buffer goroutine starts immediately. cfg may be nil; the buffer behaves as enabled with default values when so.
func (*HoldBuffer) Forget ¶ added in v0.13.7
func (b *HoldBuffer) Forget(proxyID string)
Forget drops all held state for proxyID without emission. Called when a proxy is fully cleaned up.
func (*HoldBuffer) Hold ¶ added in v0.13.7
func (b *HoldBuffer) Hold(entry proxy.LogEntry, proxyID, fingerprint string, classifyCascade bool)
Hold pushes entry into the buffer for proxyID. classifyCascade is the caller's classification of whether the entry is a transport / JS cascade message (drop on recovery) versus a genuine error (emit on recovery). For transport diagnostics, callers always pass true. For browser-JS errors, callers pass the result of MatchesJSCascade. For HTTP entries, callers pass true (5xx during an outage is upstream flapping; the gate only forwards 5xx when not in outage).
Non-blocking: queues onto the loop channel with a default branch so pathological backpressure drops the held entry rather than stalling the gate.
func (*HoldBuffer) MatchesJSCascade ¶ added in v0.13.7
func (b *HoldBuffer) MatchesJSCascade(msg string) bool
MatchesJSCascade reports whether msg matches any configured cascade pattern. Case-insensitive substring match. Exposed for callers that classify entries before calling Hold.
func (*HoldBuffer) OnRecovery ¶ added in v0.13.7
func (b *HoldBuffer) OnRecovery(proxyID string)
OnRecovery signals that proxyID has exited transport outage. Cascade entries are dropped; non-cascade entries are emitted immediately.
func (*HoldBuffer) Stop ¶ added in v0.13.7
func (b *HoldBuffer) Stop()
Stop terminates the buffer loop. Pending entries are dropped without emission — callers should drain via Forget or wait for window expiry before stopping in production.
type HoldEmitFn ¶ added in v0.13.7
HoldEmitFn is the callback invoked when the buffer decides to release a held entry. The implementation is responsible for fanning the entry to all consumers (AlertHub stream sinks, incident bus adapters, etc).
type HookEvent ¶ added in v0.12.44
type HookEvent struct {
Event string `json:"event"`
Payload json.RawMessage `json:"payload,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
ReceivedAt time.Time `json:"received_at"`
SessionID string `json:"session_id,omitempty"`
ProjectPath string `json:"project_path,omitempty"`
Agent string `json:"agent,omitempty"`
}
HookEvent is the in-memory representation of a single Claude Code hook invocation after it has been pushed into the daemon ring buffer. The raw wire form is protocol.HookPayload; this struct wraps it with daemon-side provenance fields so downstream consumers (phase 3 fan-out to the overlay panel, StreamSink, etc) can filter and attribute events.
Payload stays as json.RawMessage on purpose: the daemon has no schema for the opaque Claude Code hook payload and re-marshalling would just burn CPU on the drain path. Consumers that care about specific fields unmarshal into their own local struct.
type HookEventSink ¶ added in v0.12.44
type HookEventSink interface {
EmitHookEvent(ev HookEvent)
}
HookEventSink receives Claude Code hook events drained from the daemon ring buffer. Implementations must be non-blocking: BroadcastHookEvent fans out under the hub's read lock and a slow sink would stall the drain goroutine. Sinks that need to queue should own an internal buffer and drop on overflow.
type KillResult ¶ added in v0.12.36
type KillResult struct {
PortConflict
Killed bool `json:"killed"`
Error string `json:"error,omitempty"`
}
KillResult reports what happened for each conflict.
type KilledProcess ¶ added in v0.12.36
KilledProcess records a single killed duplicate.
type MCPAlertSink ¶ added in v0.11.5
MCPAlertSink delivers alert messages via MCP session notifications.
type OutageClassifier ¶ added in v0.12.41
type OutageClassifier struct {
// contains filtered or unexported fields
}
OutageClassifier wraps HealthTracker with classification + the per- process side-table. Construction always pairs the two — the classifier is useless without a tracker.
func NewOutageClassifier ¶ added in v0.12.41
func NewOutageClassifier( tracker *HealthTracker, procLookup func(string) (*goprocess.ManagedProcess, error), emit func(proxy.LogEntry, string), proxyForProcess func(string) string, ) *OutageClassifier
NewOutageClassifier wires a classifier on top of an existing HealthTracker. All function arguments may be nil for tests; in that case the classifier degrades to "always healthy" / no emission.
The classifier registers callbacks on the tracker so that outage edges observed by the tracker hot path automatically populate the classifier crash-rate ring buffer and reset one-shot markers. The tracker MUST not have any other classifier already attached.
func (*OutageClassifier) Classify ¶ added in v0.12.41
func (c *OutageClassifier) Classify(processID string) OutageType
Classify returns the OutageType for processID at the current instant. Reads the current process state, exit code, and tracker bookkeeping; no side effects beyond updating the crash-rate ring on the slow path.
Returns OutageHealthy if the classifier or tracker is nil, the process can't be found, or the process is past its grace window. "Don't suppress" is the safer default for all error cases.
func (*OutageClassifier) ClassifyProxy ¶ added in v0.13.7
func (c *OutageClassifier) ClassifyProxy(proxyID, linkedProcessID string) OutageType
ClassifyProxy returns the OutageType for proxyID, taking the worse of:
- the linkedProcessID's process-state outage (existing Classify)
- the proxy's transport-signal outage (new HealthTracker bookkeeping)
When the proxy is in synthetic transport outage but the process is healthy, the result is OutageRebuild. When the process is in a worse state (LongRebuild/ExpiredRebuild/Crash), the worse classification wins. linkedProcessID may be empty for unlinked proxies; in that case only the transport signal contributes.
func (*OutageClassifier) Forget ¶ added in v0.12.41
func (c *OutageClassifier) Forget(processID string)
Forget drops all classifier-side state for processID. Called from the daemon when a script is fully cleaned up.
func (*OutageClassifier) NoteOutageOnset ¶ added in v0.12.41
func (c *OutageClassifier) NoteOutageOnset(processID string, ts time.Time)
NoteOutageOnset records an outage-start timestamp in the per-process crash-rate ring buffer. Called from the gate or HealthTracker.observe whenever a process leaves Running. Bounded ring (crashHistorySize entries) keeps memory and rate-check work O(1).
func (*OutageClassifier) SuppressionMode ¶ added in v0.12.41
func (c *OutageClassifier) SuppressionMode(processID string) SuppressionMode
SuppressionMode maps Classify(processID) → tri-state mode. O(1) on the hot path: one Classify call plus a switch.
func (*OutageClassifier) SuppressionModeProxy ¶ added in v0.13.7
func (c *OutageClassifier) SuppressionModeProxy(proxyID, linkedProcessID string) SuppressionMode
SuppressionModeProxy returns the gate decision for a proxy, considering both its linked process's state and any synthetic transport outage. The hot path is one ClassifyProxy plus a switch — same shape as SuppressionMode.
type OutageType ¶ added in v0.12.41
type OutageType int
OutageType categorises a process outage. The set is closed.
const ( // OutageHealthy means the process is Running and past the grace window. OutageHealthy OutageType = iota // OutageRebuild is a short outage (<RebuildShortWindow) with rebuild evidence. OutageRebuild // OutageLongRebuild is an ongoing outage in RebuildShortWindow..RebuildLongWindow. OutageLongRebuild // OutageExpiredRebuild is an ongoing outage past RebuildLongWindow. OutageExpiredRebuild // OutageCrash is everything else: unexpected exits, direct Running→Failed, // or chronic restart loops. OutageCrash )
func (OutageType) String ¶ added in v0.12.41
func (o OutageType) String() string
String returns a human-readable name for diagnostics.
type OverlayAlertSink ¶ added in v0.11.5
OverlayAlertSink delivers alert messages via PTY stdin injection.
type PendingProcess ¶ added in v0.13.5
type PendingProcess struct {
// ProcessID is the daemon-side identifier (project_path + name).
ProcessID string
// Name is the script-style name passed to PROC RUN.
Name string
// ProjectPath is the normalised project path the process belongs to.
ProjectPath string
// Command is the resolved command string (for visibility in proc list).
Command string
// WaitingFor is the set of dependency names the process is still
// waiting for. Sorted for stable output.
WaitingFor []string
// Deadline is the per-process timeout deadline. Zero means no deadline.
Deadline time.Time
// State distinguishes "still waiting" from "dependency timed out".
State PendingProcessState
// FailureReason is the human-readable reason set when State is
// PendingFailed. Format: "dependency_timeout:<dep-name>".
FailureReason string
// CreatedAt is when the entry was registered.
CreatedAt time.Time
}
PendingProcess captures the wire-visible fields a pending process exposes through PROC STATUS / PROC LIST while it is gated on dependencies.
type PendingProcessState ¶ added in v0.13.5
type PendingProcessState int
PendingProcessState describes the lifecycle of a pending process.
const ( // PendingWaiting means the process is gated on at least one dependency. PendingWaiting PendingProcessState = iota // PendingFailed means a dependency timed out or the process never launched. PendingFailed )
func (PendingProcessState) String ¶ added in v0.13.5
func (s PendingProcessState) String() string
type PendingProcessTracker ¶ added in v0.13.5
type PendingProcessTracker struct {
// contains filtered or unexported fields
}
PendingProcessTracker is the registry of processes waiting on dependencies.
func NewPendingProcessTracker ¶ added in v0.13.5
func NewPendingProcessTracker() *PendingProcessTracker
NewPendingProcessTracker returns a ready-to-use tracker.
func (*PendingProcessTracker) Get ¶ added in v0.13.5
func (t *PendingProcessTracker) Get(processID string) (PendingProcess, bool)
Get returns a snapshot of processID's pending state, or false if the process is not in the tracker.
func (*PendingProcessTracker) ListByProject ¶ added in v0.13.5
func (t *PendingProcessTracker) ListByProject(projectPath string) []PendingProcess
ListByProject returns snapshots of all pending processes whose ProjectPath matches. Pass an empty string to return all entries.
The result is freshly allocated; the tracker retains no reference.
func (*PendingProcessTracker) MarkFailed ¶ added in v0.13.5
func (t *PendingProcessTracker) MarkFailed(processID, dep string)
MarkFailed transitions processID to PendingFailed with reason "dependency_timeout:<dep>". The entry remains in the registry so PROC STATUS can return the failure reason; callers should call Remove once the failure has been surfaced (e.g., once the dependent failure has been folded into the script registry as StateFailed).
func (*PendingProcessTracker) MarkReady ¶ added in v0.13.5
func (t *PendingProcessTracker) MarkReady(processID, dep string) int
MarkReady removes dep from the remaining wait set for processID. If processID is not registered, the call is a no-op. Returns the count of remaining dependencies after removal (0 means all deps are satisfied).
func (*PendingProcessTracker) Register ¶ added in v0.13.5
func (t *PendingProcessTracker) Register(p PendingProcess, deps []string) PendingProcess
Register adds processID to the tracker as waiting on the given deps. Idempotent: re-registering an existing process replaces the entry. The caller is responsible for spawning the wait goroutine.
Returns the snapshot of the registered entry.
func (*PendingProcessTracker) Remove ¶ added in v0.13.5
func (t *PendingProcessTracker) Remove(processID string)
Remove deletes processID from the tracker. Safe to call on an unknown processID.
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 PortConflict ¶ added in v0.12.36
type PortConflict struct {
ScriptName string `json:"script_name"`
Port int `json:"port"`
PIDs []int `json:"pids"`
ProcessName string `json:"process_name,omitempty"`
// LinuxPIDs are sourced from /proc/net/tcp (Linux) or lsof (macOS).
// Killable via syscall.Kill / ProcessManager.KillProcessByPort.
LinuxPIDs []int `json:"linux_pids,omitempty"`
// WindowsPIDs are sourced from netstat.exe via WSL interop. They live
// in the Windows kernel namespace and are unreachable from syscall.Kill;
// they require platform.KillWindowsPID (taskkill.exe).
WindowsPIDs []int `json:"windows_pids,omitempty"`
}
PortConflict describes an unmanaged process blocking a declared port.
PIDs is the union of LinuxPIDs + WindowsPIDs. The split exists so the kill path can route Linux-side PIDs through ProcessManager (syscall.Kill + process-group escalation) and Windows-side PIDs through platform.KillWindowsPID (taskkill.exe interop). On non-WSL hosts WindowsPIDs is always nil.
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 ProcRunConfig ¶ added in v0.12.51
type ProcRunConfig struct {
Run string `json:"run,omitempty"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Cwd string `json:"cwd,omitempty"`
Env map[string]string `json:"env,omitempty"`
URLMatchers []string `json:"url_matchers,omitempty"`
AutoRestart bool `json:"auto_restart,omitempty"`
ProjectPath string `json:"project_path,omitempty"`
// DependsOn lists script names this process must wait for before
// launching. Empty means start immediately.
DependsOn []string `json:"depends_on,omitempty"`
// DependsOnTimeout is the per-process upper bound on the dep wait
// in seconds. Zero (or omitted) → 30s default.
DependsOnTimeout int `json:"depends_on_timeout,omitempty"`
}
ProcRunConfig holds the JSON payload for PROC RUN. Mirrors the procRunPayload struct in hub_proc.go — kept in sync with the wire contract (extra / renamed fields require updating both sides).
type ProcRunGroupConfig ¶ added in v0.13.5
type ProcRunGroupConfig struct {
ProjectPath string `json:"project_path,omitempty"`
DependsOnTimeout int `json:"depends_on_timeout,omitempty"`
Processes []GroupProcess `json:"processes"`
}
ProcRunGroupConfig holds the JSON payload for PROC RUN-GROUP. Mirrors the procRunGroupPayload struct in hub_proc.go.
type ProcessAlertStore ¶ added in v0.12.0
type ProcessAlertStore = alert.ProcessAlertStore
ProcessAlertStore is an alias for alert.ProcessAlertStore.
func NewProcessAlertStore ¶ added in v0.12.0
func NewProcessAlertStore(maxSize int) *ProcessAlertStore
NewProcessAlertStore creates a new alert store with the given capacity.
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, env []string, expectedPorts []int, 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. Uses atomic fields for restart_count and last_restart to avoid acquiring per-process locks, eliminating the nested lock pattern (r.mu RLock + state.mu Lock).
func (*ProcessAutoRestarter) Unregister ¶ added in v0.11.1
func (r *ProcessAutoRestarter) Unregister(processID string)
Unregister disables auto-restart for a process.
type ProcessExitInfo ¶ added in v0.12.41
type ProcessExitInfo struct {
ProcessID string `json:"process_id"`
ExitCode int `json:"exit_code"`
Reason string `json:"reason"` // "stopped" | "crash" | "signal"
StartedAt time.Time `json:"started_at,omitempty"`
EndedAt time.Time `json:"ended_at"`
Uptime time.Duration
StderrTail string `json:"stderr_tail,omitempty"`
}
ProcessExitInfo is a snapshot of a process death. It is held in the daemon's in-memory exit-info store and rendered into proc status / proc list responses.
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 ProxyBroadcaster ¶ added in v0.13.0
type ProxyBroadcaster interface {
// BroadcastAlertToast sends a toast to all connected browser clients.
// toastType matches the toast severity ("error", "warning").
// Implementations must be non-blocking; errors are swallowed at debug level.
BroadcastAlertToast(toastType, title, message string)
}
ProxyBroadcaster broadcasts alert toasts to all active browser overlay connections. Implemented by proxyManagerBroadcaster which wraps *proxy.ProxyManager. Test code can use a stub without starting a real proxy.
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)
ProxyName string // Config proxy name (for FallbackPortCheck 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 // FallbackPortCheck indicates a delayed check for script-linked proxies that // weren't created by URL detection — creates proxy using fallback-port if needed FallbackPortCheck )
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.
func (*ReadySignaler) WaitReadyCtx ¶ added in v0.12.40
func (rs *ReadySignaler) WaitReadyCtx(processID string, ctx context.Context) error
WaitReadyCtx blocks until processID is signaled ready or the context is cancelled. Returns nil if ready, or ctx.Err() wrapped with context on cancellation.
type ReconnectCallback ¶
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) Doctor ¶ added in v0.12.21
func (rc *ResilientClient) Doctor(projectPath string) (map[string]interface{}, error)
Doctor runs health checks and returns a diagnostic report.
func (*ResilientClient) IncidentQuery ¶ added in v0.13.0
func (rc *ResilientClient) IncidentQuery(filter protocol.IncidentQueryFilter) (*protocol.IncidentQueryResult, error)
IncidentQuery queries the incident inbox for the current session.
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) ProcRun ¶ added in v0.13.5
func (rc *ResilientClient) ProcRun(name string, cfg ProcRunConfig) (map[string]interface{}, error)
ProcRun starts an admin-aware process via PROC RUN. Optionally gates on declared dependencies before launching. See Client.ProcRun for the full contract.
func (*ResilientClient) ProcRunGroup ¶ added in v0.13.5
func (rc *ResilientClient) ProcRunGroup(cfg ProcRunGroupConfig) (map[string]interface{}, error)
ProcRunGroup launches a multi-process startup group via PROC RUN-GROUP. Performs cycle detection before any process launches. See Client.ProcRunGroup for the full contract.
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) SessionRegisterWithContainment ¶ added in v0.12.41
func (rc *ResilientClient) SessionRegisterWithContainment(code, overlayPath, projectPath, command string, args []string, sessionPGID int, sessionJobHandle uint64) (map[string]interface{}, error)
SessionRegisterWithContainment registers a new session and reports both the Unix session pgid and the Windows Job Object handle for the PTY child subtree. See Client.SessionRegisterWithContainment for platform semantics.
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 ¶ 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
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.
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. State is cached in memory per-project. Reads are served from cache. Mutations update cache under lock, then enqueue async disk writes via a write-behind channel.
func NewSchedulerStateManager ¶ added in v0.7.0
func NewSchedulerStateManager() *SchedulerStateManager
NewSchedulerStateManager creates a new scheduler state manager.
func NewSchedulerStateManagerWithInterval ¶ added in v0.12.40
func NewSchedulerStateManagerWithInterval(interval time.Duration) *SchedulerStateManager
NewSchedulerStateManagerWithInterval creates a scheduler state manager with a custom debounce interval.
func (*SchedulerStateManager) ClearProject ¶ added in v0.7.0
func (m *SchedulerStateManager) ClearProject(projectPath string) error
ClearProject removes all tasks for a project.
func (*SchedulerStateManager) Close ¶ added in v0.12.40
func (m *SchedulerStateManager) Close() error
Close stops the background writer after flushing pending state.
func (*SchedulerStateManager) Flush ¶ added in v0.12.40
func (m *SchedulerStateManager) Flush() error
Flush ensures all pending writes are persisted to disk immediately.
Race note: there is a transient window between close(stopCh) and close(stopped) during which writeLoop is running its final drain+write but no longer receiving on flushCh. A naive `select { case flushCh <- done: case <-stopped: }` can block forever if the scheduler picks the flushCh send branch at exactly the wrong moment. We cover this by also watching stopCh — once stopCh is closed we do a direct synchronous write instead of queueing, which is correct because writeLoop's final doWriteAll is protected by the same mutex.
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 from the in-memory cache.
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 ScriptKind ¶ added in v0.12.51
type ScriptKind string
ScriptKind classifies admin-surface entries returned by SCRIPT LIST.
The script registry in go-cli-server is strictly process-kind (backed by a real child process), but the overlay status bar and the `SCRIPT LIST` admin screen are also the surface for explicit proxies — proxies started without a linked script (MCP tool path or `autostart true` on a standalone proxy config). To keep the admin surface unified without modifying the vendored script package, proxy-kind entries live in a parallel daemon-level map and are merged into SCRIPT LIST responses.
ScriptKindProcess is the default / implicit kind for entries returned directly from scriptRegistry.List (the vendored registry has no Kind field; the merge path tags every script.Entry as ScriptKindProcess).
const ( ScriptKindProcess ScriptKind = "process" ScriptKindProxy ScriptKind = "proxy" )
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
// SessionPGID is the POSIX process group ID of the PTY child. The PTY
// child is started as its own session leader (via creack/pty's Setsid),
// so on Unix this equals the PTY child PID and identifies every process
// the coding agent spawned via non-interactive bash, including
// backgrounded `npm run dev &` style jobs. Zero on Windows (Job Object
// cleanup is handled separately) or when the client didn't report one.
SessionPGID int `json:"session_pgid,omitempty"`
// SessionJobHandle is the Windows Job Object handle for the PTY child
// subtree, reported by `agnt run` on Windows. The Windows equivalent
// of SessionPGID: every process assigned to this job (and its
// descendants) is killed when the job is terminated via
// platform.KillSessionJobObject. Zero on Unix or when the client
// didn't report one. Stored as uint64 because windows.Handle is not
// available outside the Windows build-tagged platform package.
//
// Caveat: job handles are per-process on Windows. This field is a
// best-effort hint for the daemon; the authoritative containment is
// JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the owning `agnt run`
// process. When the daemon IS the owner (shared process) or when
// the handle is still valid cross-process (e.g. via inheritance),
// explicit KillSessionJobObject at session cleanup accelerates
// teardown.
SessionJobHandle uint64 `json:"session_job_handle,omitempty"`
// 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
IsActive returns true if the session is currently active.
func (*Session) MarshalJSON ¶ added in v0.7.0
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) 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 ¶
SocketConfig holds configuration for socket management. Wraps go-cli-server/socket.Config with agnt-specific defaults (socket name, process matcher).
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.
type StartProcessResult ¶ added in v0.13.5
type StartProcessResult struct {
// ProcessID is the daemon-side identifier (project_path + name).
ProcessID string
// State is the immediate state observed by the caller:
// "starting" — no deps, launch was synchronous and succeeded.
// "pending" — deps exist, launch is deferred until all deps ready.
// "failed" — synchronous launch failed (returned in Err).
State string
// WaitingFor is populated when State == "pending"; the set of dep
// names the launcher will block on.
WaitingFor []string
// Err is non-nil only when the synchronous launch path failed
// (no-deps case). Async failures land on the script registry's
// StateFailed and the pending tracker's PendingFailed.
Err error
}
StartProcessResult captures the outcome of a deferred PROC RUN launch kicked off by StartProcessWithDeps.
Used by RunGroup to report per-process kickoff status. The actual launch happens asynchronously — this struct only reports what happened up to the point where StartProcessWithDeps returned.
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. Reads are served from in-memory state. Writes are enqueued to a background goroutine via a write-behind channel, so the mutex never touches disk I/O.
func NewStateManager ¶
func NewStateManager(config StateManagerConfig) *StateManager
NewStateManager creates a new state manager with a background writer.
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 and deletes the state file.
func (*StateManager) Close ¶ added in v0.12.40
func (sm *StateManager) Close() error
Close stops the background writer after flushing pending state. Safe to call multiple times.
func (*StateManager) Flush ¶
func (sm *StateManager) Flush() error
Flush ensures any pending saves are written immediately. Blocks until the write completes.
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 reads state from disk into memory. Only called at startup.
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 synchronously by flushing the write-behind channel.
func (*StateManager) SaveDebounced ¶
func (sm *StateManager) SaveDebounced()
SaveDebounced enqueues an async write. Multiple rapid calls coalesce.
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 StreamSink ¶ added in v0.12.36
StreamSink receives filtered proxy log events via a channel. The consumer reads from Ch until it is closed (on unregister or daemon shutdown).
Concurrency contract: producers and the closer (RemoveStreamSink) use a lock-free reference count + closed flag instead of a per-sink RWMutex. Hot path is two atomic loads and two atomic adds; slow path (close) spins until refs drains. This is ~4× faster than the prior RWMutex pair under high fan-out (100+ sinks × thousands of events) and eliminates the per-sink RLock contention that caused TestAlertHub_FanOutToManySinks to flake under concurrent test load. See sendToStreamSinkSafe for the send-side dance and RemoveStreamSink for the close-side wait.
closed is set to true BEFORE refs is consulted by the closer so any producer that has already entered the critical section (refs > 0) will be drained before close(Ch) runs. Producers that observe closed=true after their refs increment must decrement and exit without sending.
type SuppressionMode ¶ added in v0.12.41
type SuppressionMode int
SuppressionMode is the tri-state result of the classifier — what the gate should do for a proxy linked to this process.
const ( // ModeOff broadcasts every entry normally. ModeOff SuppressionMode = iota // ModeFull drops everything except diagnostic entries. ModeFull // ModeDiagnosticOnly drops error-class entries and forwards // warnings, info, and diagnostics. The TrafficLogger only // distinguishes error vs non-error today; in practice this collapses // to ModeFull for HTTP and Error log types but allows custom // warn-level entries through. See proxyBroadcastGate for the exact // classification. ModeDiagnosticOnly )
func (SuppressionMode) String ¶ added in v0.12.41
func (m SuppressionMode) String() string
String returns a human-readable mode name for diagnostics.
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 TransportConfig ¶ added in v0.13.7
type TransportConfig struct {
Threshold int // err count to trigger outage
Window time.Duration // sliding window for the threshold
RecoveryDebounce time.Duration // ignore recovery signals within this window after outage entry
}
TransportConfig configures the per-proxy transport-signal outage detector. Values mirror the OutageHoldConfig getters; see internal/config/agnt.go.
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.
Source Files
¶
- alert_hub.go
- alert_store.go
- autostart.go
- autostart_manager.go
- client.go
- conn.go
- daemon.go
- daemon_autostart.go
- daemon_helpers.go
- daemon_orphan_pgid.go
- daemon_proc_deps.go
- daemon_reconcile.go
- daemon_session_cleanup.go
- daemon_shutdown.go
- doctor.go
- doctor_unix.go
- duplicate_scanner.go
- health_tracker.go
- hold_buffer.go
- hook_runner.go
- hub_alerts.go
- hub_automate.go
- hub_automation.go
- hub_autostart.go
- hub_browser.go
- hub_chaos.go
- hub_currentpage.go
- hub_doctor.go
- hub_helpers.go
- hub_hook.go
- hub_incidents.go
- hub_lifecycle.go
- hub_overlay.go
- hub_proc.go
- hub_proxy.go
- hub_proxylog.go
- hub_router.go
- hub_run.go
- hub_script.go
- hub_session.go
- hub_status.go
- hub_store.go
- hub_stream.go
- hub_tunnel.go
- outage_classifier.go
- port_preflight.go
- proc_pending.go
- process_autorestart.go
- process_exit_watcher.go
- proxy_events.go
- proxy_overlay.go
- proxy_registry.go
- proxy_waitfor.go
- ready_signaler.go
- resilient.go
- scheduler.go
- scheduler_state.go
- session.go
- socket_compat.go
- startup_errors.go
- startup_resilience.go
- state.go
- test_helpers.go
- upgrade.go
- urltracker.go