Documentation
¶
Overview ¶
Package wire is the attach protocol's vocabulary: the typed SSE event payloads and their event names, the durable eventlog rows the agent writes for things that happen TO a session (guardrail trips, turn errors, failed context reductions, audit rows), the turn-error classifier, and the small set of capability interfaces and context accessors pkg/agent implements or reads.
It is the part of pkg/attach that pkg/agent EMITS, split out so the agent runtime can speak the protocol without linking the HTTP/SSE server (#1415). Everything here is plain types, constants and pure functions over an ADK session.Event; nothing here may import the server, the broadcaster, the session ACL store, gorm, or net/http handler types. Keeping it that way is what keeps pkg/attach's server — and pkg/auth and the other edges only the server needs — out of the slim embed graph (examples/embed/slim, dev/tools/verify-slim-deps).
pkg/attach re-exports every name declared here under its original identifier (see pkg/attach/wire.go), so callers that already say attach.TurnError keep compiling unchanged. pkg/agent and pkg/agent/background import this package directly so that neither pulls the HTTP/SSE server into the slim embed graph (dev/tools/verify-slim-deps); dev/tools/verify-apidiff recognizes type-alias moves from pkg/attach.X to pkg/attach/wire.X as compatible when pkg/attach/wire.go re-exports X = wire.X. Packages outside the slim graph — pkg/attachadapter, pkg/compose — can keep saying attach.X, which is the same type.
Index ¶
- Constants
- func ContextReductionDegraded(ev *session.Event) (operation, detail string, ok bool)
- func ContextReductionFailure(ev *session.Event) (operation, reason string, ok bool)
- func DirectCaller(ctx context.Context) string
- func InjectTask(ctx context.Context) (string, bool)
- func NewContextReductionDegradedEvent(operation, detail string) *session.Event
- func NewContextReductionFailedEvent(operation, reason string, consecutiveFailures, cooldownTurns int) *session.Event
- func NewGuardrailHaltEvent(guardrail, reason string, haltedTurn bool) *session.Event
- func NewGuardrailResetAuditEvent(identity string, reset []string, budgetUSD float64) *session.Event
- func NewGuardrailTripEvent(guardrail, reason string) *session.Event
- func NewGuardrailTurnTripEvent(guardrail, reason string, haltedTurn bool) *session.Event
- func NewInterruptAuditEvent() *session.Event
- func NewPermModeAuditEvent(identity string, from, to permissions.Mode) *session.Event
- func NewTurnErrorEvent(te TurnError, promptID, cutBy string) *session.Event
- func WithDirectCaller(ctx context.Context, identity string) context.Context
- func WithInjectTask(ctx context.Context, task string) context.Context
- type AgentIdentity
- type AgentInfo
- type AgentStopReporter
- type AgentsProvider
- type Capabilities
- type DescriptionProvider
- type GuardrailPersistedState
- type GuardrailTrip
- type InboxEvent
- type InterruptSelfAuditor
- type PauseEvent
- type SelfClassifyingError
- type StatusUpdate
- type StopAgentOutcome
- type SubagentBudget
- type SubagentCatalogInfo
- type SubagentCatalogProvider
- type SubagentSpawnResponse
- type SubagentSpawner
- type SubagentSpec
- type ToolInfo
- type TurnComplete
- type TurnError
- type UsageByModel
- type UsageLastTurn
- type UsageUpdate
- type WakeEvent
Constants ¶
const ( // ContextReductionFailedEventName is the event name of the row. ContextReductionFailedEventName = "context-reduction-failed" // ContextReductionFailedEventAuthor authors the row. ContextReductionFailedEventAuthor = "agent/context-reduction" )
Event name and author for the context-reduction failure row. The author prefix distinguishes it from model turns in an eventlog tail, and matches the `agent/...` convention the guardrail trip row uses for things that happen TO a session.
const ( // ContextReductionCompaction marks a failed automatic compaction — // the threshold-driven summarizer run (Mechanism A). ContextReductionCompaction = "compaction" // ContextReductionCheckpoint marks a failed automatic task-boundary // checkpoint (Mechanism C). ContextReductionCheckpoint = "checkpoint" )
Values carried under the row's `operation` metadata key. Lowercase nouns rather than the Go method names so a consumer rendering them is not quoting an implementation detail back at an operator.
const ( // ContextReductionDegradedEventName is the event name of the row. ContextReductionDegradedEventName = "context-reduction-degraded" // ContextReductionDegradedEventAuthor authors the row. Same author // as the failure row: an eventlog tail filtered to this prefix // should show the whole story of a session's context reduction. ContextReductionDegradedEventAuthor = ContextReductionFailedEventAuthor )
A context reduction that is still happening, but worse (#974).
Distinct from the failure row above rather than an extra `operation` value on it, because the two say opposite things to whoever is reading during an incident. "Failed and was swallowed" means the mechanism did not run and the context is not being reduced. "Degraded" means it ran — the session is still bounded — on an assumption or a fallback that is worse than the real thing. Filing both under a row literally named `context-reduction-failed` would make a working-but-guessing compactor indistinguishable from an absent one, which is the exact confusion #974 exists to remove.
const ( // ContextReductionWindowUnknown marks a session whose model is not // in the context-window table, so the compaction threshold is being // applied against an assumed window rather than a known one. The // detail carries the model id and the size assumed. ContextReductionWindowUnknown = "window-unknown" // ContextReductionMechanical marks a compaction that was performed // by mechanical truncation because the summarizer was unavailable. // The detail says how much was dropped. ContextReductionMechanical = "mechanical-compaction" // ContextReductionTurnCut marks a turn stopped in flight because a // tool result took the estimated context past the point where the // next request would fit (#975). Compaction is pending when this is // written, so the session heals on its next turn; the detail carries // the estimate, the window, and how much of the estimate was // unmeasured bytes. // // Deliberately a degraded row rather than a guardrail trip: nothing // latches and there is nothing for an operator to reset, so the // guardrail vocabulary would render the wrong affordance. ContextReductionTurnCut = "turn-cut" )
Values carried under the degraded row's `operation` metadata key.
const ( EventCapabilities = "capabilities" EventStatusUpdate = "status-update" EventUsageUpdate = "usage-update" EventInbox = "inbox" EventTurnComplete = "turn-complete" EventTurnError = "turn-error" // EventPause (v1.5.0) reports the session's pause gate opening or // closing. Emitted for every transition regardless of which client // caused it, so a second TUI — or mast-web watching alongside one — // learns that someone else parked the agent without polling // /status. EventPause = "pause" // EventWake (v1.7.0) reports that the session's wake signal fired: // something out-of-band decided the loop should look at the world // again. In a stock daemon that means an operator's POST /wake; the // other producer is a host that calls Agent.RequestWake itself, // which is how a background alert is meant to wake a sleeping // supervisor (see dev/uat/scheduled-monitor). No in-tree code wires // that up for you, so do not read this event as "an alert arrived". // // It is an ATTENTION signal, not a state change: there is no // matching "unwake", and nothing to reconcile on reconnect. // // Deliberately NOT emitted for the wake that Inject fires // internally: that one already has its own frame on the wire (the // `inbox` queued event), and emitting both would make every // operator-typed prompt raise a "something needs you" notice about // the operator's own typing. POST /wake carrying a `prompt` is the // one case that produces both, because it is an inject and an // explicit wake request in the same call. EventWake = "wake" // EventGuardrailTrip (v1.13.0) reports that a guardrail halted the // session. Non-terminal — see the GuardrailTrip payload for why a // trip stopped being a turn outcome. // // The name matches GuardrailTripEventName, the durable eventlog row // #643 already writes for the same fact, deliberately: one thing // that happened, one name for it, whether you read it off the wire // or out of the session's history. EventGuardrailTrip = "guardrail-trip" // EventAgent is the legacy event type carrying ADK session.Event // payloads (stream-chunk / tool-call / tool-result are all // multiplexed onto this one event today). Kept for back-compat // indefinitely — Phase 1 clients in poll mode rely on it, and // even push-mode clients still consume it for the model's // streamed text output. EventAgent = "agent" )
SSE event-type names per the protocol spec (section 2).
const ( TurnStateIdle = "idle" TurnStateStreaming = "streaming" TurnStateAwaitingPermission = "awaiting_permission" TurnStateAwaitingElicit = "awaiting_elicit" )
Turn-state values per spec section 2.2.
const ( InboxStateQueued = "queued" InboxStateDequeued = "dequeued" )
Inbox states per spec section 2.4. The spec reserves room for future states (e.g. "injected"); consumers tolerate unknown values.
const ( PauseStatePaused = "paused" PauseStateResumed = "resumed" )
Pause states carried on PauseEvent.State (v1.5.0).
const ( // ResumeModeSteer resumes with the operator's new instruction // injected under interrupt framing. Implied when Steer is non-empty // and Mode is omitted. ResumeModeSteer = "steer" // ResumeModeContinue resumes with a "carry on where you left off" // note and no new instruction. Implied when Steer is empty and Mode // is omitted. ResumeModeContinue = "continue" // ResumeModeAbandon opens the gate without injecting anything and // without waking the loop: the interrupted work is dropped and the // agent goes quiet until something else drives it. ResumeModeAbandon = "abandon" )
Resume modes: the disposition an operator picks when reopening the pause gate. Carried on ResumeRequest.Mode over the wire and echoed back on PauseEvent.Mode.
const ( TurnErrorConfig = "config_error" TurnErrorAuth = "auth_error" TurnErrorModelNotFound = "model_not_found" TurnErrorRateLimited = "rate_limited" TurnErrorTransientNet = "transient_network" // TurnErrorCostCeiling fires when a configured per-turn or // per-session cost ceiling is exceeded (#145). Agent refuses new // turns until the operator calls ResetCostCeiling on the agent // (typically via a slash command). Retryable=false on this kind // — the host should surface the message + halt automated retry. // Since v1.13.0 (#891) this kind classifies the REFUSAL only — a // turn the pre-flight declined because a prior turn already tripped // the ceiling, which genuinely is that turn's outcome. The trip // itself is no longer reported here; it gets its own non-terminal // `guardrail-trip` event. // // Which means core-agent stops putting this kind on the SSE wire // altogether, and a client watching for it will simply stop seeing // it: the refusal short-circuits above the point where Run installs // the cleanup that emits `turn-error`, so it is delivered as the // iterator's error and as `error.type` on the invocation metric, // not as a frame. The kind stays in the enum because that error and // that label are what a host classifies, and because a different // producer may well emit it. TurnErrorCostCeiling = "cost_ceiling" // TurnErrorWatchdog fires when the behavioral watchdog trips a // Critical runaway signal under --watchdog=enforce (#623). Like the // cost ceiling, the agent refuses new turns until the operator calls // ResetWatchdog on the agent. Retryable=false — the host should // surface the message + halt automated retry (an auto-continue // re-drive would just re-trip the same loop). Also refusal-only // since v1.13.0; see the note on TurnErrorCostCeiling. TurnErrorWatchdog = "watchdog" // TurnErrorRefusalStorm fires when the permission gate ends a turn // because the model kept re-issuing a call the operator had already // refused in it (#1081). Unlike the two kinds above it is **not** a // guardrail: nothing is tripped, nothing needs resetting, and the // next turn runs normally — a model that will not take no for an // answer has had a bad turn, not a broken session. // // Like them, core-agent never puts this on the SSE wire. The cut goes // through Interrupt, so the turn's one terminal frame is `canceled`, // and this kind exists so `error.type` on the invocation metric can // say which kind of deliberate stop it was — the #818 part 2 problem, // where a metrics backend cannot tell a halt from an operator // pressing stop. The durable account of the cut is an audit row in // the eventlog (see pkg/agent/refusal_storm.go), not a frame. TurnErrorRefusalStorm = "refusal_storm" // TurnErrorRefusalLoop fires when the durable write gate ends a turn // because the model kept re-proposing mutating calls the operator had // already refused in that turn (#1400). Retryable=false. TurnErrorRefusalLoop = "refusal_loop" // TurnErrorCanceled fires when the turn's context was cancelled // (#816): an operator interrupt (POST /interrupt, the TUI's ESC), // a parent-context cancel at shutdown, or a guardrail halting the // turn in flight — that last one via Interrupt, and since v1.13.0 // (#891) it is the cut turn's ONLY terminal frame, preceded by a // non-terminal `guardrail-trip` carrying the reason. Every one of // those is a deliberate stop, // so Retryable=false: re-running the work is the opposite of what // was asked for. Distinct from a context.DeadlineExceeded, which // stays transient_network and retryable — a call that ran out of // time is worth another try. TurnErrorCanceled = "canceled" TurnErrorUnknown = "unknown" )
TurnError kinds per spec section 2.6. Consumers MUST treat unknown values as TurnErrorUnknown (forward-compat for new categories).
const ( // GuardrailTripEventName is the event name of a durable trip row. GuardrailTripEventName = "guardrail-trip" // GuardrailTripEventAuthor authors a trip row. The agent writes it, // not an operator — a trip is something that happened TO the // session. GuardrailTripEventAuthor = "agent/guardrail-trip" // GuardrailResetEventName is the event name of a durable reset row. GuardrailResetEventName = "attach-guardrail-reset" // GuardrailResetEventAuthor authors a reset row. GuardrailResetEventAuthor = "attach/guardrail-reset" )
Event names and authors for the durable guardrail rows. The author prefix distinguishes them from model turns in an eventlog tail.
const ( // GuardrailWatchdog is the behavioral watchdog (enforce mode). GuardrailWatchdog = "watchdog" // GuardrailCostCeiling is the per-turn / per-session spend cap. GuardrailCostCeiling = "cost_ceiling" // GuardrailAll targets every guardrail that is currently tripped. // The default when the request names none. GuardrailAll = "all" )
Guardrail names accepted by GuardrailResetRequest.Guardrail and reported in GuardrailResetResponse.Reset (#666). Shared with the durable trip row (#643) and the `guardrail-trip` frame, so an operator UI has one set of names to know.
const ( // PermModeEventName is the event name of a mode-change row. PermModeEventName = "attach-perm-mode" // PermModeEventAuthor authors a mode-change row. PermModeEventAuthor = "attach/perm-mode" )
Durable audit row for a permission-mode change (#1168, protocol 1.16.0). The request/response shapes and the handler stay in pkg/attach; only the row the agent writes lives here.
const ( ToolSourceBuiltin = "builtin" ToolSourceMCP = "mcp" ToolSourceSkill = "skill" ToolSourceSubagent = "subagent" ToolSourceOther = "other" )
Tool source classifications surfaced via GET /sessions/.../tools. Bare strings (not a typed enum) so JSON clients downstream — the TUI, an eventual WebUI, operator scripts — don't have to know a Go type to reason about them.
const ( AgentStatusRunning = "running" AgentStatusCompleted = "completed" AgentStatusFailed = "failed" AgentStatusStopped = "stopped" AgentStatusDeferred = "deferred" )
SUBagent statuses carried on AgentInfo.Status — the string form of background.Status. Distinct from the AgentState* set in pkg/attach, which describes the SESSION's loop rather than one spawned subagent.
const ( // GuardrailTurnTripEventName is the event name of the row recording // a guardrail trip that did NOT halt the session: a per-turn cost // ceiling trip (#1049) or a turn-scoped watchdog cut (#1090). A trip // that halts the session is recorded by the halt row // (GuardrailTripEventName) instead, never by both. GuardrailTurnTripEventName = "guardrail-turn-trip" // GuardrailTurnTripEventAuthor authors the per-turn trip row. // Deliberately not GuardrailTripEventAuthor: the halt fold keys on // that author, and a per-turn trip must not restore as a halt. GuardrailTurnTripEventAuthor = "agent/guardrail-turn-trip" // TurnErrorEventName is the event name of the durable turn-error row. TurnErrorEventName = "turn-error" // TurnErrorEventAuthor authors the turn-error row. TurnErrorEventAuthor = "agent/turn-error" )
Event names and authors for the per-turn failure rows.
Variables ¶
This section is empty.
Functions ¶
func ContextReductionDegraded ¶
ContextReductionDegraded reads a degraded row back out of an eventlog tail. Returns ok=false for any other event — including the failure row, which shares an author and is matched by ContextReductionFailure instead.
func ContextReductionFailure ¶
ContextReductionFailure reads a context-reduction failure row back out of an eventlog tail. Returns ok=false for any other event, so a consumer can run it over an undifferentiated event stream.
Exists so a client (or a test) matches on the row through one function rather than re-deriving the key names, which is how the two halves of a metadata contract drift apart.
Matches on the event name as well as the author: the degraded row below shares this author deliberately, and an author-only match would report a working-but-degraded compactor as a failed one (#974).
func DirectCaller ¶
DirectCaller returns the identity the attach server verified from the request's own credential, or "" when it verified none (an anonymous request carries a placeholder identity, not a verified one) or when a proxy asserted the identity on someone's behalf (X-Asserted-Caller).
It is how an inject tells an operator's own message from one a relay sent under the operator's name: k8s-lookout and chat gateways inject that way, and their text is relayed event or chat content, not the operator's instruction (#1175 decision 6). The agent records it on the queued message and checks it against permissions.auto.task_from.
The auth source /whoami reports is not enough to decide this. A listener's transport bearer token or a verified client certificate upgrades the source, but the identity is then the configured default (multi_session.default_identity, or "anon"), which every holder of that token shares — the operator's TUI and a watcher alike. Only an identity the per-caller authenticator derived from the credential is one caller's.
func InjectTask ¶
InjectTask returns the part of an injected message its client says the operator wrote (InjectRequest.TaskBytes), and whether the client said anything. Without it, the whole message is the operator's. Like DirectCaller, only the inject handler sets it; the agent reads it when it queues the message (#1230).
func NewContextReductionDegradedEvent ¶
NewContextReductionDegradedEvent builds the eventlog row recording that context reduction is running in a degraded mode.
operation is ContextReductionWindowUnknown or ContextReductionMechanical. detail is the operator-facing explanation — the model id and assumed window, or what the truncation dropped.
Writers are expected to emit this at most once per distinct condition per session. It describes a state, not an attempt, and a state re-announced every turn is one operators filter out.
func NewContextReductionFailedEvent ¶
func NewContextReductionFailedEvent(operation, reason string, consecutiveFailures, cooldownTurns int) *session.Event
NewContextReductionFailedEvent builds the eventlog row recording that an automatic context reduction failed and was swallowed.
operation is ContextReductionCompaction or ContextReductionCheckpoint. reason is the error text, carried verbatim — the provider's own explanation for a text-less summary ("finish_reason=MAX_TOKENS") is the whole diagnostic value of the row, so it is not summarised down to a category here.
consecutiveFailures and cooldownTurns describe the backoff the agent applied, and are omitted from the metadata when zero: the checkpoint path has no backoff to report, and a key that is always present but meaningless for half its writers is a key consumers read wrong.
func NewGuardrailHaltEvent ¶
NewGuardrailHaltEvent is NewGuardrailTripEvent plus the halted_turn key the per-turn row carries (#1258). The fold ignores the key; a client rendering a replayed halt needs it, because a halt that cut a turn is followed by a `canceled` turn-error row that core-tui absorbs only under a trip that says it cut the turn — exactly as it does live, off the typed frame's field.
func NewGuardrailResetAuditEvent ¶
NewGuardrailResetAuditEvent builds the durable row recording an operator-initiated guardrail reset (#666). It is both the audit trail (#331) and the state transition that keeps the halt cleared across a restart (#643): CustomMetadata carries who did it, what was cleared, and how much budget was added.
func NewGuardrailTripEvent ¶
NewGuardrailTripEvent builds the durable row recording that a guardrail halted the session. guardrail is GuardrailWatchdog or GuardrailCostCeiling; reason is the operator-facing explanation, carried verbatim so the restored halt says the same thing the original did rather than a reconstruction of it.
func NewGuardrailTurnTripEvent ¶
NewGuardrailTurnTripEvent builds the durable row recording a guardrail trip that left the session running. guardrail is GuardrailWatchdog or GuardrailCostCeiling; reason is the same operator-facing sentence the log line and the typed frame carry, verbatim. haltedTurn mirrors the typed frame's field: true when the trip cut the turn in flight (a `canceled` turn error follows), false when it fired at the boundary.
func NewInterruptAuditEvent ¶
NewInterruptAuditEvent builds the eventlog row that records an operator-initiated interrupt. Author + CustomMetadata identify the source so a later audit query (or attach /events tail) can distinguish operator cancels from any other ctx.Canceled flowing through the agent loop. Shared by the handler's out-of-band fallback (appendInterruptAudit) and by self-auditing registrants (InterruptSelfAuditor) so the two paths can never drift (#565).
func NewPermModeAuditEvent ¶
func NewPermModeAuditEvent(identity string, from, to permissions.Mode) *session.Event
NewPermModeAuditEvent builds the durable row recording an operator's mode change. It is an audit record only: a restarted or resumed session comes back in its configured mode, not the last one an operator picked, so nothing folds these rows back into state. identity is omitted when empty rather than written as a placeholder, so the row never claims an attribution the daemon did not verify.
func NewTurnErrorEvent ¶
NewTurnErrorEvent builds the durable row recording one turn error. te is the classified payload — the same value the typed `turn-error` frame carries, so the two cannot disagree. promptID correlates the row with the turn (empty when the turn never got one: a pre-turn refusal). cutBy names the guardrail whose cut produced the error (a TurnError* guardrail kind, e.g. TurnErrorCostCeiling or TurnErrorRefusalStorm), empty when no guardrail was involved — the error's own kind is then `canceled` and only this key says why.
Optional keys (code, hint, prompt_id, cut_by) are omitted when empty, for the reason NewContextReductionFailedEvent gives: a key that is always present but meaningless half the time is a key consumers read wrong.
func WithDirectCaller ¶
WithDirectCaller stamps DirectCaller's answer onto ctx. Only the attach server's caller middleware writes it; it is exported because the key lives here and the writer lives in pkg/attach.
Types ¶
type AgentIdentity ¶
type AgentIdentity struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Description string `json:"description,omitempty"`
Model string `json:"model,omitempty"`
Provider string `json:"provider,omitempty"`
URL string `json:"url,omitempty"`
}
AgentIdentity is the capabilities.agent block — the producer's own identity, consolidating agent-card + per-session status fields the client would otherwise have to fan-out fetches to assemble. Every field is optional; consumers render only what's present.
type AgentInfo ¶
type AgentInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"` // AgentStatus*: running | completed | failed | stopped | deferred
StartedAt time.Time `json:"started_at"`
ParentSessionID string `json:"parent_session_id,omitempty"`
LastReport string `json:"last_report,omitempty"` // see the type comment
NextWakeAt time.Time `json:"next_wake_at,omitzero"`
WakeDetail string `json:"wake_detail,omitempty"`
}
AgentInfo is one background subagent the parent agent knows about, surfaced via GET /sessions/.../agents. Populated from the BackgroundAgentManager when one is wired; empty list otherwise.
LastReport is the returned result, else the final text, once the subagent has finished; while it runs, its latest report_alert text, or failing that its latest model message, cut to 1 KiB (protocol 1.20.0, #1283).
NextWakeAt and WakeDetail (protocol 1.20.0, #1283) are set only while the subagent is sleeping between turns on a schedule_next_turn wake: the time it will wake, and the one-line reason it gave. Status stays "running" while it sleeps, because a new status word would read as finished to clients that predate it. Both are absent otherwise, and always absent from a pre-1.20.0 daemon.
type AgentStopReporter ¶
type AgentStopReporter interface {
// AttachStopAgentOutcome stops the named background subagent and
// reports what the attempt actually did.
AttachStopAgentOutcome(name string) (StopAgentOutcome, error)
}
AgentStopReporter is the 1.12.0 refinement of AgentStopper: it separates "this call stopped a running subagent" from "the subagent had already finished", which a single bool cannot carry and which the route consequently reported wrong for its whole life (#897).
A separate interface rather than a changed AgentStopper signature, following IdentifyingInjector (#840): these capability interfaces are implemented outside this repository, and the handler degrades to the old answer when only the old method is present.
type AgentsProvider ¶
type AgentsProvider interface {
AttachAgents() []AgentInfo
}
AgentsProvider is the optional capability for GET /sessions/.../agents. Returns the background subagents tracked by the registrant's BackgroundAgentManager (if any).
type Capabilities ¶
type Capabilities struct {
ProtocolVersion string `json:"protocol_version"`
EventTypes []string `json:"event_types"`
Server string `json:"server,omitempty"`
// Features is a feature-flag map derived from live runtime state
// (are MCP servers registered? does the daemon have multi-session
// on? etc.). Consumers should treat absent keys as "off / unknown"
// and unknown keys as forward-compat additions. Suggested initial
// keys are defined as the feature* string constants below.
Features map[string]bool `json:"features,omitempty"`
// SlashCommands lists the server-side slash-command names the
// producer will accept via POST /sessions/.../slash/<name>. Derived
// from capability-interface presence, not a registry table. Clients
// use this to render only the slashes that will actually work
// against the connected agent.
SlashCommands []string `json:"slash_commands,omitempty"`
// Agent identifies the producing agent — same source that feeds
// the /.well-known/agent-card.json endpoint plus per-session
// runtime state (model/provider). Consolidates fields today
// scattered across the agent card, GET /status, and the free-form
// Server banner. Absent when the server doesn't know its own
// identity (rare — implies neither AgentCardConfig nor a
// StatusProvider is wired).
Agent *AgentIdentity `json:"agent,omitempty"`
// CallerID is the resolved Caller.Identity after the auth
// middleware ran, echoed back to the consumer as a display hint.
// The canonical source is GET /whoami (which also carries admin
// + auth source). Empty when the caller couldn't be resolved.
CallerID string `json:"caller_id,omitempty"`
}
Capabilities is the first frame on every newly-opened stream (spec section 2.1). Required so clients can decide push vs poll.
v1.4.0 (#329) added the Features/SlashCommands/Agent/CallerID fields. All four are optional — older clients that don't know about them ignore silently; older servers omit them and the consumer sees the pre-1.4.0 shape unchanged.
type DescriptionProvider ¶
type DescriptionProvider interface {
Description() string
}
DescriptionProvider is the optional capability the agent-card handler consults when AgentCardConfig.Description is empty. Returns a one-line summary of what the agent does — fed by the same source as ADK's llmagent.Config.Description, so the operator writes it once and it flows to both the LLM's system prompt and the public discovery card.
type GuardrailPersistedState ¶
type GuardrailPersistedState struct {
// WatchdogTripped / CostTripped are latched by a trip row and
// cleared by a reset row naming that guardrail.
WatchdogTripped bool
WatchdogReason string
CostTripped bool
CostReason string
// BudgetAddedUSD is the total runway operators granted across every
// reset in the session's history. Applied on top of the CONFIGURED
// per-session ceiling, so an operator who bought $5 of headroom
// doesn't lose it to a pod roll and re-halt at the old bar.
BudgetAddedUSD float64
}
GuardrailPersistedState is the halt state folded out of a session's eventlog — what a fresh process must restore to honor a halt that happened before it started.
func FoldGuardrailEvents ¶
func FoldGuardrailEvents(events iter.Seq[*session.Event]) GuardrailPersistedState
FoldGuardrailEvents replays a session's events in order and returns the guardrail state they imply. Events that aren't guardrail rows are skipped, so callers can hand it a whole session tail.
Malformed rows are ignored rather than failing the fold: a row whose metadata we can't read is a row we can't act on, and refusing to restore ANY state because one row is unreadable would disarm the backstop — the opposite of what a durable halt is for.
func (GuardrailPersistedState) Halted ¶
func (s GuardrailPersistedState) Halted() bool
Halted reports whether the folded state leaves the session refusing turns.
type GuardrailTrip ¶
type GuardrailTrip struct {
// Guardrail is GuardrailWatchdog or GuardrailCostCeiling — the same
// vocabulary as the durable trip row (#643) and the reset endpoint,
// so an operator UI has one set of names to know.
Guardrail string `json:"guardrail"`
// Reason is the operator-facing explanation, verbatim from the
// guardrail that tripped, including what to do about it.
Reason string `json:"reason"`
// HaltedTurn distinguishes the two shapes: true means a turn was cut
// short and its terminal frame is the `canceled` turn-error that
// follows; false means the turn completed and `turn-complete`
// follows. A client that renders a "turn was killed" affordance
// needs this, because the frames after it differ.
//
// Deliberately NOT omitempty. False is a real answer, and a client
// must not have to distinguish it from a field the daemon left out.
HaltedTurn bool `json:"halted_turn"`
// EventID names the durable eventlog row that records this trip
// (v1.19.0, #1258): the `guardrail-trip` halt row when the trip
// halted the session, the `guardrail-turn-trip` row when it did
// not. Same purpose as TurnError.EventID — one failure, counted
// once by a client that received both. Omitted when the session has
// no eventlog.
EventID string `json:"event_id,omitempty"`
}
GuardrailTrip (v1.13.0, #891) reports that a guardrail halted the session: the watchdog tripped on a runaway, or a spend cap was crossed. The session now refuses turns until an operator resets it.
Non-terminal, and that is the whole point. Until v1.13.0 a trip rode out as a `turn-error` with kind `cost_ceiling` / `watchdog`, which made one frame do two unrelated jobs — "the session has halted, here is why" and "this turn ended" — and the two shapes a trip comes in need those answered differently:
- Tripped mid-turn: the guardrail cuts the turn via Interrupt. The turn genuinely ended, so something must be its terminal frame — but the `canceled` turn-error that the cancellation produces is the accurate one, and #818 had to SUPPRESS it to avoid emitting two terminal frames for one turn.
- Tripped at the turn boundary, in the post-turn hook: the turn already produced its answer and emits `turn-complete`. So a consumer saw a `turn-error` followed by a `turn-complete` for the same turn and could not tell from either frame whether the guardrail frame was terminal.
Neither half was droppable — without the guardrail frame an operator never learns why the agent is about to start refusing, and without `turn-complete` a consumer waits forever for a turn that ended. So the trip stops being a turn outcome. It does not participate in the exactly-one-terminal-frame-per-turn rule, it fires identically in both shapes, and the turn's real outcome (`canceled` or `turn-complete`) follows it unmodified. #818's suppression is gone with it.
`cost_ceiling` / `watchdog` remain in the turn-error kind enum for the REFUSAL path — a turn the pre-flight declined because the session was already halted, which is that turn's outcome and nothing else's.
func GuardrailHaltRow ¶
func GuardrailHaltRow(ev *session.Event) (GuardrailTrip, bool)
GuardrailHaltRow reads the halt row (#643) as the GuardrailTrip a client renders. HaltedTurn is read from the row when it carries one (written since #1258) and is false for an older row, which never recorded it. ok=false for any other event.
func GuardrailTurnTrip ¶
func GuardrailTurnTrip(ev *session.Event) (GuardrailTrip, bool)
GuardrailTurnTrip reads a per-turn trip row back out of an event stream. ok=false for any other event, so a consumer can run it over an undifferentiated tail. Matches on author AND name, like ContextReductionFailure, so a future row sharing the author cannot be misread as this one.
type InboxEvent ¶
type InboxEvent struct {
State string `json:"state"`
PromptID string `json:"prompt_id"`
QueuedAt time.Time `json:"queued_at,omitempty"`
}
InboxEvent fires when an operator-typed prompt changes inbox state. PromptID is the correlation handle that links this event to downstream turn-complete / turn-error for the same turn.
type InterruptSelfAuditor ¶
type InterruptSelfAuditor interface {
// MarkInterruptPending records that an operator interrupt fired and
// an audit row should be appended once the current turn unwinds.
// Called from the /interrupt handler only after AttachInterrupt
// reported an in-flight turn was cancelled. Safe to call
// concurrently with the registrant's turn loop.
MarkInterruptPending()
}
InterruptSelfAuditor is the optional capability a registrant implements when it records the operator-interrupt audit event itself, from inside its own serialized turn loop, instead of leaving the /interrupt handler to append it out-of-band.
The handler's fallback (appendInterruptAudit in pkg/attach) does a Get-then-AppendEvent on the live session row while the interrupted turn is still flushing its final events. That extra write bumps the row's last_update_time and can trip the runner's optimistic- concurrency check mid-flush, so the operator's clean cancel surfaces as an opaque "stale session error" instead of ctx.Canceled (#565).
A registrant that implements this interface takes ownership of the audit: MarkInterruptPending records the intent, and the registrant appends the audit row once the interrupted turn unwinds — the one window with no live runner handle racing the write. When a registrant implements it, the /interrupt handler calls MarkInterruptPending and skips its own append.
type PauseEvent ¶
type PauseEvent struct {
State string `json:"state"`
Reason string `json:"reason,omitempty"`
Interrupted bool `json:"interrupted,omitempty"`
Mode string `json:"mode,omitempty"`
At time.Time `json:"at"`
}
PauseEvent fires when the session's pause gate closes or opens — docs/operator-interrupt-design.md. Consumers render a banner from it and (for a TUI) switch the input line into "what do you want me to do instead?" mode.
Interrupted distinguishes the two ways in: true when a turn was actually cancelled on the way to this pause, false for a plain /pause or an /interrupt that landed while the agent was idle. That's the difference between "your work was killed" and "the loop just won't start", which is the first thing an operator asks.
Mode is set only on a resumed event and echoes the disposition the operator chose ("steer" / "continue" / "abandon"), so a second client watching the stream can render what happened rather than just that something did.
type SelfClassifyingError ¶
type SelfClassifyingError interface {
error
// AsTurnError returns the payload to report for this error. It
// should match whatever the raiser emits for the same condition
// on the wire, so the two readings of one event agree.
AsTurnError() TurnError
}
SelfClassifyingError is implemented by an error that already knows which protocol kind it should be reported as. ClassifyTurnError consults it before every heuristic below, so such an error is never left hoping its prose happens to contain one of the substrings the classifier scans for.
It exists because the dependency only runs one way: the packages that raise these errors import pkg/attach to emit events, so pkg/attach cannot import them back and a type switch here is impossible. The interface inverts that — the raiser declares its kind, this package keeps ownership of the vocabulary.
Implemented in-tree by the two guardrail refusals (#818): before them, `cost_ceiling` and `watchdog` were the only kinds in the enum that no classifier path could produce, so a turn refused by a tripped guardrail recorded `error.type: unknown` on gen_ai.agent.invocation.duration — the two outcomes an operator most wants on a dashboard were the two that arrived unlabelled.
type StatusUpdate ¶
type StatusUpdate struct {
Model string `json:"model,omitempty"`
Provider string `json:"provider,omitempty"`
PermMode string `json:"perm_mode,omitempty"`
TurnState string `json:"turn_state"`
ContextPct *int `json:"context_pct,omitempty"`
Capabilities *Capabilities `json:"capabilities,omitempty"`
}
StatusUpdate is emitted on session-level state changes (turn start/end, model swap, perm-mode change, provider change) and also once right after Capabilities as a full snapshot.
Merge semantics: fields not present in an update are unchanged on the consumer side. TurnState is always present on every emission (snapshot or delta) per spec.
Capabilities (v1.4.0+) is an optional merge frame carrying hot changes to the capabilities the server advertised on stream open — e.g. an MCP server registers mid-session and features.mcp flips true, or a new slash provider gets wired. Semantics: any field the server sets is merged into the consumer's cached capabilities; fields absent from the update stay as-is. Not emitted by this server today (spec'd for future use); consumers MUST tolerate its absence.
type StopAgentOutcome ¶
type StopAgentOutcome struct {
// Found reports whether the manager has a subagent registered
// under this name — live or finished. False is the only thing that
// justifies a 404: the operator aimed at a name that does not
// exist, so they missed, and a retry against the same name will
// miss too.
Found bool
// Stopped reports whether THIS call halted a live subagent. False
// with Found=true means it had already reached a terminal status
// before the call arrived.
Stopped bool
// Status is the subagent's status after the call — "stopped" when
// Stopped is true, otherwise whatever it terminated as
// ("completed", "failed", "deferred"). Empty when the registrant
// only implements AgentStopper and cannot say.
Status string
}
StopAgentOutcome is what a stop attempt actually did, as opposed to what the operator asked for. The two differ whenever the subagent beat the operator to it, which is the ordinary case for a subagent an operator only noticed because it had been running a while.
type SubagentBudget ¶
type SubagentBudget struct {
MaxTurns int `json:"max_turns,omitempty"`
MaxCostUSD float64 `json:"max_cost_usd,omitempty"`
MaxWallClockS int `json:"max_wall_clock_seconds,omitempty"`
}
SubagentBudget mirrors agent.BackgroundBudgets. Zero values mean "use the manager's default for that field".
type SubagentCatalogInfo ¶
type SubagentCatalogInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Model string `json:"model,omitempty"` // resolved model id; empty only for a predefined spec that inherits the parent's
Root string `json:"root,omitempty"` // own content root, when rooted
// Modes is how this subagent can be invoked ON THIS SESSION: always
// "async" (spawn_agent by reference), plus "sync" only when this
// session's agent also carries it as a parent tool. A session created
// via POST /sessions gets the background manager but not the
// synchronous subagent tools, so its entries are async-only (#741).
Modes []string `json:"modes"`
// Tools is the subagent's CONFIGURED tool grant, sorted by name and
// classified the same way GET .../tools classifies the parent's
// (#767): builtin / mcp / skill / other, with MCP server attribution.
// It answers "can this specialist actually reach kubectl?" — the
// question an operator asks immediately after "what specialists
// exist?" (#768).
//
// Configured, not effective: the loop-control tools every spawned
// subagent gets wired regardless (return_result, report_alert,
// schedule_next_turn) are absent, because they are a property of the
// runtime rather than of this subagent's configuration. Empty for a
// subagent granted no tools at all.
Tools []ToolInfo `json:"tools,omitempty"`
}
SubagentCatalogInfo is one CONFIGURED subagent in the roster surfaced via GET /sessions/.../subagents (#627) — what the daemon LOADED, as opposed to what it has spawned (AgentInfo / GET .../agents, "what's running"). Populated from the BackgroundAgentManager's catalog when one is wired; empty list otherwise (e.g. --no-background-agents, where nothing is spawnable by reference).
type SubagentCatalogProvider ¶
type SubagentCatalogProvider interface {
AttachSubagentCatalog() []SubagentCatalogInfo
}
SubagentCatalogProvider is the optional capability for GET /sessions/.../subagents (#627). Returns the CONFIGURED subagent roster (declarative templates + predefined catalog specs) — distinct from AgentsProvider, which returns live/spawned instances. Absence (or a nil manager) reports an empty list rather than 501, matching the other read-only projections.
type SubagentSpawnResponse ¶
type SubagentSpawnResponse struct {
Name string `json:"name"`
StartedAt time.Time `json:"started_at"`
}
SubagentSpawnResponse confirms the spawn. StartedAt is the manager's record of when the subagent's first turn dispatched.
type SubagentSpawner ¶
type SubagentSpawner interface {
AttachSpawnSubagent(ctx context.Context, spec SubagentSpec) (SubagentSpawnResponse, error)
}
SubagentSpawner is the optional capability for POST /sessions/.../slash/subagent.
type SubagentSpec ¶
type SubagentSpec struct {
Name string `json:"name"`
SystemPrompt string `json:"system_prompt,omitempty"`
Goal string `json:"goal"`
Tools []string `json:"tools,omitempty"`
Extras []string `json:"extras,omitempty"`
Budgets SubagentBudget `json:"budgets,omitempty"`
Scheduler string `json:"scheduler,omitempty"`
}
SubagentSpec is the POST body for /slash/subagent. Mirrors agent.BackgroundSpec in JSON-friendly form.
type ToolInfo ¶
type ToolInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Source string `json:"source"` // builtin | mcp | skill | subagent | other
Server string `json:"server,omitempty"` // MCP server attribution when Source=mcp
GateState string `json:"gate_state,omitempty"`
}
ToolInfo is one entry in the GET /sessions/.../tools response.
GateState carries the pre-flight projection from permissions.Gate.ToolGateState — empty when no gate is wired (library callers with no permission policy). The TUI v1 fetches the field but doesn't surface it; v1.1 adds the column in the /tools modal.
type TurnComplete ¶
type TurnComplete struct {
PromptID string `json:"prompt_id"`
Model string `json:"model"`
TokensIn int `json:"tokens_in"`
TokensOut int `json:"tokens_out"`
CostUSD *float64 `json:"cost_usd,omitempty"`
LatencyMs int64 `json:"latency_ms"`
}
TurnComplete fires once per turn after the last stream-chunk for that turn and before the next turn's events.
That ordering is enforced, not assumed (#864). `agent` frames reach a subscriber through the eventlog pump while typed frames are published directly, so the terminal frame used to be able to overtake the turn's own final text — and a consumer that finalizes its render here then had nowhere to put what followed. The broadcaster holds a terminal frame until every subscriber has been sent the log through its head; see awaitTerminalBarrier, including the bounded wait that degrades to unordered delivery rather than stalling a turn.
CostUSD is *float64 (optional) per spec v1.1.0 §2.5 — servers whose model layer doesn't know pricing (this server, since agent.* deliberately has no pricing reference) leave it nil and the immediately-following usage-update carries authoritative cost. Servers with in-band pricing populate it.
type TurnError ¶
type TurnError struct {
Kind string `json:"kind"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
Hint string `json:"hint,omitempty"`
// EventID names the durable `turn-error` eventlog row that records
// this same error (v1.19.0, #1258). A client that saw this frame
// live will also receive the row as an `agent` frame; the shared id
// is how it counts the error once. Empty when nothing was persisted
// — no eventlog, or a classification that never reached the wire.
EventID string `json:"event_id,omitempty"`
}
TurnError is emitted on a pipeline failure that should reach the operator. Successful retries do NOT emit this (the spec's "if something is wrong, tell the operator" contract — successful internal retries are not operator-facing failures).
func ClassifyTurnError ¶
ClassifyTurnError maps a raw error from a turn to a TurnError payload conforming to the SSE event-stream protocol's kind enum (spec section 2.6). Most of what reaches it comes off the model call, but not all — the turn's own context surfaces here too — so "the model failed" is not a safe reading of every result.
Classification is string-based rather than type-based because the genai / ADK / Vertex / Anthropic clients each wrap upstream errors differently and changing wrapper layers would silently regress a type-switch. String matching against the canonical status names (gRPC code names, HTTP status numbers, well-known substrings) survives wrapper churn.
The hint field is populated with the most actionable next step when one is obvious — operators reading these in a chat-bubble shouldn't need to leave the TUI to know what to try.
A provider retry that did not rescue its call leads its message with its outcome (models.RetryError, #1206), and the frame keeps that lead even where a branch below replaces the message with fixed text — a recovered stream cut by a deadline would otherwise read "model call timed out" and the transcript would lose the retry the log counted.
func TurnErrorRow ¶
TurnErrorRow reads a turn-error row back as the TurnError payload the typed frame would have carried, with EventID set to the row's id, plus the guardrail that cut the turn (empty if none). ok=false for any other event.
type UsageByModel ¶
type UsageByModel struct {
TokensIn int `json:"tokens_in"`
TokensOut int `json:"tokens_out"`
CostUSD float64 `json:"cost_usd"`
Turns int `json:"turns"`
}
UsageByModel is one model's bucket inside UsageUpdate.ByModel.
type UsageLastTurn ¶
type UsageLastTurn struct {
TokensIn int `json:"tokens_in"`
TokensInCached int `json:"tokens_in_cached,omitempty"`
TokensInCacheWrite int `json:"tokens_in_cache_write,omitempty"`
TokensOut int `json:"tokens_out"`
CostUSD float64 `json:"cost_usd"`
Model string `json:"model,omitempty"`
}
UsageLastTurn captures the just-completed turn's per-turn footer fields — enough for a "◇ 12,345 in · 456 out · $0.0125 · gemini-3.1-pro" row without a follow-up round-trip. Cached input is surfaced when present so future TUI iterations can render a "· 8k cached" tag alongside the base tokens.
TokensInCached and TokensInCacheWrite are disjoint subsets of TokensIn (the third subset, the uncached remainder, is TokensIn minus both). A client that renders only the cached tag on an Anthropic turn shows a split that doesn't add up, which is why the write bucket ships alongside it rather than waiting for a consumer (#263).
type UsageUpdate ¶
type UsageUpdate struct {
TokensInTotal int `json:"tokens_in_total"`
TokensOutTotal int `json:"tokens_out_total"`
CostUSDTotal float64 `json:"cost_usd_total"`
TurnsTotal int `json:"turns_total"`
ByModel map[string]UsageByModel `json:"by_model,omitempty"`
LastTurn *UsageLastTurn `json:"last_turn,omitempty"`
}
UsageUpdate is emitted after each turn finalizes and as a cumulative snapshot on stream open. ByModel is optional — present when the tracker has more than one model bucketed (typical when --agentic-tools routes subtasks to a small model). LastTurn is optional — populated on turn-end emissions (the tracker.Append callback path), omitted on the snapshot emission at stream open where there's no meaningful "last turn" to attribute.
LastTurn carries the just-completed turn's per-turn cost so operator surfaces (remote TUI's per-turn footer) can render authoritative cost without needing client-side pricing lookups. The server's tracker owns the pricing catalog + cache-discount math; clients that recompute inevitably drift.
type WakeEvent ¶
WakeEvent fires when the agent's wake signal is raised (v1.7.0) — see EventWake for which wakes qualify. Carried on the `wake` SSE event.
The payload is deliberately just a timestamp. A wake carries no state a consumer can render: the thing that woke the loop reports itself through its own frames (an alert arrives as an `inbox` event, a subagent's result as `agent` events, the resulting work as `status-update` / `turn-complete`). What the wake adds is "look now", and the only thing worth attaching to that is when. A `reason` field nothing on this side can fill would be a promise to consumers that the producer cannot keep.
Coalescing: none is promised in either direction. The agent's own wake channel is buffered-1 and drops a fire that lands while one is already pending, so two wakes microseconds apart may produce one frame or two. Consumers must treat this as an edge, not a count.