turnevent

package
v0.40.4 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 1 Imported by: 0 modules, 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 turnevent defines the daemon-owned, neutral model of outbound turn events, plus the inbound commands in permission.go.

The types are pure values: no transport, no I/O, standard library only (TestImportBoundary_StdlibOnly). Producers map claude's stream-json output (internal/streamsup) and Codex app-server output (internal/codexsup) into this model, and turnbridge.MapEvent maps it onto the internal/protocol wire types. The model is shaped closely on ACP so an ACP adapter can stay thin, but the daemon owns it, so ACP spec churn stays in that adapter and never reaches the daemon core or the mobile wire.

No variant carries the daemon's conversation identity; the consumer injects it when mapping to the wire. Where a variant carries claude's session_id or uuid, its doc says so; otherwise both are deliberately absent, because claude's session is not the daemon's conversation. See docs/knowledge/features/turnevent-package.md.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ApiRetry added in v0.16.0

type ApiRetry struct {
	Active  bool
	Current int
	Total   int
}

ApiRetry is claude's live API-error retry state, a status peer of Stall. streamsup maps each system/api_retry line to an Active true reading and publishes one Active false edge before the next assistant, user or result content. Current and Total are claude's attempt and max_retries, {0,0} when the counter did not decode.

type BackgroundTask added in v0.16.0

type BackgroundTask struct {
	// TaskID is claude's handle for the task, the join key back to its
	// BackgroundTaskStarted and every BackgroundTaskUpdated.
	TaskID string
	// ToolCallID names the launching tool call in this session and child
	// lifetime; empty when no retained start matched. The hold copies the
	// already-bounded BackgroundTaskStarted.ToolCallID.
	ToolCallID string
	// TaskType is claude's kind for the task, a plain string for
	// BackgroundTaskStarted.TaskType's reason.
	TaskType string
	// Description is the task's label. For local_bash it is the literal command
	// line: safe to render, never to execute or re-shell. A list of command lines
	// is a tempting thing to feed somewhere structured, hence the repeat here.
	//
	// It takes streamsup's tighter maxTaskRosterDescription cap: here it is one
	// label in a list whose length claude chooses, and the full copy already
	// crossed the wire on the BackgroundTaskStarted.
	Description string
	// TruncatedFields names this entry's cut fields in claude's field order,
	// "task_id", "task_type", "description", then "tool_call_id" when the joined
	// start id was cut; otherwise per BackgroundTaskStarted.TruncatedFields.
	TruncatedFields []string
}

BackgroundTask is one row of a BackgroundTaskRoster, not an Event. claude's roster entry has only task_id, task_type and description; ToolCallID is joined in by cmd/pyry's sessionBackgroundTaskHold from a retained BackgroundTaskStarted.

type BackgroundTaskProgress added in v0.16.0

type BackgroundTaskProgress struct {
	// TaskID is claude's handle for the task, the join key back to its
	// BackgroundTaskStarted. It is also the producer's rate key: an empty TaskID
	// still produces events, and all unkeyed lines share one counter.
	TaskID string
	// Description is what the task is doing now, from the emitting line
	// ("Reading alpha.txt" in the capture), not its opening description. Free
	// text capped by streamsup's maxTaskDescription, not the roster's tighter
	// cap, because this event carries it once.
	//
	// Inert text to render, never to execute or re-shell. Captured values name a
	// file the subagent is reading, so it carries path fragments from the
	// operator's host; do not treat it as a safe label.
	Description string
	// SubagentType is claude's kind for the agent doing the work
	// ("general-purpose" in the capture), a plain string for
	// BackgroundTaskStarted.TaskType's reason. Safe to render, never to execute.
	SubagentType string
	// LastToolName is the tool the subagent most recently invoked ("Read" in the
	// capture), under SubagentType's rules. It is not a claim that the tool
	// finished or succeeded.
	LastToolName string
	// TotalTokens, ToolUses and DurationMS are claude's readings off the line's
	// nested usage object, verbatim. They are cumulative per task, so two events
	// for one task carry growing totals: never sum them, diff them for a rate.
	// The producer accumulates nothing. A counter may go backwards and nothing
	// repairs it, so a consumer that subtracts readings must tolerate a negative
	// result.
	TotalTokens int
	ToolUses    int
	DurationMS  int
	// TruncatedFields names cut fields ("task_id", "description",
	// "subagent_type", "last_tool_name") per
	// BackgroundTaskStarted.TruncatedFields.
	TruncatedFields []string
}

BackgroundTaskProgress reports that a background task claude already started is still working, and on what. It maps claude's system/task_progress line, so a long-running task shows movement between its BackgroundTaskStarted and the BackgroundTaskUpdated that ends it.

It is its own variant rather than more BackgroundTaskUpdated fields. Its Description is the task's current activity, not its opening description, and two meanings under one name on one task row would be a wire trap; and SubagentType and LastToolName describe the agent doing the work, not the task's state. It synthesizes no Patch, because BackgroundTaskUpdated.Patch is claude's own bytes by contract.

Rate: the producer emits at most one event per streamsup's minTaskToolCallsPerEvent tool calls of a task's own counter, so events do not enumerate claude's lines, and a gap between two does not mean the task stalled. The rate state is per task and bounded by maxTaskProgressTasks; a task past that cap gets no progress events, though its start and end frames are unaffected.

