Documentation
¶
Overview ¶
Package daemon coordinates the libp2p Host, CRDT StateStore, GossipSub topic, stream handlers, mDNS discovery, dispatcher, action gate, and the Unix-socket hook IPC into a single Run loop.
The Run loop is the integration seam for every other internal package in agenthive: nothing else in the codebase wires the subsystems together. Construction (New) only builds the dependency graph and validates the supplied Config; no goroutines start, no listeners bind, no files are written until Run is called. Run is single-shot — a Daemon cannot be re-Run after its Stop has fired. This mirrors how a process supervisor would treat the daemon binary: one start, one stop, no recycling.
Index ¶
- Constants
- type ActionEntry
- type Config
- type Daemon
- func (d *Daemon) DispatchNotification(ctx context.Context, n protocols.Notification) error
- func (d *Daemon) Host() host.Host
- func (d *Daemon) ListActions() ([]ActionEntry, error)
- func (d *Daemon) ListPeers() []PeerEntry
- func (d *Daemon) ListRoutes() []RouteEntry
- func (d *Daemon) Multiaddrs() []string
- func (d *Daemon) Run(ctx context.Context) error
- func (d *Daemon) State() *crdt.StateStore
- func (d *Daemon) Stop() error
- func (d *Daemon) TailLogLines(limit int) ([]string, error)
- type ListActionsResponse
- type ListLogsRequest
- type ListLogsResponse
- type ListPeersResponse
- type ListRoutesResponse
- type PeerEntry
- type QueryBackend
- type RouteEntry
- type SocketEnvelope
- type SocketError
- type SocketServer
Constants ¶
const ( KindActionRequest = "action_request" KindActionResponse = "action_response" KindError = "error" KindListPeers = "list_peers" KindListPeersResponse = "list_peers_response" KindListRoutes = "list_routes" KindListRoutesResponse = "list_routes_response" KindListActions = "list_actions" KindListActionsResponse = "list_actions_response" KindListLogs = "list_logs" KindListLogsResponse = "list_logs_response" )
Envelope kinds carried on the Unix socket. The wire format is framed JSON (a 4-byte big-endian length prefix followed by the JSON body, identical to the libp2p stream framing in package protocols) where each envelope is a SocketEnvelope with a discriminator (Kind) and a raw JSON payload sized to the discriminator.
The list_* request kinds power the TUI's snapshot polling (cmd_tui). Each request kind has a matching response kind so the client can tell a response to its query from an unrelated envelope on the same fd.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ActionEntry ¶
type ActionEntry struct {
Action protocols.ActionRequest `json:"action"`
}
ActionEntry is a single pending action in a ListActionsResponse. Action carries the full ActionRequest so the TUI can render the tool name + input without a second round-trip.
type Config ¶
type Config struct {
ConfigDir string
Identity crypto.PrivKey
ListenAddrs []string
LogPath string
SocketPath string
}
Config is the daemon's startup configuration. Every field is required except ListenAddrs (which falls back to the transport package's loopback + ephemeral defaults).
type Daemon ¶
type Daemon struct {
// contains filtered or unexported fields
}
Daemon is the long-running coordinator. Construction sets up every component up-front so Run has nothing to do but start goroutines and block on ctx.Done().
Field lifecycle:
- cfg/state/dispatcher/gate/socket: created by New. State outlives Run because tests inspect it both before Run starts and after it returns.
- host/gossipsub/topic/sub/mdnsStop: created inside Run; nil before Run starts and after Run returns.
- stopOnce/stopCh: drive Stop. stopCh is closed by Stop to act as a secondary cancellation signal for Run, on top of the caller's ctx.
func New ¶
New constructs the Daemon's component graph but does not start any goroutines. Call Run to start the daemon.
New validates the supplied Config (identity must be non-nil, ConfigDir must be non-empty), then builds the CRDT StateStore, on-disk hooks queue, dispatcher with a single LogSurface, the action gate, and the SocketServer. None of these touch the network. The libp2p Host and GossipSub are deferred to Run because they need the ctx the caller will pass and because Host construction is the most likely thing to fail at startup — surfacing that failure from Run (with the rest of the wiring already torn down) is cleaner than failing in New and leaving the caller to clean up the dispatcher's file descriptors.
func (*Daemon) DispatchNotification ¶
DispatchNotification fans a notification out to local surfaces and to any remote peer whose route matches. Plan L5.B step 4: ask the matcher for target peers first; route the libp2p stream only to those peers; always also call dispatcher.Dispatch for local surfaces.
If Run has not been called (or has already returned), DispatchNotification still invokes the local dispatcher — the matcher and host are optional. A per-peer stream write failure is logged but does not abort the fan-out.
func (*Daemon) Host ¶
Host returns the libp2p host, or nil if Run has not been called yet (or has already returned). The accessor is read-locked so callers in other goroutines see a consistent view; the field itself is set exactly once by Run and cleared exactly once at shutdown.
func (*Daemon) ListActions ¶
func (d *Daemon) ListActions() ([]ActionEntry, error)
ListActions implements the QueryBackend surface: scans the queue directory for *.pending files and decodes each into an ActionRequest. The list is sorted by ActionID so the TUI render is stable across polls.
A missing queue directory is not an error — it just means no actions have ever been written. We return an empty slice in that case.
func (*Daemon) ListPeers ¶
ListPeers implements the QueryBackend surface: returns the CRDT peer set as a deterministically-sorted slice (by peer ID) so the TUI's render is stable across polls.
func (*Daemon) ListRoutes ¶
func (d *Daemon) ListRoutes() []RouteEntry
ListRoutes implements the QueryBackend surface: returns the routes table as a deterministically-sorted slice (by route ID).
func (*Daemon) Multiaddrs ¶
Multiaddrs returns the host's listen addresses as /p2p/<peerid>-suffixed strings, suitable for sharing with peers. Returns nil before Run has built the host.
func (*Daemon) Run ¶
Run blocks until ctx is done or Stop is called, then tears down every component in reverse order and persists state to <configDir>/state.json.
Workflow (matches plan L4):
- Build the libp2p Host via transport.New(ctx, cfg).
- Build GossipSub: NewGossipSub(ctx, host), Join(TopicState), Subscribe().
- Register stream handlers on the Host for the four protocol IDs.
- Start mDNS via discovery.StartMDNS with a callback that adds discovered peers to the StateStore and to the libp2p peerstore.
- Start the SocketServer goroutine.
- Start a goroutine that applies incoming StateDelta messages from the GossipSub topic to the StateStore.
- Start a goroutine that periodically publishes deltas of the StateStore via the topic (debounced 200ms, max once per 2s active).
- Connect to all peers in StateStore.ListPeers() (best-effort).
- Block on ctx.Done(). On cancel, close everything in reverse order and persist state to state.json.
func (*Daemon) State ¶
func (d *Daemon) State() *crdt.StateStore
State returns the CRDT StateStore. Always non-nil after New.
func (*Daemon) Stop ¶
Stop signals the Run loop to begin shutting down. Safe to call multiple times concurrently. Stop returns immediately; the actual shutdown happens inside Run.
func (*Daemon) TailLogLines ¶
TailLogLines implements the QueryBackend surface: returns up to limit most recent lines from the JSONL log file. Each entry is one raw line — the TUI is responsible for parsing it via json.Unmarshal into a logEnvelope shape.
A missing log file is not an error; it just means nothing has been logged yet. We return an empty slice in that case.
type ListActionsResponse ¶
type ListActionsResponse struct {
Actions []ActionEntry `json:"actions"`
}
ListActionsResponse is the body of a list_actions_response envelope.
type ListLogsRequest ¶
type ListLogsRequest struct {
Limit int `json:"limit,omitempty"`
}
ListLogsRequest is the body of a list_logs request envelope. Limit is the maximum number of recent log lines to return; <=0 means "use the server's default cap" (currently 500).
type ListLogsResponse ¶
type ListLogsResponse struct {
Lines []string `json:"lines"`
}
ListLogsResponse is the body of a list_logs_response envelope. Lines are raw JSONL strings (each line is one logEnvelope as written by LogSurface). The TUI parses them per-row so a single malformed line cannot crash the view.
type ListPeersResponse ¶
type ListPeersResponse struct {
Peers []PeerEntry `json:"peers"`
}
ListPeersResponse is the body of a list_peers_response envelope.
type ListRoutesResponse ¶
type ListRoutesResponse struct {
Routes []RouteEntry `json:"routes"`
}
ListRoutesResponse is the body of a list_routes_response envelope.
type PeerEntry ¶
PeerEntry is a single (id, info) pair in a ListPeersResponse. We do not expose the underlying map[string]PeerInfo directly so the wire format has a stable, ordered shape the TUI can render row by row.
type QueryBackend ¶
type QueryBackend interface {
ListPeers() []PeerEntry
ListRoutes() []RouteEntry
ListActions() ([]ActionEntry, error)
TailLogLines(limit int) ([]string, error)
}
QueryBackend is the read-only surface SocketServer needs in order to answer list_* envelopes. The Daemon implements it; tests can substitute a stub.
type RouteEntry ¶
RouteEntry is a single (id, rule) pair in a ListRoutesResponse.
type SocketEnvelope ¶
type SocketEnvelope struct {
Kind string `json:"kind"`
Payload json.RawMessage `json:"payload"`
}
SocketEnvelope is the on-wire frame used between cmd/agenthive's hook subcommand and the running daemon. Payload is left raw so the server can decode it lazily based on Kind without having to declare a union type.
type SocketError ¶
type SocketError struct {
Message string `json:"message"`
}
SocketError is the body of a kind:"error" envelope. The hook subcommand treats any error envelope as "fall back to Claude's built-in prompt", never as a hard failure.
type SocketServer ¶
type SocketServer struct {
// contains filtered or unexported fields
}
SocketServer accepts hook IPC connections on a Unix socket. One connection is one request and one response.
Wire format on the socket: framed JSON.
Request: {"kind":"action_request", "payload": ActionRequest}
Response: {"kind":"action_response", "payload": ActionResponse}
{"kind":"error", "payload": {"message": "..."}}
The socket file is created at path with mode 0600. If a stale socket file is already present (e.g. from a previous crash), it is removed before binding. On graceful shutdown via the supplied context, the socket file is unlinked so subsequent restarts can bind cleanly.
func NewSocketServer ¶
func NewSocketServer(path string, gate *hooks.Gate) *SocketServer
NewSocketServer returns a SocketServer that listens on path and routes action_request envelopes through gate. query may be nil — in that case list_* envelopes return an error envelope. Production callers pass the Daemon itself (which implements QueryBackend) so the TUI can query state.
func (*SocketServer) Run ¶
func (s *SocketServer) Run(ctx context.Context) error
Run binds the Unix socket and accepts connections until ctx is done.
Each accepted connection is handled in its own goroutine via handleConn, which reads exactly one framed envelope, dispatches it through the gate, and writes the resulting envelope back. Connection-level errors are logged and never bubble up: a misbehaving client must not be able to kill the daemon. A bind failure (port-in-use, missing parent directory, permission denied, etc.) is returned to the caller so the daemon can react.
On ctx.Done() the listener is closed (which unblocks Accept) and Run waits for any in-flight handler goroutines to return before unlinking the socket file and returning nil.
func (*SocketServer) SetQueryBackend ¶
func (s *SocketServer) SetQueryBackend(q QueryBackend)
SetQueryBackend installs the read-only state backend used to answer list_* envelopes. The Daemon calls this after construction so the SocketServer can survive being built before the daemon has finished wiring itself up. Safe to call before Run.