daemon

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: Apache-2.0 Imports: 15 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	EventUsage        = "usage-update"
	EventTurnComplete = "turn-complete"
	EventTurnError    = "turn-error"
	EventStatusUpdate = "status-update"
	EventCapabilities = "capabilities"
)

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.

View Source
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.

View Source
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.

View Source
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.

View Source
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".

Variables

This section is empty.

Functions

func IsTransient

func IsTransient(err error) bool

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
}

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

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 New

func New(cfg Config) (*Client, error)

New validates the config and returns a Client.

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, assertedCaller string) (Session, error)

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) Inject

func (c *Client) Inject(ctx context.Context, sess Session, assertedCaller, text string) error

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.

func (*Client) Wake

func (c *Client) Wake(ctx context.Context, sess Session, assertedCaller string) error

Wake runs a turn on a session with no new input to give it. It is not the companion to Inject — see Inject — but part of the daemon's frozen verb set and the way to rouse a session that has gone idle on its own.

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.

type Event

type Event struct {
	Type string
	Data string
}

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 Session

type Session struct {
	App string
	ID  string
}

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

type StatusError struct {
	Method     string
	Path       string
	StatusCode int
	Message    string
}

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.

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

func ToolCalls(data string) []ToolCall

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

func TurnFailed(data string) (e TurnError, ok bool)

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

func (e TurnError) Guardrail() bool

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

func TurnCompleted(data string) (u TurnUsage, ok bool)

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.

func (TurnUsage) Empty

func (u TurnUsage) Empty() bool

Empty reports whether the usage carries nothing worth showing.

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.

Jump to

Keyboard shortcuts

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