claude's tool_use_id is not carried; the task's call is BackgroundTaskStarted.ToolCallID. Its documented `summary` is not a field either: the committed capture, a local agent without progress summaries, carries no such key (TestRealClaudeTaskProgressCaptureKeysArePinned). Every string is bounded at construction (streamsup's maxTaskFieldID and maxTaskDescription); the integers need no cap.

type BackgroundTaskRoster added in v0.16.0

type BackgroundTaskRoster struct {
	// Tasks is the roster in claude's order, truncated from the tail past the
	// entry cap; no ranking is invented. nil for an empty roster and when claude
	// omits the key. An empty roster is still emitted: it says nothing is alive.
	Tasks []BackgroundTask
	// DroppedTasks counts entries past the producer's cap that this event does
	// not carry; 0 when none. len(Tasks) + DroppedTasks is claude's roster size.
	// The count reports here rather than as a top-level TruncatedFields, since a
	// name-only report would lose how many were lost; text cuts ride each entry.
	DroppedTasks int
}

BackgroundTaskRoster carries the complete set of background tasks claude is tracking at one moment. It maps claude's system/background_tasks_changed line. The other background-task variants report what happened to one task; this reports what is alive.

The name describes a snapshot, not claude's trigger: a variant called "...Changed" would invite a consumer to read it as a delta, one step from inferring a finish. A task's disappearance from a later roster is never reported as a finish; the only finish the daemon reports is the one claude states, in BackgroundTaskUpdated.Status. A consumer may diff snapshots on its own terms.

Bounded at construction in both dimensions: the entry count by streamsup's maxTaskRosterEntries, since the array length is claude's to choose, and each entry's text by maxTaskFieldID and maxTaskRosterDescription.

type BackgroundTaskStarted added in v0.16.0

type BackgroundTaskStarted struct {
	// TaskID is claude's opaque handle for the task, the join key the later
	// lifecycle lines carry.
	TaskID string
	// ToolCallID is the tool call that spawned the task: claude's tool_use_id,
	// the identifier ToolStart and ToolUpdate carry under this name. The producer
	// cuts and reports an over-long value, where the later
	// ToolCallDenied.ToolCallID drops one.
	ToolCallID string
	// Description is the task's label. For claude's local_bash task type it is
	// the literal command line: safe to render as text, never to execute or
	// re-shell.
	Description string
	// TaskType is claude's kind for the task ("local_bash" in the captured line).
	// A plain string, not a closed enum: one observation does not earn a closed
	// set.
	TaskType string
	// TruncatedFields names the fields the producer cut to fit their caps, in
	// declaration order, by the daemon's snake_case field names rather than
	// claude's keys: "task_id", "tool_call_id", "description", "task_type". nil
	// when nothing was cut, never an empty non-nil slice, so a consumer can emit
	// it as absent rather than []. Every TruncatedFields in this package follows
	// this convention.
	TruncatedFields []string
}

BackgroundTaskStarted announces that claude started a background task: work that outlives the turn that spawned it. It maps claude's system/task_started line.

It opens and closes no turn, and that is the point: a backgrounded command is still alive when the turn ends, and without this event a client cannot tell that turn end from a genuine finish. Every background-task variant shares this.

The name is the daemon's: "Task" alone collides with ACP tool-call vocabulary, and translating at this boundary keeps a claude rename of the subtype inside the parser. Every background-task variant follows this rule.

Every string field is claude-derived and bounded at construction (streamsup's maxTaskFieldID and maxTaskDescription), so an oversized payload never enters the event stream, a queue or a log.

type BackgroundTaskUpdated added in v0.16.0

type BackgroundTaskUpdated struct {
	// TaskID is claude's handle for the task, the join key back to its
	// BackgroundTaskStarted.
	TaskID string
	// Patch is claude's patch object (what changed about the task), carried
	// whole and unparsed as text, so a patch key claude adds later is not
	// discarded. One key has been observed (is_backgrounded). Empty when claude
	// omits it; "" and "{}" stay distinguishable.
	//
	// A plain string, not json.RawMessage, for Unrecognized.Raw's reason: a
	// truncated object is not valid JSON, so a consumer must not assume it
	// parses. The producer also deletes invalid UTF-8 bytes (streamsup's
	// truncateField), even when nothing is cut, and TruncatedFields reports only
	// the cap cut, so Patch can differ from claude's bytes without being listed.
	//
	// Safe to render as text, never to execute or re-shell: a patch key may carry
	// command text.
	Patch string
	// Status is the terminal state claude reported on system/task_notification;
	// empty on task_updated events and when claude omits it.
	//
	// It is claude's report, not the daemon's detection: the daemon does not
	// verify that the task stopped. A plain string, not a closed set: only
	// "completed" has been observed, and the documented "failed" and "stopped"
	// were never captured. Safe to render, never to execute.
	Status string
	// Summary is claude's account of what the task did, from
	// system/task_notification; empty on task_updated events and when claude
	// omits it. Model-authored free text with no documented length bound, capped
	// by streamsup's maxTaskSummary. Captured values range from the task's
	// literal command line to multi-line prose, so it is inert text to render,
	// never to execute or re-shell.
	Summary string
	// TruncatedFields names cut fields ("task_id", "patch", "status", "summary")
	// per BackgroundTaskStarted.TruncatedFields. Because the subtypes fill
	// disjoint fields, one event names fields from only one of them, plus
	// "task_id".
	TruncatedFields []string
}

BackgroundTaskUpdated reports that a background task claude already started changed state. Two claude subtypes produce it and fill disjoint fields:

  • system/task_updated fills Patch: a mid-life change.
  • system/task_notification fills Status and Summary: the task ending.

A non-empty Status therefore says a terminal state was reported. No field names the producing subtype, since that would be content the daemon invented. It is one variant rather than two because a client already joins the background-task frames on TaskID, and a second frame would differ only in which fields it fills.

output_file (a path on the operator's host) and tool_use_id are not on the producer's decode target, so no code path holds them; the task's tool call is already BackgroundTaskStarted.ToolCallID. Every string field is bounded at construction (streamsup's maxTaskFieldID, maxTaskPatch and maxTaskSummary).

type Banner struct {
	// Level is claude's `level` key, verbatim: an open set, on
	// TurnEnd.Outcome's rule. "warning" is observed (claude 2.1.259, in
	// internal/e2e/realclaude/testdata/operator_system_lines_v2.1.259.json);
	// "info", "notice" and "suggestion" are documented but not observed.
	//
	// Dropped rather than cut past the producer's bound, on
	// CompactionBoundary.Trigger's rule, because a consumer matches it. An
	// emptied Level is directly observable and needs no report.
	Level string
	// Text is claude's `content`, renamed so it does not read as the frame's own
	// body. It is the field this variant exists to carry. Bounded at 4 KiB by
	// streamsup's maxBannerText and cut rather than dropped; Truncated says
	// whether a cut happened.
	//
	// Security: claude-authored, bounded and not sanitized, and arbitrary prose:
	// newlines, terminal escapes, markup, a URL and text impersonating daemon
	// chrome all fit, and the observed line contains a host path and echoes the
	// operator's prompt. Treat it as inert text on
	// protocol.UnrecognizedMessagePayload.Raw's rule (never an HTML sink, an
	// attribute or a URL) and attribute it to claude.
	Text string
	// Truncated is the producer's answer on whether it cut Text; use it rather
	// than recomputing from len(Text). Text is the only field the daemon cuts, so
	// one bool suffices.
	Truncated bool
	// StopsTurn is claude's `prevent_continuation`, renamed: claude will not
	// continue past this banner (observed true on a hook that refused a prompt).
	// It is the only client-visible sign that a prompt was refused, since such a
	// prompt opens and closes no turn.
	//
	// A report, never an actuator, despite a name that reads like a lever:
	// keying a teardown, retry suppression or queue decision on it would let a
	// fabricated line abort the operator's work. Nothing acts on it; making it an
	// actuator needs a security review.
	StopsTurn bool
}

Banner reports operator-facing text claude printed about the session rather than as part of an answer, such as a hook's block reason. streamsup's emitInformationalBanner maps claude's system/informational line, and codexsup's translator reports a Codex model reroute as a warning banner.

It carries no turn identity: a prompt a hook refuses is never answered, so no turn exists to attribute it to. It opens and closes no turn.

Every field is claude's, and so is the fact of the banner, which nothing else on the wire can confirm. Its whole purpose is arbitrary claude-authored prose shown as a first-class notice, so text impersonating daemon chrome at Level "warning" is the realistic abuse: render it as claude's assertion, attributed to claude. Nothing in the daemon acts on any field.

type Cancel

type Cancel struct{}

Cancel is an inbound command: stop the current turn (the neutral form of a remote Esc / ACP session/cancel, #600). Fieldless — the daemon has one live turn context, so no correlation id is needed yet; #600 adds a session/turn id additively if ACP needs one.

Cancel is declared vocabulary in this slice: the mobile interrupt frame routes to Esc directly via the relay seam (internal/relay handleInterrupt), it does not construct a Cancel value — mirroring how the mobile modal_cancel frame routes to ModalResolver.ResolveCancel rather than building a PermissionResponse. The mobile-wire → neutral-Cancel translator is the ACP adapter's job (#600); Cancel exists now so #600 has its target.

type Compacting added in v0.16.0

type Compacting struct {
	Active bool
	// Result is claude's compact_result off the closing system/status line
	// ("success" observed at claude 2.1.259). An open set carried verbatim, on
	// TurnEnd.Outcome's rule. Empty on every rising edge, when claude sends no
	// key and on the daemon's turn-boundary reset; those are one reading.
	//
	// It is not a discriminator anywhere in the daemon: the falling edge depends
	// only on claude's status leaving "compacting", so a failed compaction closes
	// the banner exactly as a successful one does. This field says which it was.
	Result string
	// ErrorText is claude's compact_error off the same line: free-form prose on
	// why a compaction failed, absent on success. Named ErrorText, not Error, to
	// avoid confusion with the error interface.
	//
	// Bounded at 256 bytes by streamsup's maxCompactField and cut rather than
	// dropped, since a cut sentence still reads as what it is. The cut is not
	// reported, and truncateField scrubs a mid-rune cut.
	//
	// Security: claude-authored, bounded and not sanitized, and arbitrary prose:
	// newlines, terminal escapes, markup, a URL or text impersonating daemon
	// chrome all fit in 256 bytes. Render it as inert text attributed to claude
	// (protocol.UnrecognizedMessagePayload.Raw's rule); the client's render
	// boundary owes the stripping. Nothing in the daemon acts on it.
	ErrorText string
}

Compacting reports that claude is compacting the conversation. Active is the rising (true) or falling (false) edge, which is what lights and clears a client's banner. streamsup's emitCompactingStatus maps claude's system/status line, streamsup's turn-boundary reset also produces a falling edge, and codexsup maps Codex's contextCompaction item. The falling edge off claude's closing status line carries claude's outcome in Result and ErrorText.

type CompactionBoundary added in v0.16.0

type CompactionBoundary struct {
	// Trigger is claude's compact_metadata.trigger: "manual" observed (a typed
	// /compact), "auto" documented. An open set carried verbatim, on
	// TurnEnd.Outcome's rule.
	//
	// Bounded at 256 bytes by streamsup's maxCompactTrigger and dropped rather
	// than cut: a consumer matches this token, and a cut token would match
	// nothing while looking real. It is the only droppable field here, so an
	// empty value needs no drop report.
	//
	// Security: claude-authored, bounded and not sanitized; a short open-set
	// token, so switch on it against known values.
	Trigger string
	// PreTokens and PostTokens are claude's context size before and after the
	// compaction, as stated. Pointers because an omitted count and a count of
	// zero are different facts, and post_tokens is optional in claude's shape: nil
	// means claude stated none.
	//
	// Neither is clamped, range-checked or ordered; PostTokens above PreTokens is
	// kept as sent. A value that does not fit an int fails the whole line's decode
	// and produces no event.
	PreTokens  *int
	PostTokens *int
}

CompactionBoundary reports that a compaction finished, what triggered it and how far the context shrank. It maps claude's system/compact_boundary line.

It is a separate variant, not more Compacting fields, because of line order. In the committed capture, internal/e2e/realclaude/testdata/compaction_v2.1.259.json, claude sends status "compacting", then the closing status line where Compacting's falling edge fires, then system/init, then this line. The counts arrive after the edge has shipped, so a client applies them to the divider it already drew. The producer (streamsup's emitCompactionBoundary) reads and writes no parser state, so it also fires when no compacting edge preceded it.

Every field is claude's, and so is the fact of the boundary: a fabricated line draws a plausible compaction where none happened. Render it as claude's assertion, never the daemon's finding. Nothing in the daemon acts on any field.

The rest of compact_metadata is not on streamsup's decode target: cumulative_dropped_tokens and duration_ms have no consumer, and preserved_segment, preserved_messages and logical_parent_uuid name entries in the operator's own transcript. It opens and closes no turn.

type ContextUsage added in v0.16.0

type ContextUsage struct {
	Model              string
	TotalTokens        int
	MaxTokens          int
	Percentage         int
	Categories         []ContextUsageCategory
	DroppedCategories  int
	MCPTools           []ContextUsageMCPTool
	DroppedMCPTools    int
	MemoryFiles        []ContextUsageMemoryFile
	DroppedMemoryFiles int
}

ContextUsage is one solicited reading of claude's context-window arithmetic. It is informational only: consumers may display it, but it does not replace the daemon-owned contextwindow.Read value used for control decisions.

Every claude-authored string and every list is bounded by streamsup at construction (maxContextUsageStringBytes, maxContextUsageEntries), and each Dropped count reports the entries omitted from its list. Each list is ordered by descending token count so a count cut keeps the heaviest entries. The scalar integers are claude's own values; the daemon neither recomputes nor normalizes them.

type ContextUsageCategory added in v0.16.0

type ContextUsageCategory struct {
	Name   string
	Tokens int
}

ContextUsageCategory is one named contribution to a ContextUsage reading.

type ContextUsageMCPTool added in v0.16.0

type ContextUsageMCPTool struct {
	Name       string
	ServerName string
	Tokens     int
}

ContextUsageMCPTool is one MCP tool's contribution to a ContextUsage reading.

type ContextUsageMemoryFile added in v0.16.0

type ContextUsageMemoryFile struct {
	Path   string
	Type   string
	Tokens int
}

ContextUsageMemoryFile is one memory file's contribution to a ContextUsage reading. Path is descriptive; nothing on this event path opens it.

type ConversationReset added in v0.16.0

type ConversationReset struct {
	// NewConversationID is the id claude says it mounted the fresh transcript
	// under, verbatim.
	//
	// Canonical by construction and never empty: the producer (streamsup's
	// emitConversationReset) runs it through transcript.ValidStem and emits
	// nothing on failure, so a consumer holds a 36-character lowercase
	// hex-and-hyphen stem or no event at all. A resolver of <dir>/<id>.jsonl may
	// use it as a filename component, since the alphabet holds no path
	// metacharacter. The check lives in the producer because this package
	// imports only the standard library. The fixed-length match bounds the value
	// more tightly than a cap would, so there is no cap and no Truncated report.
	//
	// Well-formed is not authentic: a buggy or compromised claude can announce
	// any well-formed stem, including another session's. A consumer that re-keys
	// on it owns the authorization question.
	NewConversationID string
}

ConversationReset reports that claude reset the conversation and mounted a fresh transcript under a new id. It maps claude's top-level conversation_reset line, which claude writes when a /clear, a plan-mode exit or a fresh-session flow runs. It opens and closes no turn.

It carries claude's own identity on purpose, the one exception to the package rule: following claude to the transcript it just mounted is the reason the event exists.

Its consumer is cmd/pyry's sessionResetFollower. interactiveTurnEmitterV2.Handle has no case for it and turnbridge.MapEvent does not map it: the boundary a client draws comes from the session_transition frame.

type DiffContent

type DiffContent struct {
	Path    string
	OldText string
	NewText string
}

DiffContent is a file edit a tool produced.

type Event

type Event interface {
	// contains filtered or unexported methods
}

Event is the sealed sum type of outbound turn events. The isTurnEvent markers below and in permission.go list every variant, and the unexported marker keeps the set closed to this package.

Consumers type-switch on it: turnbridge.MapEvent, and cmd/pyry's turnMarkFor, eventKind and interactiveTurnEmitterV2.Handle. Only turnMarkFor is checked for totality (TestTurnMarkFor_TotalOverEveryVariant reads these markers), so a new variant means checking every switch by hand; see turnevent-package.md § The three sum-type seams.

type Inbound

type Inbound interface {
	// contains filtered or unexported methods
}

Inbound is the sealed sum type of inbound commands the consumer sends back to the daemon. The unexported marker keeps the variant set closed to this package, mirroring Event and ToolContent. PermissionResponse is the first member; #707 adds Cancel. The remaining deferred inbound commands (Prompt / DropQueued) join the same set when their tickets land. Cancel keeps the marker here beside its sibling — the relocation to a separate file hinted above is optional churn this slice declines.

type Location

type Location struct {
	Path string
	Line int
}

Location is a file a tool call touches (ACP tool-call location). Line is 1-based; 0 means unspecified.

type MCPServerStatus added in v0.16.0

type MCPServerStatus struct {
	Name    string
	Status  string
	Error   string
	Scope   string
	Version string
}

MCPServerStatus is one entry of MCPStatus, not an Event. It carries only the server object's top-level name, status, error and scope plus serverInfo.version. Config, tools and serverInfo.name are not on the decode target, so no consumer can recover credentials, argv, tool metadata or a second spelling of the server name from it.

Every field is copied without canonicalisation and is untrusted, unsanitized text. Error, the one free-form prose field, is cut to streamsup's maxMCPStatusError bytes as valid UTF-8. A renderer must treat every string as inert claude-authored content, never as an actuator or command argument.

type MCPStatus added in v0.16.0

type MCPStatus struct {
	Servers        []MCPServerStatus
	DroppedServers int
}

MCPStatus is one shape-recognised reading of the MCP servers claude reports, once per eligible initialize exchange. turnbridge.MapEvent publishes it as protocol.MCPStatusPayload; no daemon behaviour is keyed on it, and it opens and closes no turn. An empty Servers is meaningful (claude sent mcpServers:[]), so the producer emits it; a missing or unusable payload emits no event.

Servers keeps claude's order and at most streamsup's maxMCPStatusServers entries. DroppedServers counts every entry omitted from the tail, so len(Servers) + DroppedServers is claude's array length. The count is daemon-derived; every string remains claude-authored.

type ModelAnnounced added in v0.16.0

type ModelAnnounced struct {
	// Model is claude's announced identifier, verbatim: no lowercasing, alias
	// expansion, date-stamping, family mapping or lookup against a published
	// model list. Other fields cite this as ModelAnnounced.Model's rule. Never
	// empty: the producer does not emit on an empty model.
	//
	// claude echoes an identifier at least as specific as the one it was given:
	// it dates a bare alias (haiku → claude-haiku-4-5-20251001) and passes one
	// already fully formed through (claude-haiku-4-5). So the value is not
	// reliably dated and need not appear in any published model list, which is a
	// reason to carry it untouched.
	//
	// Bounded and valid UTF-8 is all it is: streamsup's truncateField scrubs
	// invalid UTF-8, but nothing strips control characters or terminal escapes,
	// and only a phone-supplied override passes internal/relay's validModel.
	// turnbridge.MapEvent publishes it as protocol.ModelAnnouncedPayload, so the
	// client's render boundary owes the sanitization.
	Model string
	// Truncated reports whether Model was cut to fit the producer's cap. A bool
	// rather than a TruncatedFields slice because the payload is a single string,
	// so a slice could only ever be nil or ["model"].
	Truncated bool
}

ModelAnnounced reports the model claude says it is running, from claude's system/init line. It is the only thing that answers what is running: the model on protocol.ScreenSnapshotPayload and protocol.SessionSettingsPayload is the per-session override, "" when inherited, so the daemon knows what it asked for and only claude knows what it got.

Per line, not per session: claude emits init once per turn, so one session produces several and they need not agree. A /model turn's own init still reports the old model, so a consumer should render the latest announcement, not latch the first. The producer does not dedup, which would need turn state the parser does not hold. It opens and closes no turn.

The init line carries 24 keys and this variant one. cwd, memory_paths and messaging_socket_path are paths on the operator's host and are not on the producer's decode target (streamsup's systemInitLine), so they cannot leak. The model is bounded at construction by streamsup's maxModelField.

type ModelList added in v0.16.0

type ModelList struct {
	// Models is the inventory in claude's order, reduced to one row per family:
	// the producer drops each pinned row whose family row is present and keeps
	// only the newest pinned row of a family that has none
	// (internal/modelfamily.Reduce, applied before the entry cap), because a pyry
	// session follows a family's latest model. No ranking is invented and no
	// surviving row is changed. Never empty: the producer does not emit an empty
	// array, and the reduction never empties a list.
	//
	// Three dimensions, all bounded at construction. Per-entry text by
	// streamsup's maxModelResolved, maxModelValue, maxModelDisplayName and
	// maxModelEffortLevel, reported in ModelOption.TruncatedFields. The entry
	// count by maxModelListEntries, truncated from the tail and reported as
	// DroppedModels. The per-entry level count by maxModelEffortLevelCount,
	// reported as "effort_levels" on that entry.
	Models []ModelOption
	// DroppedModels counts entries past the producer's cap that this event does
	// not carry; 0 when none. len(Models) + DroppedModels is the reduced list's
	// size; rows the family reduction removed are not counted, since a rule
	// removed them rather than the size cap. It reports here rather than in a
	// top-level TruncatedFields for BackgroundTaskRoster.DroppedTasks' reason, and
	// it is daemon-derived.
	DroppedModels int
}

ModelList is claude's inventory of selectable models: the models array of the initialize reply, which the daemon solicits once per child with streamsup's WriteInitialize and claude answers on a control_response line. It answers what can be run, before the first turn, with each alias's current resolution.

It is an Event rather than parser-held state so it reaches the wire on the same path as every other interactive payload: turnbridge.MapEvent maps it onto protocol.ModelListPayload, which takes its ConversationID at mapping time.

Delivery: interactiveTurnEmitterV2.Handle emits it on the interactive lane, best-effort, since turnMarkFor answers turnMarkNone and the fan-in may drop it under load. cmd/pyry's sessionModelHold retains the value for the session's life, and the relay's connect-time reconcile (retainedModelLists) sends it to a client that connects later.

The producer emits nothing for an ambiguous line rather than a list it did not observe: a missing menu beats a wrong one. It opens and closes no turn and is not per turn: one initialize exchange per child produces one.

type ModelOption added in v0.16.0

type ModelOption struct {
	// ResolvedModel is what Value resolves to now: the concrete identifier, and
	// the field to use for a dated one. Verbatim per ModelAnnounced.Model's rule.
	// It need not be dated or appear in any published list: the capture's
	// claude-sonnet-5, claude-opus-5 and claude-fable-5 are undated.
	ResolvedModel string
	// Value is the argument passed to select this model: an alias (sonnet), a
	// bracketed variant (claude-fable-5[1m]) or default, not a dated identifier.
	// A consumer cannot derive a family by splitting it on "-" or assume it
	// round-trips; see protocol.ModelOption.Value for the inbound gap and why
	// internal/relay's validModel is not widened to close it.
	Value string
	// DisplayName is claude's human label for the entry ("Default
	// (recommended)", "Haiku 4.5"): prose to render as inert text, never a key to
	// match on. Bounded and not sanitized, so the client's render boundary owes
	// the sanitization, as protocol.ModelOption's SECURITY paragraph states for
	// all three strings.
	DisplayName string
	// EffortLevels are the reasoning-effort levels claude published for this
	// model, so a client's effort control offers exactly what claude accepts.
	// Verbatim per ModelAnnounced.Model's rule, in claude's own order (low,
	// medium, high, xhigh, max in the capture, which is not sorted). Bounded and
	// valid UTF-8 only, under DisplayName's security reading.
	//
	// Bounded at construction in both dimensions: each level by streamsup's
	// maxModelEffortLevel, the count by maxModelEffortLevelCount, since the
	// array length is claude's to choose.
	//
	// An absent key, a JSON null and a published [] are one reading, nil;
	// streamsup's emitModelList normalises the zero-length list at construction.
	// The daemon has no fallback effort vocabulary, so every reading gives the
	// same instruction: there is no menu to offer. The distinction would not
	// survive the wire either (protocol.ModelOption.MarshalJSON sends [] for
	// nil), and slices.Equal(nil, []string{}) is true, so the usual assertions
	// could not see it. Only Go's spelling of zero is normalised; elements and
	// order stay claude's. Full argument:
	// streamsup-package-the-per-entry-byte-budget-s-third-dimension.md.
	//
	// When TruncatedFields names "effort_levels", a level was cut, the count cap
	// shortened the list, or both. The list is then not claude's published menu
	// and must not be offered as one; the true level count is not recoverable
	// from this event.
	//
	// internal/relay's validEffort is not applied to this list and must not be
	// widened or narrowed to match it. It bounds a phone-supplied value on an
	// inbound path: applying it here would drop a level claude adds, and widening
	// it to claude's list would let the subprocess extend what an untrusted
	// inbound frame may set.
	EffortLevels []string
	// SupportsAutoMode is claude's answer to whether it accepts auto permission
	// mode for this model, so a client's permission-mode menu can grey the option
	// out. Verbatim, with no daemon policy folded in.
	//
	// An absent key, a JSON null and false are one reading, false. That is the
	// safe direction for a grant: "claude refused" and "claude said nothing" both
	// grey the option out, and granting on silence would be the unsafe collapse.
	// claude has never been seen to send false, and
	// protocol.ModelOption.SupportsAutoMode makes the same collapse, so a *bool
	// would carry nothing to the wire.
	//
	// It is a report to a client's menu, never an authorization input: nothing in
	// the daemon may branch on it to decide what to send claude, since that would
	// be a subprocess authorizing itself. A bool is never cut, so it never appears
	// in TruncatedFields.
	SupportsAutoMode bool
	// TruncatedFields names this entry's cut fields ("resolved_model", "value",
	// "display_name", "effort_levels") per
	// BackgroundTaskStarted.TruncatedFields. "effort_levels" reports either of
	// that list's two cuts, at most once.
	TruncatedFields []string
}

ModelOption is one entry of a ModelList, not an Event. Its claude-authored fields are exactly protocol.ModelOption's, in that type's declaration order.

The capture's other per-entry keys are not on the producer's decode target: description, supportsFastMode, supportsAdaptiveThinking and supportsEffort have no consumer, and protocol.ModelOption carries none of them. supportsEffort would add nothing, since a nil EffortLevels already says what supportsEffort false or absent would say.

type ModelRefusalFallback added in v0.16.0

type ModelRefusalFallback struct {
	// Scope is how long the fallback lasts: "session" keeps the session on
	// FallbackModel, so a later ModelAnnounced reports a different model and this
	// event explains why; "local" retries only the refused turn. Documented, not
	// exhaustive: an open set on TurnEnd.Outcome's rule. Dropped rather than cut,
	// since a consumer matches it.
	Scope string
	// OriginalModel is the model that refused; FallbackModel is the one claude
	// retried on. Both verbatim per ModelAnnounced.Model's rule. Dropped rather
	// than cut, on ToolCallDenied.ToolCallID's rule: a consumer joins
	// FallbackModel against the ModelAnnounced it holds.
	OriginalModel string
	FallbackModel string
	// RefusalCategory is claude's open classification of what it refused
	// ("cyber" and "bio" are documented examples). It is claude's assertion about
	// a user's request, never the daemon's finding, and it is accusatory: a
	// mistaken line attributes a category to a user who triggered none. Render it
	// attributed to claude and never act on it. Dropped rather than cut, as a
	// matched token.
	RefusalCategory string
	// RefusalExplanation is claude's display prose about the refusal, and Banner
	// is the announcement text claude wrote for the swap (its `content` key, named
	// for its documented role). Both are cut rather than dropped.
	//
	// Security: claude-authored, bounded and not sanitized. Prose about a refused
	// request can quote or paraphrase the user's own words, or the command or code
	// claude declined to produce. Safe to render as text, never to execute or
	// re-shell.
	RefusalExplanation string
	Banner             string
	// TruncatedFields names cut fields ("refusal_explanation", "banner") per
	// BackgroundTaskStarted.TruncatedFields.
	TruncatedFields []string
	// DroppedFields names dropped fields ("scope", "original_model",
	// "fallback_model", "refusal_category", not claude's api_refusal_category)
	// per ToolCallDenied.DroppedFields. With a documentation-derived field set any
	// key may be absent, so the two reports are what separate an empty value
	// claude sent from one the daemon emptied.
	DroppedFields []string
}

ModelRefusalFallback reports that a turn ended with stop reason refusal, that claude retried it on a fallback model and, when Scope says so, that the session stays on that model. It maps claude's system/model_refusal_fallback line; without it a client sees the model change on the next ModelAnnounced with nothing explaining it. The name avoids "swapped" because a local-scope fallback is only a one-turn retry. It opens and closes no turn.

It is claude's announcement of what it will run next; ModelAnnounced stays the authority on what it is running. Read the cause here and the result there: a client that updates its model state from FallbackModel trusts a prediction as an observation.

Every field is claude's, and so is the fact of the fallback. The daemon has nothing to verify it against, and nothing in the daemon acts on any field (no routing, retry, model selection or session setting).

The field set is documentation-derived, not capture-derived: read from the Claude Code headless docs and @anthropic-ai/claude-agent-sdk@0.3.263's sdk.d.ts against claude 2.1.259. No capture exists, because a refusal cannot be provoked without a prompt this repo should not contain, so every key is treated as optional. Five keys are not on the decode target: trigger and direction restate the subtype, request_id is API-internal, and retracted_message_uuids and refused_user_message_uuid name claude message ids no daemon surface can join, so a consumer cannot honour the retraction of the refused partial response.

Every string is bounded at construction (streamsup's maxTaskFieldID and maxDenialProse) and valid UTF-8, nothing more: nothing strips control characters or terminal escapes, so a client owes the sanitization at its render boundary.

type ModelRefusalNoFallback added in v0.16.0

type ModelRefusalNoFallback struct {
	// OriginalModel is the model that refused, verbatim, without alias expansion
	// or validation against a model list. Dropped rather than cut, because a
	// client matches the identifier and a cut token looks real while joining to
	// nothing.
	OriginalModel string
	// RefusalCategory is claude's open classification string, such as "cyber" or
	// "bio": claude's assertion about the request, never the daemon's finding, so
	// a consumer must attribute it accordingly. Dropped rather than cut, as a
	// matched token.
	RefusalCategory string
	// RefusalExplanation is claude's display prose about the refusal; Banner is
	// the announcement text from claude's `content` key. Both may quote or
	// paraphrase the user's refused request, code or command line. Inert text:
	// render it with the consumer's sanitization, never execute or re-shell it.
	// Both are cut rather than dropped, since a shortened sentence stays useful.
	RefusalExplanation string
	Banner             string
	// TruncatedFields names cut fields ("refusal_explanation", "banner") per
	// BackgroundTaskStarted.TruncatedFields.
	TruncatedFields []string
	// DroppedFields names dropped fields ("original_model", "refusal_category")
	// per ToolCallDenied.DroppedFields.
	DroppedFields []string
}

ModelRefusalNoFallback reports that claude ended a turn with stop reason refusal and did not retry it on another model. It maps claude's system/model_refusal_no_fallback line and is deliberately distinct from ModelRefusalFallback: this turn stopped, where that one was retried.

It is claude's assertion, not a daemon finding, and ModelAnnounced remains the authority on which model claude is running. Nothing in the daemon acts on these fields (no routing, retry, teardown, model selection or session setting), so a fabricated or mistaken line can mislabel a refusal but cannot actuate the daemon.

The field set is documentation-derived from the same sources as ModelRefusalFallback's, so every field is optional. An empty field named in neither report below means claude omitted or emptied it; a field named in a report means the daemon bounded it. request_id and refused_user_message_uuid are not on the decode target, so the refused partial cannot be retracted on this wire.

Every string is bounded at construction (streamsup's maxTaskFieldID and maxDenialProse) and valid UTF-8, nothing more: control characters, terminal escapes and markup are not sanitized. It opens and closes no turn.

type ModelWindow added in v0.16.0

type ModelWindow struct {
	// ModelID is the key claude used in its modelUsage map, verbatim per
	// ModelAnnounced.Model's rule. It need not be dated, and an alias pair may
	// name one model twice (see TurnEnd.ModelWindows).
	//
	// Security: claude-authored, bounded by streamsup's maxModelWindowID and not
	// sanitized. It is not published to clients; whoever publishes it owes
	// sanitization at the client's render boundary.
	//
	// An id past the cap is dropped with its entry, never cut: a cut id names no
	// model, and a consumer joining on it would silently match nothing.
	ModelID string
	// WindowTokens is the context window claude reported for this model, in
	// tokens, always > 0. An int, matching contextwindow.Usage.WindowTokens, the
	// value it feeds. It is claude's reported number rather than one inferred from
	// the model name, which matters: a session announced as plain claude-sonnet-5,
	// with no [1m] marker, reported a 1M window.
	WindowTokens int
}

ModelWindow is one entry of TurnEnd.ModelWindows: the context window claude reported for one model. It is not an Event.

claude's entry also carries maxOutputTokens, which nothing reads, and canonicalModel, which only some claude versions send (present at v2.1.220 and v2.1.239, absent at v2.1.143, v2.1.158 and v2.1.199). Neither is on the producer's decode target (streamsup's resultLine), so no consumer can come to depend on them.

type PermissionOption

type PermissionOption struct {
	ID    string               // referenced by PermissionResponse.OptionID
	Label string               // human-readable ("Yes", "No, and don't ask again")
	Kind  PermissionOptionKind // the ACP semantic kind
}

PermissionOption is one selectable answer in a PermissionRequest. Order within PermissionRequest.Options is significant — the consumer renders in order.

type PermissionOptionKind

type PermissionOptionKind string

PermissionOptionKind is the ACP session/request_permission option-kind taxonomy.

const (
	PermissionOptionKindAllowOnce    PermissionOptionKind = "allow_once"
	PermissionOptionKindAllowAlways  PermissionOptionKind = "allow_always"
	PermissionOptionKindRejectOnce   PermissionOptionKind = "reject_once"
	PermissionOptionKindRejectAlways PermissionOptionKind = "reject_always"
)

func (PermissionOptionKind) Valid

func (k PermissionOptionKind) Valid() bool

Valid reports whether k is one of the ACP permission-option kinds.

type PermissionRequest

type PermissionRequest struct {
	RequestID  string             // correlates request <-> response
	ToolCallID string             // the tool call this gates; "" if not tool-triggered
	Title      string             // human-readable prompt text (e.g. "Do you want to proceed?")
	Options    []PermissionOption // ordered; the consumer renders + selects from these
}

PermissionRequest is an outbound Event: the daemon asks the consumer (phone / ACP client) to answer a permission modal, correlated to its inbound PermissionResponse by RequestID. ACP's session/request_permission (#600) maps onto this same shape, so it is adapter-neutral, not mobile-specific.

It references the gating tool call by ToolCallID — the same by-id reference style ToolUpdate uses — rather than re-embedding tool details; the consumer already saw the matching ToolStart in the stream. ToolCallID is empty when a permission prompt has no backing tool call.

func NewPermissionRequest

func NewPermissionRequest(requestID, toolCallID, title string, options []PermissionOption) PermissionRequest

NewPermissionRequest assembles a PermissionRequest from its parts. It does NOT validate — constructing an invalid one (e.g. an option with an out-of-taxonomy Kind) is allowed and caught downstream via PermissionOptionKind.Valid(), matching the package's construct-then-validate-downstream convention.

type PermissionResponse

type PermissionResponse struct {
	RequestID string // the PermissionRequest this answers
	OptionID  string // the selected PermissionOption.ID; "" when Cancelled
	Cancelled bool   // true => the consumer dismissed the modal without selecting
}

PermissionResponse is an inbound command answering a PermissionRequest, matched by RequestID. Exactly one outcome is meaningful: either OptionID names the selected PermissionOption.ID, or Cancelled is true (the consumer dismissed the modal without selecting). The package does not enforce that exclusivity — validation is the inbound parser's job, consistent with the package's stance.

type PromptSuggestion added in v0.34.0

type PromptSuggestion struct {
	Text string
}

PromptSuggestion is claude's own suggested next prompt, read off a top-level prompt_suggestion line that claude emits after the turn's result when prompt suggestions are enabled. Reusing it saves the daemon a model call of its own.

Text is claude-authored and untrusted. The producer checks its shape (a non-blank string of at most maxPromptSuggestionBytes valid UTF-8 bytes with no line break) and carries it verbatim, with no trimming or repair. It does not vet the content: control characters and bidi marks other than line breaks pass through, and the text is model output, not the operator's words.

It opens and closes no turn and names none: claude's uuid and session_id on the line establish no daemon turn, so neither is carried.

type RateLimited added in v0.16.0

type RateLimited struct {
	// Status is claude's rate_limit_info.status, verbatim and never empty (the
	// gate does not emit on an empty status). Beyond the benign value
	// (streamsup's benignRateLimitStatus) the set is almost entirely unmeasured:
	// one non-benign value is on record, "allowed_warning", the weekly warning
	// band, and no capture of a limit actually in force exists. An event is not
	// proof that anything was blocked.
	//
	// The benign value is the one a consumer compares against, as the falling
	// edge's discriminator. Every other value is an opaque label to render, never
	// to branch on; a plain string keeps the rest of the set measurable instead
	// of inventing an enum. claude reports one window per line and chooses which,
	// so a benign reading means claude reported no non-benign window, not that
	// the warned limit lifted.
	Status string
	// LimitType is which limit the reading is about: claude's rateLimitType
	// ("five_hour" and "seven_day" observed). Renamed because RateLimitType inside
	// RateLimited stutters; its TruncatedFields name is "limit_type". A plain
	// string for Status's reason.
	//
	// The falling edge names a different limit than the warning it clears: every
	// benign reading on record says "five_hour" and every warning "seven_day".
	// Key a banner on the conversation, not on this value.
	LimitType string
	// ResetsAt is when claude says the limit lifts, in Unix seconds; 0 when
	// claude did not report it, and the event still fires. It is claude's
	// unvalidated number: it need not lie in the future or in any sane range, so
	// range-check it before formatting it as a date. An int64, not a time.Time,
	// which would claim the bytes are a valid instant and add a second absent
	// value.
	ResetsAt int64
	// Utilization is how much of the window claude says is spent, as claude's own
	// number; nil when claude reported none, and the event still fires.
	//
	// A pointer, unlike ResetsAt, because 0 here is a meaningful reading (a fresh
	// window), and folding absence into it would show an untouched quota as an
	// exhausted one. Every committed benign record omits it, so the falling edge
	// usually carries nil and a consumer must degrade rather than render a number.
	//
	// Unvalidated like ResetsAt: not guaranteed to lie in 0..1 or any sane range
	// (0.94 is the one observed value), so range-check it before scaling a
	// progress bar by it. A float64 needs no cap. Like the whole variant it is a
	// report, not a threshold: never throttle or pause on it.
	Utilization *float64
	// TruncatedFields names cut fields ("status", "limit_type") per
	// BackgroundTaskStarted.TruncatedFields. The numeric fields cannot be cut.
	TruncatedFields []string
}

RateLimited reports a reading of claude's usage-limit window that the producer's gate judged worth repeating. It maps claude's top-level rate_limit_event line, which claude emits once per run whatever the window's state, so the gate drops the routine benign reading and fires on a change: the window entering a non-benign state, and its return to the benign state after one.

So a RateLimited may carry the benign status. That is the falling edge, and the benign Status is its discriminator; no other field or variant marks it. The edge is per-parser state, so a consumer must not rely on one arriving: a session rotation starts a fresh parser, and a warning raised before it is never cleared by an event.

It is a report, never a control input. Nothing in the daemon may key a behaviour on it (no backoff, throttle, retry, turn suspension or reconnect delay): every field is claude-authored and crosses the subprocess trust boundary, and display is its only use downstream. Making the daemon act on a rate limit means redoing that trust analysis.

claude's four overage keys are not carried: overageStatus and isUsingOverage are org-policy detail nothing reads, and overageResetsAt and overageDisabledReason vary by claude version. Both string fields are bounded at construction by streamsup's maxRateLimitField.

type SessionFacts added in v0.16.0

type SessionFacts struct {
	// ClaudeCodeVersion is claude's own build string, verbatim per
	// ModelAnnounced.Model's rule: not normalised or parsed into a semver triple.
	// A consumer comparing versions does its own parsing, since a build carrying
	// a suffix, date or channel name would force a parsing producer to invent an
	// answer.
	ClaudeCodeVersion string
	// PermissionMode is the posture claude says the child runs under ("default",
	// "bypassPermissions", "plan" and whatever claude adds), verbatim per
	// ModelAnnounced.Model's rule.
	//
	// An open set on purpose. streamsup's permissionModeAllowed bounds the mode
	// the daemon may ask for, where refusing an unknown value is right. This is
	// claude's report of what it is running, and an allow-list would drop the one
	// report an operator most needs: a mode the daemon has not heard of.
	//
	// It is a claim, not an authorization decision: a buggy or compromised claude
	// can report "default" under any posture. Nothing in the daemon gates on it
	// or feeds it back into a spawn or control request.
	PermissionMode string
	// TruncatedFields names cut fields ("claude_code_version",
	// "permission_mode") per BackgroundTaskStarted.TruncatedFields. A slice rather
	// than ModelAnnounced's bool because there are two candidate fields.
	TruncatedFields []string
}

SessionFacts reports claude's own build and the permission posture it runs under, two more keys of the system/init line ModelAnnounced maps. As with the model, the daemon knows what it asked for and only claude knows what it got, so an unexpected posture is visible here.

"Session" names the child run these facts describe; the event carries no session identity. The name matches the wire type, which follows this package's variant names (internal/protocol's codes doc states the rule).

A separate variant rather than a widened ModelAnnounced: widening a shipped payload is a wire-compatibility change, and the facts have different consumers. A client renders the model every turn, while a version and a posture are what an operator checks when something looks wrong.

Per line, not per session, with ModelAnnounced's hazard: one per turn, no dedup. The values ordinarily agree; a consumer wanting change detection does it itself. The producer emits when either field is present, so either may be empty. It opens and closes no turn.

There is no effort field: no init line carries an effort key even with an effort set on the argv and in band, which streamsup's effortInitPins test pins. The host paths on the init line are excluded as for ModelAnnounced, and MCP server status is MCPStatus's.

Both strings are bounded at construction (streamsup's maxClaudeVersionField and maxPermissionModeField) and valid UTF-8, nothing more: a client rendering either owes the sanitization, as for ModelAnnounced.Model.

type SlashCommand added in v0.16.0

type SlashCommand struct {
	// Name is claude's command name, verbatim per ModelAnnounced.Model's rule: no
	// lowercasing, canonicalisation or prefix stripping, and no leading "/" added
	// or removed. It is not an identifier: one captured name is
	// __remote-workflow, so assume no charset.
	Name string
	// ArgumentHint is claude's synopsis of what the command takes after its
	// name, verbatim. An empty hint is the ordinary case, not missing data: 33 of
	// the capture's 51 entries carry "" and none omits the key. It is never sent
	// back, and 13 of the 18 non-empty hints carry [ and ] (ten carry < and >), so
	// render it as syntax-shaped text, not a slug.
	ArgumentHint string
	// Description is claude's description of the command, verbatim and with no
	// newline stripping: it is the one string here a captured value carries
	// newlines in. Multi-line prose, often non-ASCII (14 of 51 captured), not a
	// label. No second copy exists on any lane, so a cut is not recoverable.
	Description string
	// Aliases are claude's alternative names for the command, verbatim and in
	// claude's order: no lowercasing, trimming, deduplication, sorting or "/"
	// changes. An alias is not an entry: the capture's clear carries reset and
	// new, which belong to clear and are never expanded into commands claude did
	// not publish. Aliases make a consumer's match correct, since a menu entry
	// may be an alias (the desktop Actions menu's reset) rather than a name.
	//
	// An absent key, a JSON null and a published [] are one reading, nil. None of
	// the capture's 51 entries carries [], and protocol.SlashCommand.MarshalJSON
	// publishes [] for both anyway, so a kept distinction would be one no
	// consumer could act on.
	//
	// The only field whose list a cut can shorten: see SlashCommandList for the
	// two caps. A cut on either reports once as "aliases".
	Aliases []string
	// TruncatedFields names this entry's cut fields ("name", "argument_hint",
	// "description", "aliases") per BackgroundTaskStarted.TruncatedFields. They
	// match protocol.SlashCommand.TruncatedFields' wire names, so mapping is a
	// copy. "aliases" covers a cut alias or a shortened list, at most once, and
	// does not say which. A name for a field this type does not declare must
	// never appear.
	TruncatedFields []string
}

SlashCommand is one entry of a SlashCommandList, not an Event. Its five fields are protocol.SlashCommand's, in that type's declaration order, so the mapping onto the wire is a field-for-field copy; keep the two orders matched.

Every string here is covered by SlashCommandList's security paragraph.

type SlashCommandList added in v0.16.0

type SlashCommandList struct {
	// Commands is the inventory in claude's order; no ranking is invented. The
	// producer does not emit an empty list, because its decode cannot tell a
	// published [] from an absent key. Truncated from the tail past
	// maxSlashCommandListEntries.
	Commands []SlashCommand
	// DroppedCommands counts entries the producer cut past its entry cap; 0 when
	// none. len(Commands) + DroppedCommands is the list's size here. It reports
	// here rather than in a top-level TruncatedFields for
	// BackgroundTaskRoster.DroppedTasks' reason. It is the one daemon-derived
	// field on this type, so the only one a consumer may trust without the render
	// boundary above.
	//
	// The entry cap alone does not bound the wire frame: 128 entries at the
	// 1280-byte per-entry worst case pass the 65519-byte v2 application-envelope
	// cap. turnbridge's maxSlashCommandListBytes does, at mapping, and adds its
	// own drops to protocol.SlashCommandListPayload.DroppedCommands. So the wire
	// count is the size after both cuts, while this one counts the producer's cut
	// alone.
	DroppedCommands int
}

SlashCommandList is claude's inventory of slash commands for this session in this working directory: the commands array of the same initialize reply ModelList comes from. A command defined in a repository exists for that repository's sessions only, and the count varies by workspace and claude version, so a client must not cache one list across working directories.

streamsup's commandEntryLine decodes the entries, and emitSlashCommandList caps, constructs and emits the list. turnbridge.MapEvent maps it onto protocol.SlashCommandListPayload and interactiveTurnEmitterV2.Handle emits it. It opens and closes no turn and is not per turn: one initialize exchange per child produces one.

Every dimension is bounded at construction: each entry's text by streamsup's maxSlashCommandName, maxSlashCommandArgumentHint, maxSlashCommandDescription and maxSlashCommandAlias (reported per entry), each entry's alias count by maxSlashCommandAliasCount, and the entry count by maxSlashCommandListEntries (reported as DroppedCommands). This type declares no maximum of its own, so each limit is decided in one place.

Security: every string is workspace-authored, written by whoever wrote the repository, which is lower trust than claude's own strings. Render them as inert text, never into an HTML sink, an attribute or a URL. The daemon bounds but does not sanitize them, so the client's render boundary owes the sanitization. A client sending a Name back as message text is the feature, but publishing a name does not make it trusted: nothing in the daemon may treat a value here as a command vocabulary, and no field may reach a child as an argv element.

type Stall

type Stall struct{}

Stall is an internal-only onset marker that a child stalled: no payload and no clearing edge. The mobile adapter sends it as the wire "stall" event; it has no ACP equivalent. No producer constructs it today.

type TerminalContent

type TerminalContent struct {
	TerminalID string
}

TerminalContent references, by id, a terminal a tool is driving.

type TextChunk

type TextChunk struct {
	MessageID        string
	ParentToolCallID string
	Text             string
}

TextChunk is incremental assistant text, grouped by message. ParentToolCallID names the Agent/Task call that spawned the subagent producing the text, or is empty on the main conversation; it follows ToolStart.ParentToolCallID's rules.

type TextContent

type TextContent struct {
	Text string
}

TextContent is plain text tool output.

type ThinkingProgress added in v0.16.0

type ThinkingProgress struct {
	// ParentToolCallID names the spawning Agent/Task call, or is empty for
	// main-thread thinking.
	ParentToolCallID string
	// EstimatedTokens is claude's estimate of the tokens spent thinking as of
	// the emitting line. It is cumulative within one inference request, not a
	// turn, and restarts near zero at each request boundary (the captured turn
	// has four restarts). Treat it as a progress reading, never a turn total, and
	// never expect the difference of two readings to be non-negative.
	EstimatedTokens int
	// EstimatedTokensDelta is claude's per-line increment from the emitting line.
	// Because the rate bound drops most lines, received deltas do not sum to the
	// turn's total (674 tokens arrive as 243 across 8 events on the capture), and
	// nothing reports the residue. It is a rate reading, not an accumulator input.
	EstimatedTokensDelta int
}

ThinkingProgress reports that claude is reasoning, and roughly how much. It maps claude's system/thinking_tokens line, claude's only mid-turn proof of life on stream-json: during a long assistant turn nothing else crosses stdout, so without it a client cannot tell a slow answer from a wedged one. It carries none of the reasoning's content; ThoughtChunk does.

Rate: the producer emits at most one event per streamsup's minThinkingTokensPerEvent tokens of accumulated delta (33 lines become 8 events on the committed capture). Events do not enumerate claude's lines, and a gap between two does not mean thinking stopped.

It neither masks nor triggers stall detection: streamsup's Watchdog reads raw stdout, counts every line as activity and never reads parser events.

Only a main-thread reading (empty ParentToolCallID, per ToolStart's rules) opens the daemon's turn and is published; a parent-attributed reading is used for classification only. The numeric fields need no cap, so there is no TruncatedFields.

type ThoughtChunk

type ThoughtChunk struct {
	MessageID string
	// ParentToolCallID names the spawning Agent/Task call, or is empty for
	// main-thread thinking.
	ParentToolCallID string
	Text             string
}

ThoughtChunk is streaming reasoning ("thinking") text, grouped by message.

type ToolCallDenied added in v0.16.0

type ToolCallDenied struct {
	// ToolName is claude's name for the refused tool ("Bash" in all seven
	// captured lines): an open set carried verbatim, on TurnEnd.Outcome's rule.
	// Dropped rather than cut, since a consumer switches on it.
	ToolName string
	// ToolCallID is the refused call: claude's tool_use_id, under the name
	// ToolStart and ToolUpdate use, so a consumer joins the three directly. All
	// seven captured denials share their id with the tool_use before and the
	// tool_result after. Dropped rather than cut, because a cut join key matches
	// nothing while looking real (ModelWindow.ModelID's rule); the older
	// BackgroundTaskStarted.ToolCallID cuts the same identifier instead.
	ToolCallID string
	// Message is claude's rejection text, the prose it also writes into the
	// tool_result. Every captured line is a sandbox refusal naming the absolute
	// host paths of the session's allowed working directories. Cut rather than
	// dropped, since a cut sentence still reads as what it is.
	//
	// Security: claude-authored, bounded and not sanitized. A rule-based denial
	// may quote the refused command line. Safe to render as text, never to
	// execute or re-shell.
	Message string
	// DecisionReasonType is claude's word for what denied the call: "classifier",
	// "asyncAgent", "mode" and "rule" are documented (SDKPermissionDeniedMessage
	// in @anthropic-ai/claude-agent-sdk@0.3.263). Absent in all seven captured
	// lines at claude 2.1.239, as
	// TestParser_DenialCaptureYieldsEmptyDecisionReasons pins; decoded anyway
	// because the consumer wants it. Dropped rather than cut, on ToolName's rule.
	DecisionReasonType string
	// DecisionReason is claude's free-form explanation, absent in all seven
	// captured lines. Cut, reported and treated as Message is.
	DecisionReason string
	// TruncatedFields names cut fields ("message", "decision_reason") per
	// BackgroundTaskStarted.TruncatedFields.
	TruncatedFields []string
	// DroppedFields names the fields the producer emptied for exceeding their
	// caps ("tool_name", "tool_call_id", "decision_reason_type"), in declaration
	// order by daemon name; nil when nothing was dropped. Three fields here can
	// drop, so without it an empty value could not be told from one claude never
	// sent. A field named here was emptied by the daemon; an empty field named in
	// neither report was empty as claude sent it.
	DroppedFields []string
}

ToolCallDenied reports that claude refused a tool call it was about to make. It maps claude's system/permission_denied line. Without it a client cannot tell a blocked call from one that ran and failed, because claude also writes the rejection text into an is_error tool_result. The line does not arrive in the daemon's production launch posture, so streamsup also recovers one marker per denied id no line announced from the `result` line's permission_denials, carrying ToolName and ToolCallID only.

The name is deliberately not PermissionDenied, which would read as the negative answer of the PermissionRequest/PermissionResponse modal pair; this event reports claude refusing a call, whatever decided it. It opens and closes no turn.

Every field is claude's, and so is the fact of the denial: a mistaken or fabricated line can name a call that ran and succeeded. The daemon does not verify the id against calls it saw, since that needs parser state and would drop a denial whose call preceded a session rotation. Instead the join is the client's (an id matching no seen call renders unattributed), and nothing in the daemon acts on any field.

Every string is bounded at construction (streamsup's maxTaskFieldID and maxDenialProse). Tokens and ids are dropped past the cap and reported in DroppedFields; prose is cut and reported in TruncatedFields.

type ToolContent

type ToolContent interface {
	// contains filtered or unexported methods
}

ToolContent is the sealed sum type a ToolUpdate carries: text, diff, or terminal. A consumer recovers the concrete shape with a type switch. A nil ToolContent is a valid "no content change" (status-only ToolUpdate), not an error. The unexported marker keeps the variant set closed to this package.

type ToolKind

type ToolKind string

ToolKind is the ACP tool-call kind taxonomy.

const (
	ToolKindRead    ToolKind = "read"
	ToolKindEdit    ToolKind = "edit"
	ToolKindDelete  ToolKind = "delete"
	ToolKindMove    ToolKind = "move"
	ToolKindSearch  ToolKind = "search"
	ToolKindExecute ToolKind = "execute"
	ToolKindThink   ToolKind = "think"
	ToolKindFetch   ToolKind = "fetch"
	ToolKindOther   ToolKind = "other"
)

func (ToolKind) Valid

func (k ToolKind) Valid() bool

Valid reports whether k is one of the ACP tool kinds. The seam consumer (#608/#607) calls this to reject an out-of-taxonomy value.

type ToolProgress added in v0.16.0

type ToolProgress struct {
	ToolCallID     string
	ElapsedSeconds int
}

ToolProgress reports the elapsed time of a tool call that ToolStart already announced. It maps claude's top-level tool_progress heartbeat and, unlike a ToolUpdate from streamsup, is a non-terminal reading that may repeat until the tool_result closes the row.

ToolCallID is read from the heartbeat's parent_tool_use_id, the handle ToolStart published, not from its synthetic per-tick tool_use_id. The producer requires a non-empty JSON string of at most streamsup's maxTaskFieldID and drops the whole event otherwise; it never cuts the id.

ElapsedSeconds is claude's signed integer reading, verbatim. Zero means claude omitted it or reported zero; a negative value stays observable. The daemon infers no cadence, accumulates nothing and keeps no per-call state.

The heartbeat's tool_name is not carried: ToolStart already published it.

type ToolStart

type ToolStart struct {
	ToolCallID       string
	ParentToolCallID string
	Title            string
	Kind             ToolKind
	RawInput         json.RawMessage
	Locations        []Location
}

ToolStart announces a new tool invocation.

RawInput is opaque tool input, carried as json.RawMessage so nothing on this path is forced to parse it; consumers decode it on their own terms.

ParentToolCallID names the Agent/Task call that spawned the subagent making this call, or is empty on the main conversation. It is byte-identical to the parent's own ToolCallID, so a consumer groups children by joining on ids; a call from a nested subagent names the inner Agent call, and following ids rebuilds the tree. Empty has one meaning, "main thread": streamsup's parentToolUseID drops, never cuts, an unreadable value or one past maxTaskFieldID, because a cut join key matches no call while still looking like one. A dropped value degrades to top-level rendering, never to a wrong parent.

type ToolStatus

type ToolStatus string

ToolStatus is the ACP tool-call status taxonomy.

const (
	ToolStatusPending    ToolStatus = "pending"
	ToolStatusInProgress ToolStatus = "in_progress"
	ToolStatusCompleted  ToolStatus = "completed"
	ToolStatusFailed     ToolStatus = "failed"
)

func (ToolStatus) Valid

func (s ToolStatus) Valid() bool

Valid reports whether s is one of the ACP tool statuses.

type ToolUpdate

type ToolUpdate struct {
	ToolCallID       string
	ParentToolCallID string
	Status           ToolStatus
	Content          ToolContent
	ResultDetail     string
}

ToolUpdate carries changed fields of an existing tool call. Content may be nil for a status-only update. Content carries claude's own bytes and is capped downstream (turnbridge's maxResultSummaryRunes).

ResultDetail is a short daemon-composed précis of an edit's or write's outcome ("+10 −3", "created · 54 lines"), built by streamsup's toolResultDetail from the tool_use_result sidecar claude writes beside each result. Reads, shell, search and unrecognised shapes send "". It holds no claude-supplied byte: only digits, spaces, ASCII letters and the separators U+2212 MINUS SIGN and U+00B7 MIDDLE DOT, with length bounded by int64's range. Render it verbatim and never parse it; the unit words are in the string so a client need not switch on a tool name.

ParentToolCallID is ToolStart's field with ToolStart's meaning, read off the `user` line this update was mapped from rather than copied from the ToolStart: the parser holds no cross-line state for it, so the two agreeing is a fact about claude's wire.

type TurnEnd

type TurnEnd struct {
	Reason TurnEndReason
	// ModelWindows is claude's reported context window for each model the turn
	// touched, one entry per model id claude used, sorted by ModelID. claude
	// sends a JSON object, so the sort is the daemon's; it makes which entries
	// survive the count cap reproducible.
	//
	// Every entry carries a usable window: the producer drops an entry whose
	// contextWindow is absent, zero or negative. Two entries need not mean two
	// models: the captures show a helper model beside the session's own, and
	// alias pairs naming one model twice (claude-haiku-4-5 and
	// claude-haiku-4-5-20251001), so the list is carried whole and keyed by
	// claude's id. An absent, null, empty or undecodable modelUsage, and a map
	// whose every entry was dropped, all read as nil.
	//
	// Bounded at construction in both dimensions: entry count by streamsup's
	// maxModelWindowEntries, id length by maxModelWindowID.
	ModelWindows []ModelWindow
	// DroppedModelWindows counts entries claude sent that this event does not
	// carry, for any cause (unusable window, over-long id, count cap); 0 when
	// none. len(ModelWindows) + DroppedModelWindows is the size of claude's map.
	// Every bound here drops rather than truncates, so one daemon-derived counter
	// is enough.
	DroppedModelWindows int
	// Outcome is the subtype on claude's `result` line: how the turn stopped,
	// where Reason says only whether it was cancelled. Observed values are
	// success, error_during_execution, error_max_turns, error_max_budget_usd and
	// error_max_structured_output_retries. It is an open set carried verbatim, and
	// is not claude's `stop_reason` key, which the daemon does not forward.
	//
	// Empty means absent or over cap: streamsup's maxTurnEndStopField drops an
	// over-long value rather than cutting it, because a cut token matches nothing
	// a consumer could act on.
	//
	// Security: claude-authored, bounded and not sanitized. It reaches clients, so
	// the client's render boundary owes control-character and escape stripping;
	// see docs/protocol-mobile.md § turn_end.
	Outcome string
	// IsError is claude's is_error flag off the same line, false when absent. It
	// is not derived from Outcome and must not be: claude sends subtype success
	// with is_error true when a turn ends on an API error (a context overflow is
	// the documented case).
	IsError bool
	// TerminalReason is claude's terminal_reason, the finer-grained cause beside
	// the subtype (max_turns, budget_exhausted, prompt_too_long, hook_stopped,
	// completed, and more: claude documents nineteen and does not close the
	// list). It is what makes a context overflow legible, since that subtype is
	// success. Outcome's rules apply: open set, verbatim, empty when absent or
	// over maxTurnEndStopField, untrusted.
	TerminalReason string
	// ErrorCategory is the API error a wrapper-level `error` key reported on an
	// `assistant` line in this turn (a sibling of `message`, never a content
	// block). Documented values are authentication_failed, oauth_org_not_allowed,
	// account_on_hold, billing_error, rate_limit, overloaded, invalid_request,
	// model_not_found, server_error, max_output_tokens and unknown. Outcome's
	// rules apply.
	//
	// It is claude's report, not the daemon's finding, and several values name an
	// account state rather than a turn state. Attribute it to claude wherever it
	// is shown; never present it as daemon chrome. Nothing in the daemon acts on
	// it (no retry, backoff, teardown or routing); making it an actuator needs a
	// security review.
	ErrorCategory string
	// DurationMS is how long this turn took, in milliseconds, per the `result`
	// line. Per turn, not a running total: it falls between turns in 13 of the
	// 21 multi-turn captures under internal/e2e/realclaude/testdata.
	DurationMS int
	// DurationAPIMS is claude's duration_api_ms for the session so far: a running
	// total, not this turn's API time. It exceeds DurationMS on 53 of 57 observed
	// result lines, including the first line of 19 of the 21 multi-turn captures,
	// so differencing consecutive turns does not recover a per-turn value either.
	// The daemon neither differences it nor remembers earlier lines.
	DurationAPIMS int
	// NumTurns is claude's num_turns for this turn: model round-trips, not a count
	// of session turns. Per turn, like DurationMS.
	NumTurns int
	// CostUSDTotal is claude's total_cost_usd: what the session has cost so far,
	// in US dollars, a running total like DurationAPIMS. Spelled cost_usd_total
	// on the wire. It is claude's estimate, not a billing statement; the daemon
	// neither computes nor verifies it.
	CostUSDTotal float64
	// InputTokens, OutputTokens, CacheReadTokens and CacheCreationTokens are the
	// four counts in the result line's usage object for this turn. InputTokens is
	// uncached input only and the two cache counts are the cached-input parts, so
	// InputTokens + OutputTokens is not the turn's total.
	InputTokens         int
	OutputTokens        int
	CacheReadTokens     int
	CacheCreationTokens int
}

TurnEnd marks the end of a claude turn. Every field except ErrorCategory is read off claude's `result` line; ErrorCategory comes from an `assistant` line earlier in the same turn, which is why streamsup's Parser holds it across lines (see that type's doc).

Two classifications ride this variant and are never reconciled. Reason is the daemon's two-value reading (streamsup's resultTurnEndReason); Outcome is claude's own token for the same stop. A turn that hit --max-turns is end_turn/error_max_turns and both halves are true; a consumer that prefers one makes a truncated run read as a finished answer. ACP models end-of-turn as session/prompt's stopReason return, not an event; converting back is the ACP adapter's job.

The window fields ride here because claude reports them on the `result` line that is the turn boundary. They are not published: turnbridge.MapEvent builds protocol.TurnEndPayload field by field and names every field here except ModelWindows and DroppedModelWindows.

TurnEnd holds a slice, so it is not comparable: == on two Event values that both hold a TurnEnd panics.

Background: turnevent-package-outbound-event-variants.md and streamsup-package-result-stop-shape-second-decode-target-and-dr.md.

type TurnEndReason

type TurnEndReason string

TurnEndReason is the ACP turn stop-reason taxonomy.

const (
	TurnEndReasonEndTurn         TurnEndReason = "end_turn"
	TurnEndReasonMaxTokens       TurnEndReason = "max_tokens"
	TurnEndReasonMaxTurnRequests TurnEndReason = "max_turn_requests"
	TurnEndReasonRefusal         TurnEndReason = "refusal"
	TurnEndReasonCancelled       TurnEndReason = "cancelled"
)

func (TurnEndReason) Valid

func (r TurnEndReason) Valid() bool

Valid reports whether r is one of the ACP turn-end reasons.

type Unrecognized added in v0.16.0

type Unrecognized struct {
	// Site is where the drop happened.
	Site UnrecognizedSite
	// Kind is the message or block `type` that had no mapping. Empty when Site
	// is UnrecognizedUndecodable.
	Kind string
	// Raw is the offending JSON, already cut to the producer's
	// maxUnrecognizedRaw.
	Raw string
	// Truncated reports whether Raw was cut.
	Truncated bool
}

Unrecognized is a diagnostic marker: a producer met a payload it has no mapping for and dropped it. It exists so unknown claude or Codex output is visible when it arrives, not lost in a debug log production does not print.

It is not the tolerate-and-drop path. Line types on the measured known-ignored list (streamsup's ignoredLineTypes) stay silent, and the system subtypes streamsup maps (emitSystemSubtype) become their own variants; only output outside both sets lands here. A row per turn would make the signal noise, so the known-ignored list is the design. These are prose pointers because turnevent must not import streamsup.

Raw is a plain string, not json.RawMessage, because the producer truncates it at construction and a truncated blob is no longer valid JSON.

type UnrecognizedSite added in v0.16.0

type UnrecognizedSite string

UnrecognizedSite names where in the producer's mapping an unmapped payload was found. String-backed so the value crosses the wire unchanged.

const (
	// UnrecognizedLineType is a top-level stream-json line whose `type` is
	// neither mapped nor on the measured known-ignored list.
	UnrecognizedLineType UnrecognizedSite = "line_type"
	// UnrecognizedAssistantBlock is an assistant message content block whose
	// `type` is not text, thinking, or tool_use.
	UnrecognizedAssistantBlock UnrecognizedSite = "assistant_block"
	// UnrecognizedUserBlock is a user message content block whose `type` is not
	// tool_result.
	UnrecognizedUserBlock UnrecognizedSite = "user_block"
	// UnrecognizedUndecodable is a line or block that failed to JSON-decode at
	// all. Kind is empty for this site: there is no type to report.
	UnrecognizedUndecodable UnrecognizedSite = "undecodable"
	// UnrecognizedCodexMethod is a Codex app-server notification whose method
	// codexsup's translator neither maps nor ignores. Kind is the method.
	UnrecognizedCodexMethod UnrecognizedSite = "codex_method"
	// UnrecognizedCodexItem is a Codex thread item whose type the translator
	// neither maps nor ignores. Kind is the item type.
	UnrecognizedCodexItem UnrecognizedSite = "codex_item"
)

type UserEcho added in v0.31.0

type UserEcho struct {
	TextSHA256 [32]byte
}

UserEcho is claude replaying a user message at the point it read it, under --replay-user-messages: every turn's opening message, and a message written into a running turn, right after the tool result it followed. The daemon matches the digest against what it wrote to place the operator's own message push.

It carries only the SHA-256 of the echoed text, never the text. That text is the delivery payload, which for an attachment-bearing message names on-host paths, so no consumer of this stream can put it on the wire or in a log. It opens and closes no turn, and no client frame is built from it.

Jump to

Keyboard shortcuts

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