Documentation
¶
Overview ¶
Package daemon is switchboard's thin client for the frozen core-agent daemon contract. A chat gateway maps a conversation (a Slack thread, a Google Chat space) onto a core-agent session and shuttles turns across the four verbs core-agent already ships:
POST /sessions -> create a session (returns SessionID) POST /sessions/<sid>/inject -> queue a user message on its inbox POST /sessions/<sid>/wake -> nudge a sleeping session to run a turn GET /sessions/<sid>/events -> SSE stream of the session's output
Auth is a static Bearer token; per-turn attribution rides the X-Asserted-Caller header (the daemon stamps it as the session Owner and resolves per-caller MCP credentials from it — the seam where W0 and W1 meet). This mirrors k8s-lookout's pkg/inject wire client; switchboard adds the /wake and /events verbs the interactive round-trip needs.
Index ¶
- Constants
- func IsTransient(err error) bool
- type AgentReply
- type Capabilities
- type Client
- func (c *Client) CreateSession(ctx context.Context, assertedCaller string) (Session, error)
- func (c *Client) HeadSeq(ctx context.Context, sess Session, assertedCaller string) (int64, error)
- func (c *Client) Inject(ctx context.Context, sess Session, assertedCaller, text string) error
- func (c *Client) Subscribe(ctx context.Context, sess Session, assertedCaller string, since int64, ...) error
- func (c *Client) Wake(ctx context.Context, sess Session, assertedCaller string) error
- type Config
- type Event
- type InboxChange
- type Session
- type SessionStatus
- type StatusError
- type ToolCall
- type ToolResult
- type TurnError
- type TurnUsage
- type UsageTotals
Constants ¶
const ( EventUsage = "usage-update" EventTurnComplete = "turn-complete" EventTurnError = "turn-error" EventStatusUpdate = "status-update" EventCapabilities = "capabilities" EventInbox = "inbox" )
The typed lifecycle events switchboard consumes. None is relayed verbatim: EventUsage and EventTurnComplete are between them the only source for what a turn cost (see TurnUsage), and EventTurnError is the only announcement that a turn died inside the daemon — without it the thread simply goes quiet (#34).
EventStatusUpdate and EventCapabilities describe the session rather than a turn's output: what the daemon is doing right now, and what it can do at all. EventInbox is the one event describing a message's life *before* it becomes a turn: queued when it lands on the inbox, dequeued when a turn takes it up. It is the only way to know a session has work waiting behind the turn it is running — see InboxChange.
const ( EventStreamChunk = "stream-chunk" EventToolCall = "tool-call" EventToolResult = "tool-result" )
The advertised names for the traffic that arrives on EventAgent. Nothing subscribes to these — the wire event stays "agent" — but they are what a capabilities frame calls the surface switchboard reads every answer and every tool notice out of, so they are the names to check it against. EventToolResult is here for the pairing; switchboard reads the calls and not their results.
const ( TurnErrorConfig = "config_error" TurnErrorAuth = "auth_error" TurnErrorModelNotFound = "model_not_found" TurnErrorRateLimited = "rate_limited" TurnErrorTransientNet = "transient_network" // TurnErrorCostCeiling and TurnErrorWatchdog are the two guardrail trips. // They differ from every other kind in what they demand of the reader: the // agent refuses further turns until an operator resets it, so "try again" // is actively wrong advice. TurnErrorCostCeiling = "cost_ceiling" TurnErrorWatchdog = "watchdog" TurnErrorUnknown = "unknown" )
TurnError kinds, mirroring the daemon's event-stream spec §2.6. Unknown values must be treated as TurnErrorUnknown — the spec reserves the right to add categories, and a gateway that switches exhaustively on today's list would go silent on tomorrow's.
const ( TurnStateIdle = "idle" TurnStateStreaming = "streaming" TurnStateAwaitingPermission = "awaiting_permission" TurnStateAwaitingElicit = "awaiting_elicit" )
Turn states, per the daemon's event-stream spec §2.2. As with the turn-error kinds, an unrecognized value must not be forced into one of these: the spec reserves the right to add states, and a gateway that reads anything it does not know as "idle" would end turns that are still running.
Only two of the four are observed in practice. core-agent declares all four and emits exactly streaming and idle; the awaiting_ pair is spec surface with no emission site as of protocol 1.5.0. They are modeled anyway because the consumer has to be written for the state it will be handed, not the state it sees today, and the shorthand for "streaming or nothing" quietly makes a permission prompt look like the end of a turn.
const ( InboxQueued = "queued" InboxDequeued = "dequeued" )
Inbox states, mirroring the daemon's event-stream spec §2.4. The spec reserves room for more (it names "injected" as a candidate), so an unknown state must be ignored rather than read as one of these two.
const EventAgent = "agent"
EventAgent is the SSE event name carrying the agent's streamed output — model text, tool calls, and tool results are all multiplexed onto it. The typed lifecycle events below are separate names switchboard consumes but does not relay verbatim.
The daemon does not list this one in the event types it advertises: it is the legacy name, and the capabilities frame describes the logical surface, where the same traffic appears as "stream-chunk", "tool-call" and "tool-result".
const FeaturePermsStream = "perms_stream"
FeaturePermsStream is the Features key for core-agent's permission-prompt broker: the /perms/stream and /perms/respond routes that turn a blocked tool call into a question someone can answer. Registered per agent, so two sessions on one daemon can disagree about it.
Variables ¶
This section is empty.
Functions ¶
func IsTransient ¶
IsTransient reports whether err is worth a chat-facing "try again" rather than a hard failure notice. A *StatusError defers to its own Transient; any other error (network failure, timeout, connection refused — the request never got a structured rejection from the daemon) is treated as transient, since it says nothing about the request itself being invalid.
Types ¶
type AgentReply ¶
type AgentReply struct {
// Seq is the event's monotonic sequence number; feed the last one
// back to Subscribe as `since` to resume a stream without replaying.
Seq int64
// Text is the concatenated model-authored text of the event, empty
// for tool-call/tool-result-only or user-authored events.
Text string
// Partial is true for an in-progress streaming chunk. The daemon
// repeats the full text in a final Partial:false event, so relaying
// only non-partial events yields one message per assistant turn.
Partial bool
}
AgentReply is the assistant text carried by one EventAgent event.
func AgentText ¶
func AgentText(data string) (r AgentReply, ok bool)
AgentText parses an EventAgent payload and reports the model-authored text it carries. ok is false when the event is not model output worth relaying (a parse failure, a non-agent/user-authored event, or an event with no text — e.g. a tool call). Callers typically relay r.Text when ok && !r.Partial && r.Text != "".
type Capabilities ¶
type Capabilities struct {
// ProtocolVersion is the event-stream spec version, e.g. "1.5.0".
ProtocolVersion string
// Server is the daemon's self-description, e.g. "core-agent/0.9.2".
Server string
// EventTypes is the logical event surface the daemon advertises. It is not
// the set of SSE event names: the daemon lists "stream-chunk", "tool-call"
// and "tool-result" separately even though all three ride on EventAgent,
// and does not list EventAgent itself. Nothing may test for "agent" here.
EventTypes []string
// Features is the set of optional *routes* the daemon serves, which is a
// different question from EventTypes: that one is about what arrives on
// this stream, this one is about what else can be called. A daemon whose
// agent registered no permission broker answers 501 at /perms/stream, and
// says so here in advance by omitting FeaturePermsStream — so a caller can
// know before it asks, on a frame it was already going to read.
//
// A key present and false means the same as absent: not offered. Use
// Offers rather than indexing, so an older daemon that sends no features
// map at all reads as "offers nothing" instead of panicking on a nil map.
Features map[string]bool
}
Capabilities is the frame the daemon opens every stream with: what it is, what protocol it speaks, and which events it will actually send.
Switchboard does not negotiate on it — there is nothing to negotiate, the daemon sends what it sends. It is read so an operator can be told when the daemon on the other end will not be sending something switchboard relies on, which otherwise shows up as a feature quietly not working: no error notice for a failed turn, no usage footer, no turn boundary for the progress clock.
func StreamOpened ¶
func StreamOpened(data string) (c Capabilities, ok bool)
StreamOpened parses an EventCapabilities payload. ok is false on a parse failure or a frame carrying none of the four fields, which says nothing worth logging.
func (Capabilities) Advertises ¶
func (c Capabilities) Advertises(t string) bool
Advertises reports whether the daemon said it sends this event type.
func (Capabilities) Missing ¶
func (c Capabilities) Missing(want ...string) []string
Missing returns the given event types the daemon did not advertise, in the order asked. Empty when the daemon advertised nothing at all: a frame with no event_types is an older or partial implementation, and reporting every type as missing would be a wall of noise about one fact.
func (Capabilities) Offers ¶ added in v0.3.0
func (c Capabilities) Offers(feature string) bool
Offers reports whether the daemon said it serves this optional route. Distinct from Advertises, which is about events on this stream.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the thinnest wire client that covers the interactive chat round-trip. It is safe for concurrent use.
func (*Client) CreateSession ¶
CreateSession opens a new session and returns it. assertedCaller (may be empty) is the identity the daemon stamps as Owner; switchboard must be listed in the daemon's attach.multi_session.proxy_identities for it to be honored. The daemon requires an authenticated, non-anonymous caller here, so a create against a multi-session daemon needs either a real bearer identity or a valid asserted caller.
func (*Client) HeadSeq ¶ added in v0.3.0
HeadSeq reports the highest event seq the daemon currently holds for a session, so a reader that wants only what happens *next* can subscribe from there. It is how switchboard adopts a session it did not create (#38): the alternative, subscribing from 0, replays the daemon's whole window — for an incident session that has been running for an hour, straight into the chat thread.
The protocol offers no way to ask, so this is a measurement: open the stream, read the backlog, and take the last seq on it. The stream is closed once it has been quiet for headProbeQuiet, or at headProbeCap, whichever comes first — so a call normally costs a fraction of a second, and at worst headProbeCap, which is what a session mid-turn costs because it never goes quiet. Neither deadline is an error once the stream is open — the quiet one is how this ends, and the cap yields a head from partway through a live turn, which is the conservative direction. Running out of time *before* the daemon accepts the stream is a different thing entirely, and is reported as an error: nothing was measured and nothing was refused.
The other half of this call matters just as much. A session with nothing to replay reports 0 — exactly what a session that does not exist would report — so the existence check is the subscribe itself: a session the daemon has never heard of answers with a 404, which comes back here as a *StatusError. Binding a thread to a session that is not there is the failure this exists to make loud.
func (*Client) Inject ¶
Inject queues a user message on the session's inbox and, as part of that, runs a turn — the daemon requests its own wake on inject, so callers must not follow this with Wake or the session runs the turn twice. assertedCaller attributes this turn to the originating chat user.
func (*Client) Subscribe ¶
func (c *Client) Subscribe(ctx context.Context, sess Session, assertedCaller string, since int64, fn func(Event) error) error
Subscribe opens the SSE stream for a session and delivers events to fn until the context is cancelled, the stream ends, or fn returns an error. It is the read half of the round-trip: the gateway relays these back into the chat thread. since replays frames with seq greater than it (0 = from the start of the daemon's replay window); track the last seq from AgentText to resume without re-delivering old turns.
type Config ¶
type Config struct {
// BaseURL is the scheme + host + port with NO trailing slash —
// e.g. "http://127.0.0.1:7777".
BaseURL string
// BearerToken authenticates switchboard to the daemon. Loaded
// from an env var by main.go (never a bare flag).
BearerToken string
// HTTPClient lets tests swap in a client pointed at an
// httptest.Server. Nil in production.
HTTPClient *http.Client
}
Config captures the daemon-side surface switchboard posts against. Constructed from CLI flags / env in main.go.
func (Config) Validate ¶ added in v0.3.0
Validate reports whether the config addresses a daemon at all. It is exported because the same three facts — where the daemon is, what authenticates to it, and which HTTP client to use — are what any client of that daemon needs, and a second copy of these rules elsewhere in the tree would be a second place for them to drift.
type Event ¶
Event is one server-sent event from a session's output stream. Type is the SSE event name (e.g. "agent", "status-update", "turn-complete") and Data is its raw JSON payload; use AgentText to pull assistant text out of an "agent" event.
type InboxChange ¶ added in v0.4.0
type InboxChange struct {
// State is InboxQueued, InboxDequeued, or a value this build does not know.
State string
// PromptID is the inbox id of the message, assigned at queue time and
// echoed on the inject response that queued it.
//
// It does NOT correlate with the prompt_id on turn-complete, whatever the
// daemon's own documentation says: core-agent mints the inbox id in
// inbox.push and then mints an unrelated one at turn start for the terminal
// frame (pkg/agent/agent.go, `promptID := newPromptID()`). Filed upstream.
// Until that is fixed, the only sound reading of an id here is "the same
// message I saw queued", never "the turn that will answer it".
PromptID string
}
InboxChange is one message's transition on the session's inbox: queued when it arrives, dequeued when the turn that will answer it takes it up.
The pair is what tells a caller that a session has work waiting behind the turn it is currently running. Nothing else on the stream does: a turn's events say nothing about what is queued behind it, and the daemon's inbox coalesces, so counting turns against messages does not work either — several queued messages drain into one turn and produce a single turn-complete.
PromptID is a set member, not a counter, and that is what makes this usable across a reconnect. Inbox events carry no seq, so they cannot be deduplicated the way agent frames are, and a replayed one is simply seen twice: adding an id already present is a no-op, and so is removing one already gone. A count incremented per event would desynchronise on exactly the reconnect it most needs to survive.
What replay cannot repair is a *lost* event — a dequeued emitted during an outage is gone, and the id it would have retired stays in the set. Callers need an independent way back to a known-empty state; the daemon reporting itself idle is one, since an idle session has by definition drained.
func InboxChanged ¶ added in v0.4.0
func InboxChanged(data string) (c InboxChange, ok bool)
InboxChanged parses an EventInbox payload. ok is false on a parse failure or a frame missing either field — an inbox event that does not name a message, or does not say what became of it, cannot move a set.
func (InboxChange) Dequeued ¶ added in v0.4.0
func (c InboxChange) Dequeued() bool
func (InboxChange) Queued ¶ added in v0.4.0
func (c InboxChange) Queued() bool
Queued and Dequeued report the transition, false for the other state and for one this build does not know.
type Session ¶
Session identifies a core-agent session. The daemon namespaces every session under an app; switchboard addresses sessions by the app-qualified route (/sessions/<app>/<id>/...) rather than the /sessions/<id>/... shortcut, which the daemon rejects with 409 when an id is ambiguous across apps. Both fields come back from CreateSession.
type SessionStatus ¶
type SessionStatus struct {
// TurnState is one of the TurnState constants, or a value this build does
// not know. Always present on a conformant frame — the spec requires it on
// every emission, snapshot or delta.
TurnState string
}
SessionStatus is what an EventStatusUpdate says the session is doing. The event also carries the model, provider, permission mode and context usage; none of those has a consumer here, and modeling a field nothing reads only invites someone to trust it.
func StatusUpdated ¶
func StatusUpdated(data string) (s SessionStatus, ok bool)
StatusUpdated parses an EventStatusUpdate payload. ok is false on a parse failure or a frame with no turn_state, which is the only field this reads — a status update that does not say what the session is doing is not one.
func (SessionStatus) Blocked ¶
func (s SessionStatus) Blocked() bool
Blocked reports whether the turn has stopped on something only a human can answer — a permission prompt or an elicitation. It is emphatically not Idle: the turn is still owed, and treating it as over would retire the thread's progress message while the daemon waits. No daemon emits either state today (see the constants), so this is a guard against the first one that does.
func (SessionStatus) Idle ¶
func (s SessionStatus) Idle() bool
Idle reports whether the session is between turns.
func (SessionStatus) Working ¶
func (s SessionStatus) Working() bool
Working reports whether the daemon is actively running a turn.
type StatusError ¶
StatusError is a non-2xx response from the daemon. The status code lets a caller distinguish a terminal client error (4xx: bad request, unknown session) from a transient server-side failure (5xx) worth telling the user to retry rather than treating as a lost cause.
func (*StatusError) Error ¶
func (e *StatusError) Error() string
func (*StatusError) Transient ¶
func (e *StatusError) Transient() bool
Transient reports whether the failure is the daemon's fault rather than the request's: a 5xx means the same request could succeed on retry, a 4xx means it won't.
501 is the exception on both counts. It is a 5xx, but it does not mean the daemon is struggling — it means the route is not implemented for this session, which is a fact about what was built rather than about this moment, and the same request will get the same answer for as long as the process lives. Retrying it is a loop, and telling an operator to try again is a lie.
type ToolCall ¶ added in v0.2.0
type ToolCall struct {
// ID is the daemon's identifier for the call, echoed on the result that
// eventually answers it. Empty for a daemon that does not send one, which
// leaves the caller to pair by name.
ID string
// Name is the tool, e.g. "bash".
Name string
// Arg is a one-line summary of a single argument, or empty when the call
// has no argument that can be summarised safely. See summariseArg for what
// "safely" is doing there — it is a disclosure decision, not a formatting
// one, and it is deliberately lossy.
Arg string
}
ToolCall is one tool invocation the agent started.
func ToolCalls ¶
ToolCalls returns the tool (function) calls carried by an EventAgent payload, in the order they appear, and is empty for events that carry none (plain model text, tool results, user turns, or a parse failure). It pairs with AgentText: an agent event is either model text (AgentText ok) or tool activity (ToolCalls non-empty), letting the gateway surface "the agent is running <tool>" progress distinctly from the answer text.
type ToolResult ¶ added in v0.2.0
type ToolResult struct {
ID string
Name string
Failed bool
// Detail is a few words about the failure, e.g. "exit 1". Empty for a
// success, and for a failure whose shape this does not recognise.
Detail string
}
ToolResult is one tool result: whether the call finished, and — if it failed — a short descriptor of how. Never the output. See ToolResults.
func ToolResults ¶ added in v0.2.0
func ToolResults(data string) []ToolResult
ToolResults returns the tool results carried by an EventAgent payload.
Unlike ToolCalls this does not filter on role. A result is authored by the tool, not the model, and the daemon labels the event "user" — the same label it puts on an injected turn echoed back. Requiring "model" here is how tool results stayed invisible to the gateway for as long as they did.
What comes back is a verdict, never the output. The response object of a single `kubectl get pods -A` carries the whole listing, and a progress notice is not where that belongs — it belongs in the answer, if the model decides it does.
type TurnError ¶
type TurnError struct {
// Kind is the stable category, one of the TurnError* constants. Treat an
// unrecognized value as TurnErrorUnknown rather than dropping the event.
Kind string
// Code is the provider's status code when one could be extracted
// ("NOT_FOUND", "429"), empty otherwise.
Code string
// Message is a single human-readable line — but not a bounded one. The
// daemon's classifier caps what it produces, and the guardrail trips
// bypass that classifier and build their message directly, interpolating
// text a caller does not control (the watchdog's trigger reason). Clamp
// before rendering.
Message string
// Retryable is the daemon's own judgement on whether sending the same
// message again could work.
Retryable bool
// Hint is the most actionable next step when one is obvious, empty
// otherwise — e.g. which IAM role the runtime service account is missing.
Hint string
}
TurnError is a turn that failed inside the daemon, as carried by an EventTurnError event. The daemon emits one only for failures an operator should see — a retry that succeeded is not one — so every TurnError received is worth surfacing.
func TurnFailed ¶
TurnFailed parses an EventTurnError payload. ok is false on a parse failure or a payload that says nothing — a frame with neither a kind nor a message cannot be rendered into a notice worth posting, and announcing "something went wrong" with no detail is worse than the silence it replaces.
An unrecognized kind is preserved rather than normalized: it still routes correctly (only the two guardrail kinds are special-cased) and the raw value is more use in a log than "unknown" would be. A frame with a message but no kind is reported as TurnErrorUnknown.
func (TurnError) Guardrail ¶
Guardrail reports whether the failure is a tripped guardrail, which the agent will not clear on its own: it refuses new turns until an operator resets it. The distinction matters to a reader, because unlike every other terminal failure there is a specific thing to go and do.
Only the *first* trip carries one of the two guardrail kinds. Every turn sent afterwards is refused before it runs, and that refusal is an ordinary error routed through the daemon's generic classifier, whose categories do not cover guardrails — so it arrives as TurnErrorUnknown. Since the refusals outnumber the trip (one trip, then every message the reader sends until someone resets), keying on kind alone would get the advice right once and wrong thereafter. Hence the message fallback: if the clause stops matching some day the reader gets the generic terminal notice, which is exactly what they would have got without it.
type TurnUsage ¶
type TurnUsage struct {
// Model is the model that ran the turn, e.g. "gemini-3.7-flash".
Model string
// TokensIn and TokensOut are the turn's prompt and completion tokens.
TokensIn, TokensOut int64
// CostUSD is the turn's cost in US dollars, from "usage-update" only.
CostUSD float64
// Latency is the turn's wall-clock duration, from "turn-complete" only.
Latency time.Duration
}
TurnUsage is the accounting for one conversational turn. No single event carries it: the tokens and cost come from differencing UsageTotals across the turn, and Latency from "turn-complete".
func TurnCompleted ¶
TurnCompleted parses an EventTurnComplete payload for the two things only it knows: that a conversational turn has ended, and how long it took. ok is false on a parse failure or a payload with neither.
type UsageTotals ¶
type UsageTotals struct {
// Model is the model that ran the most recent call.
Model string
// TokensIn, TokensOut and CostUSD are the session's cumulative totals.
TokensIn, TokensOut int64
CostUSD float64
// Calls is the daemon's turns_total: model calls, not user turns.
Calls int64
}
UsageTotals is a session's running accounting, as carried by every EventUsage event.
The totals are what a caller wanting a *conversational* turn's cost has to work from, because the daemon does not report one. Its "turn" is a single model call: one user message that drives five tool calls produces six EventUsage events, each with a last_turn describing only the call that just finished, and turns_total climbing by six. Confirmed live on 2026-08-19 — last_turn.tokens_in was 5,660 on the final event of a turn that had consumed 33,340. Differencing these totals across the turn is the only figure that is not an undercount.
func SessionUsage ¶
func SessionUsage(data string) (t UsageTotals, ok bool)
SessionUsage parses an EventUsage payload and reports the session's running totals. A report of all zeros is valid and meaningful — it is what a fresh session's priming event says — so ok is false only for a payload carrying no totals at all: a parse failure, or an object with none of the fields.