protocol

package
v0.41.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 12 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 protocol declares the wire-format types for pyrycode's mobile WebSocket protocol v1. The package is pure data: no I/O, no socket handling, no context plumbing. Consumers (internal/relay-client, internal/dispatch, future cmd/pyry-relay) marshal/unmarshal these types against the wire and dispatch on Envelope.Type.

The single source of truth for field names, optionality, and wire semantics is docs/protocol-mobile.md. When that document changes, this package changes; the test fixtures under testdata/ pin the round-trip shape.

Index

Constants

View Source
const (
	// MaxAttachmentChunkBytes bounds the RAW, pre-base64 bytes of one chunk's
	// Data so the marshalled application envelope stays under the v2
	// application-envelope cap of 65519 B (docs/protocol-mobile.md
	// § Application-envelope size cap: the 65535-byte Noise transport message
	// minus the 16-byte AEAD tag). The unit is raw bytes of Data — not base64
	// characters, not payload bytes, not envelope bytes — and no other reading
	// composes with Size, which is a raw file length.
	//
	// The arithmetic, budgeted against 65519 B. Every metadata figure is its
	// bound × 6, encoding/json's HTML-escaping ceiling: SetEscapeHTML is on by
	// default, so '<', '>', '&' and every control byte without a short escape
	// cost six bytes each (docs/protocol-mobile.md § tool_result works the same
	// multiplier out for a bounded text field, with a measured worst case).
	//
	//	envelope wrapper, every optional key present      194
	//	payload braces, keys, quotes, colons, commas      125
	//	index + total_chunks + size, 3 × 20                60
	//	sha256, 64 × 6                                    384
	//	attachment_id, MaxAttachmentIDBytes × 6           384
	//	conversation_id, MaxAttachmentIDBytes × 6         384
	//	filename, MaxAttachmentFilenameBytes × 6         1530
	//	mime_type, MaxAttachmentMimeTypeBytes × 6        1530
	//	                                        fixed    4591
	//	data at the bound, 4 × ceil(45000 / 3)          60000
	//	                                        frame   64591   (928 B spare)
	//
	// The structural row moved from 104 to 125 when #2142 added the ninth key, and
	// that 21 bytes is the part an arithmetic-by-analogy misses: a key costs its
	// own length (15) plus two quotes, a colon, a separating comma and the value's
	// two quotes, not only the value's bound. Adding a field to this frame moves
	// TWO rows.
	//
	// The ceiling is floor((65519 − 4591) / 4) × 3 = 45696. 45000 sits below it
	// and is a multiple of 3, so base64 lands on exactly 60000 bytes with no
	// padding and the table is checkable by eye. The invariant is ENFORCED by
	// TestAttachmentChunkPayload_FitV2EnvelopeCap, which measures the real total
	// rather than trusting this table; if that test ever fails, LOWER this
	// constant — never raise the cap. The conservative constant is the belt; the
	// deterministic per-frame test is the suspenders.
	//
	// Exported, where the sibling measurement constant maxV2AppEnvelope is
	// deliberately not: the envelope cap is enforced by the transport, so
	// exporting that one would imply an enforcement this package does not
	// perform. This bound is a producer-side contract every client must obey to
	// chunk a file at all, so it has to be readable from outside.
	//
	// THE CROSS-CHECK. AttachmentChunkPayload's NEVER ALLOCATE FROM A CLAIM
	// block cross-checks a claimed TotalChunks against a claimed Size using this
	// number, and the division is raw-over-raw: Size is raw file bytes and this
	// is raw chunk bytes, neither is base64 and neither is envelope bytes. Only
	// the EQUALITY form bounds TotalChunks from above. A maximum chunk size
	// yields a LOWER bound on the honest chunk count, so softening the rule to
	// TotalChunks >= ceil(Size / bound) for tolerance caps nothing and leaves
	// the make([][]byte, TotalChunks) allocation attack open.
	//
	// So the receiver requires TotalChunks == max(1, ceil(Size / bound)) — the
	// form docs/protocol-mobile.md § Attachments, "Chunking (the sender's
	// obligation)", already publishes as the sender's own, adopted here rather
	// than invented. The max(1, …) is what resolves Size == 0, where a bare
	// ceil(0 / bound) is 0 against the documented TotalChunks >= 1. The
	// equality's price is accepted rather than softened away: it mandates that
	// every chunk but the last carry exactly this many raw bytes, so a client
	// chunking at its own buffer size sends a conforming-looking transfer this
	// receiver refuses — and since the published contract already obliges that
	// stride, no client that reads the contract is broken by it.
	// attachments.CheckDeclaration is the enforcement point; this constant fixes
	// the units and enforces nothing itself.
	MaxAttachmentChunkBytes = 45000

	// MaxAttachmentIDBytes bounds BOTH id-shaped fields on this frame —
	// AttachmentID, and ConversationID since #2142, which obeys the same shape and
	// so gets no second constant of its own; RequestAttachmentPayload's block
	// records why minting one would enforce nothing while inviting the very
	// misreading the next paragraph warns about. It is a CEILING FOR THE CAP
	// ARITHMETIC, not the canonical shape, and the shape is no longer open:
	// attachments.EnsureDir picked conversations.ValidID's 36-character UUIDv4
	// form — the precedent AttachmentChunkPayload's doc had named — and #1895
	// publishes it in docs/protocol-mobile.md § Attachments as the rule a client
	// must obey. 64 sits comfortably above it, so this constant never constrained
	// the choice and does not describe it: a value passing this bound and failing
	// that shape is refused at storage.
	//
	// A LENGTH CEILING IS NOT A SAFETY PROPERTY. 64 bytes accommodates
	// "../../../../etc/passwd" several times over, so this constant does nothing
	// about the traversal hazard AttachmentChunkPayload's doc assigns to the
	// canonical-shape check that must run before the id becomes a path
	// component.
	MaxAttachmentIDBytes = 64

	// MaxAttachmentFilenameBytes bounds Filename at POSIX NAME_MAX, the
	// single-path-component limit on ext4 and APFS. Filename is documented as a
	// display string and a sanitiser input, never a path, so one component is
	// the right ceiling.
	MaxAttachmentFilenameBytes = 255

	// MaxAttachmentMimeTypeBytes bounds MimeType. RFC 6838 § 4.2 bounds a type
	// name and a subtype name at 127 characters each, so "type/subtype" is at
	// most 255.
	MaxAttachmentMimeTypeBytes = 255
)

Published byte bounds for one attachment_chunk frame (AttachmentChunkPayload below). All four are producer-side CONTRACTS WITH NO VALIDATOR in this package — the same posture the payload type itself ships with. Inbound enforcement is #1741's, outbound is #1897's and #2053's; nothing here checks anything, so a reader must not mistake a declared bound for a checked one, and that warning binds hardest on ConversationID (#2142), whose bound #1741 predates entirely. Its budget line below is arithmetic and nothing more. What makes a conversation id safe as a path component is the canonical-shape check, not this ceiling — attachments.EnsureDir already runs one on both components it joins and records that MaxAttachmentIDBytes "is not the defence and does not need to be consulted". What #2143 added is not that check but the registry validation in front of it, and the wiring that lets this field reach either; this ceiling is read on no inbound path even now.

FOUR FIELDS ARE BOUNDED BY THREE CONSTANTS, since MaxAttachmentIDBytes budgets both id-shaped fields (#2142). Count the constants here and the fields in the arithmetic below; the two numbers differ on purpose.

The metadata bounds count BYTES (len(s)), not runes. The escape ceiling the arithmetic below rests on composes directly on bytes — a one-byte input costs at most six on the wire, while a multi-byte rune is emitted raw at four bytes or fewer, so six-per-input-byte is the ceiling either way — and a filename's real-world limit is a byte limit too.

The metadata bounds matter for a reason the inbound leg does not show. A filename arrives attacker-chosen on the upload leg, is stored, and is echoed back daemon-authored on the retrieval leg: unbounded, a 100 KB filename makes the DAEMON's OWN outbound frame exceed the envelope cap and be dropped.

View Source
const (
	// ClaudeAccountKindMachineLogin means no source is configured: the daemon
	// uses the Claude login it inherited from the machine.
	ClaudeAccountKindMachineLogin = "machine_login"
	ClaudeAccountKindFile         = "file"
	ClaudeAccountKindOnePassword  = "1password"
	// ClaudeAccountKindOSKeychain is a keychain:<name> source (#2815): the
	// macOS Keychain or the Linux Secret Service.
	ClaudeAccountKindOSKeychain = "os_keychain"
)

ClaudeAccountPayload.Kind values. A client must accept an unknown kind.

View Source
const (
	ClaudeAccountStateReady         = "ready"
	ClaudeAccountStateFailed        = "failed"
	ClaudeAccountStateNotConfigured = "not_configured"
)

ClaudeAccountPayload.State values.

View Source
const (
	// ClaudeUsageStateNone means no reading has been stored since daemon start.
	ClaudeUsageStateNone = "none"
	// ClaudeUsageStateObserved means ObservedAt and at least one window are set.
	ClaudeUsageStateObserved = "observed"
)

ClaudeUsagePayload.State values. A client must accept an unknown state.

View Source
const (
	AppMobile  = "pyrycode-mobile"
	AppDesktop = "pyrycode-desktop"
)

App names a hello's client_version may carry (docs/protocol-mobile.md § hello, v2-specific note). A daemon holds a minimum version per app name; a well-formed version of any other app name parses, and no minimum applies to it.

View Source
const (
	TypeThreadItemAdded   = "thread_item_added"
	TypeThreadItemChanged = "thread_item_changed"
	TypeThreadTextAppend  = "thread_text_append"
	TypeThreadCatchUp     = "thread_catch_up"
	TypeThreadPage        = "thread_page"
	TypeThreadItems       = "thread_items"
	TypeThreadReset       = "thread_reset"
)

Thread vocabulary is v2; query handlers and wiring are declared separately. These types must stay out of the v1 inboundAppTypeSet.

View Source
const (
	TypeThreadReadToolBody = "thread_read_tool_body"
	TypeThreadToolBody     = "thread_tool_body"
	TypeThreadReadChildren = "thread_read_children"
	TypeThreadChildren     = "thread_children"
)

Expansion vocabulary is declared ahead of handlers and capability activation.

View Source
const (
	// Protocol errors.
	CodeProtocolUnknownType = "protocol.unknown_type"
	CodeProtocolMalformed   = "protocol.malformed"
	CodeProtocolUnsupported = "protocol.unsupported"

	// Auth errors.
	CodeAuthInvalidToken = "auth.invalid_token"
	CodeAuthTokenRevoked = "auth.token_revoked"

	// Server errors.
	CodeServerBinaryOffline = "server.binary_offline"
	CodeServerBinaryBusy    = "server.binary_busy"

	// Conversation errors.
	CodeConversationNotFound        = "conversation.not_found"
	CodeConversationAlreadyPromoted = "conversation.already_promoted"
	// CodeConversationNotPromoted is a non-retryable refusal to pin an
	// unpromoted conversation. Unpinning remains allowed.
	CodeConversationNotPromoted = "conversation.not_promoted"

	// Host system prompt storage failures are retryable. Malformed requests use
	// CodeProtocolMalformed (non-retryable).
	CodeHostSystemPromptUnavailable = "host_system_prompt.unavailable"

	// Message errors.
	CodeMessageTooLong = "message.too_long"

	// Relay errors.
	CodeRelayNoServer         = "relay.no_server"
	CodeRelayServerIDConflict = "relay.server_id_conflict"

	// Session errors.
	CodeSessionNotFound      = "session.not_found"
	CodeSessionBlocked       = "session.blocked"        // terminal give-up; not a retry hint (contrast server.binary_busy)
	CodeSessionChildCrashing = "session.child_crashing" // not terminal: claude keeps exiting at startup, the daemon is still restarting it and queued messages are kept

	// Attachment errors (docs/protocol-mobile.md § Attachments): the reject
	// vocabulary of the attachment frames and of send_message's attachment ids.
	//
	// attachment.not_found answers every request that yields no bytes: an unknown
	// id, a non-canonical id and an id resolving outside the named conversation's
	// directory alike, on retrieval and on a send_message whose attachment id does
	// not resolve under its own conversation. Distinct codes would make the verbs a
	// path-existence oracle, so the message stays static and, where a request names
	// several ids, MUST NOT say which one failed.
	//
	// The three retryable codes (too_many_uploads, storage_failed, stream_aborted)
	// mean retry after a backoff; an immediate resend is a hot loop.
	CodeAttachmentInvalidChunk    = "attachment.invalid_chunk"
	CodeAttachmentIntegrityFailed = "attachment.integrity_failed"
	CodeAttachmentTooManyUploads  = "attachment.too_many_uploads" // transient; clears when other uploads finish (contrast attachment.too_large)
	CodeAttachmentTooLarge        = "attachment.too_large"        // the whole transfer exceeds the receiver's per-upload bound; one oversize envelope is message.too_long
	CodeAttachmentStorageFailed   = "attachment.storage_failed"
	CodeAttachmentNotFound        = "attachment.not_found"
	CodeAttachmentStreamAborted   = "attachment.stream_aborted" // a TypeError correlated via in_reply_to, never a second attachment frame

	// Conversation-history errors (docs/protocol-mobile.md § Conversation
	// history). An unknown or non-canonical conversation_id is
	// CodeConversationNotFound: there is no second id to probe for, and
	// request_snapshot already answers an unknown conversation distinguishably.
	// history.invalid_cursor is one answer for a cursor that does not decode, was
	// minted for another conversation, or names a position not in this log; the
	// handler sees only history.ErrInvalidCursor and never echoes the cursor. Only
	// history.unavailable is retryable; the other three need a different request.
	CodeHistoryInvalidRequest  = "history.invalid_request"   // the payload did not decode; never an empty-but-successful request
	CodeHistoryInvalidPageSize = "history.invalid_page_size" // a negative limit; 0 is not a reject, it asks the daemon to choose
	CodeHistoryInvalidCursor   = "history.invalid_cursor"    // undecodable, foreign, or naming a position not in this log; one merged answer
	CodeHistoryUnavailable     = "history.unavailable"       // the log could not be read; the only retryable member of this group

	// Read-mark save error (docs/protocol-mobile.md § Marking a conversation
	// read). The advance could not be persisted, so the daemon reverted it and
	// pushed nothing; the same request can succeed once the registry saves again.
	CodeReadMarkUnavailable = "read_mark.unavailable" // retryable

	// On-demand model-list error (docs/protocol-mobile.md § Asking for a model
	// list on demand). The daemon hosts the conversation but has no menu: nothing
	// retained yet, or no model-list source wired. The causes are merged so the
	// reply reveals nothing about the host's configuration; an unhosted
	// conversation is CodeConversationNotFound (KnownConversation separates the
	// two). Retryable, since a child that has not answered initialize yet will.
	// This code, never an empty models array, is how the daemon says "no list":
	// turnevent.ModelList.Models is never empty.
	CodeModelListUnavailable = "model_list.unavailable" // the daemon hosts the conversation but has no vocabulary to answer with; retryable

	// MCP status error (docs/protocol-mobile.md § Asking for MCP status on
	// demand). Sent only after the membership check passes, when the hosted
	// conversation's resolver has no live result; the daemon never substitutes an
	// empty or retained status.
	CodeMCPStatusUnavailable = "mcp_status.unavailable" // hosted conversation has no current MCP status; retryable

	// MCP actuation error (docs/protocol-mobile.md § Actuating MCP servers on
	// demand). The one answer to every refused mcp_reconnect or mcp_toggle: an
	// unauthorized device, an unknown server, no live child and a declined
	// actuation alike. Splitting them would tell a device which MCP servers the
	// host runs and whether it is privileged; the daemon-side audit record keeps
	// the reasons apart. Never retryable, so the retry flag cannot re-split what
	// the code merges. It carries no server name and no claude-authored text; the
	// message is a constant in internal/relay.
	CodeMCPActuationRefused = "mcp_actuation.refused" // reconnect or toggle refused, reason deliberately merged; never retryable

	// Context-usage read error (docs/protocol-mobile.md § Asking for a context
	// usage reading on demand). The daemon hosts the conversation but has no
	// reading. streamsup's QueryContextUsage already collapses every such cause
	// (no session, no live child, a rotation, a failed write, a deadline, an
	// unusable payload) into one bool, and an unwired source merges in so the
	// host's configuration stays private. An unhosted conversation is
	// CodeConversationNotFound. Retryable; the resolver caches a refusal for its
	// short collapsing window, so a retry inside it gets the same answer. A
	// zero-valued ContextUsagePayload MUST NOT stand in for this code.
	CodeContextUsageUnavailable = "context_usage.unavailable" // the daemon hosts the conversation but has no reading to give; retryable

	// Workspace error (docs/protocol-mobile.md § Renaming a workspace).
	// rename_workspace names a workspace path, not a conversation, so this is not
	// CodeConversationNotFound. The refusal is also the workspace-label map's only
	// bound: a label can be stored only at a path that equals a stored
	// conversation's cwd. Not retryable; the message is static and never echoes
	// the path.
	CodeWorkspaceNotFound = "workspace.not_found"

	// Pairing-mint errors (docs/protocol-mobile.md § Minting a pairing from a
	// paired client). Neither is CodeAuthInvalidToken: the device has already
	// authenticated, and an auth code would wrongly invite it to re-pair.
	// pairing.not_permitted reports only that the asking device lacks the
	// remote-permissions flag and does not depend on device_name.
	// pairing.unavailable merges every host-side failure (a busy devices.json
	// lock, a registry read or write error, an RNG failure); the errors behind it
	// carry host paths and never reach the wire. A malformed request, including a
	// device_name over MaxDeviceNameBytes, is CodeProtocolMalformed.
	CodePairingNotPermitted = "pairing.not_permitted" // the device is authenticated but is not privileged to mint; permanent
	CodePairingUnavailable  = "pairing.unavailable"   // the mint could not be completed on the host; one merged, retryable answer

	// New-session workspace refusal (docs/protocol-mobile.md § New session). It
	// reports a rotation that succeeded: new_session rotated the conversation and
	// the successor came up, but re-confining the conversation's recorded
	// workspace at spawn time refused it (the folder was deleted or now points
	// outside $HOME). An error frame carries it so the refusal is correlated by
	// in_reply_to. It reveals nothing a client could not already derive, and every
	// inert arm of new_session stays silent, so the verb still cannot answer
	// "does this conversation exist?". Not retryable: the operator must repair or
	// re-point the folder. The conversation id travels in
	// ErrorPayload.ConversationID (a bare new_session names none); no part of the
	// path reaches the message, which is a constant in internal/relay, or a log.
	CodeNewSessionWorkspaceRefused = "new_session.workspace_refused" // the rotation completed; the recorded workspace was refused, so the successor stayed put

	// Client errors (docs/protocol-mobile.md § Compatibility). The hello's
	// client_version names an app build older than this host's minimum for that
	// app, or cannot be parsed once a minimum is set. Its own category: the fault
	// is the client build, not the protocol version or the token. Sent sealed,
	// after the Noise handshake and after the token check, so an unauthenticated
	// peer learns nothing of the version policy; the relay's
	// StatusClientUpdateRequired close follows it. Not retryable, and terminal for
	// this host only. The message is static; the minimum travels in
	// ErrorPayload.MinClientVersion.
	CodeClientUpdateRequired = "client.update_required" // the app build is older than this host's minimum; never retryable
)

Error codes: wire values for the "code" field of an ErrorPayload (docs/protocol-mobile.md § Error codes, which publishes each code's retryability). Names follow Code<Category><Reason> for the dotted category.reason string, grouped by category in spec-table order. The reasoning behind each group's merges and splits is in docs/knowledge/features/protocol-package-constants-codes-go-error-codes-21.md. Several codes merge causes on purpose, mostly so a reply discloses nothing about the host or about other ids; do not split one without reading its group's doc.

View Source
const (
	// Handshake and control.
	TypeHello    = "hello"
	TypeHelloAck = "hello_ack"
	TypeError    = "error"
	TypeAck      = "ack"

	// Messaging.
	TypeSendMessage = "send_message"
	TypeMessage     = "message"

	// Conversations.
	TypeListConversations   = "list_conversations"
	TypeConversations       = "conversations"
	TypeCreateConversation  = "create_conversation"
	TypeConversationCreated = "conversation_created"
	TypePromoteConversation = "promote_conversation"
	TypeConversationUpdated = "conversation_updated"
	// TypeRenameConversation is a phone → binary write verb that renames a
	// conversation and replies with conversation_updated.
	TypeRenameConversation = "rename_conversation"
	// TypeDeleteConversation is a phone → binary write verb that permanently
	// removes a conversation from the registry (archive_conversation is the
	// reversible path). It replies with conversation_deleted.
	TypeDeleteConversation = "delete_conversation"
	// TypeConversationDeleted is the binary → phone reply to
	// delete_conversation, correlated via in_reply_to. It carries only the
	// deleted conversation's id, since the record no longer exists.
	TypeConversationDeleted = "conversation_deleted"
	// TypeArchiveConversation is a phone → binary write verb that sets a
	// conversation's durable archived flag and replies with
	// conversation_updated. unarchive_conversation reverses it; both carry
	// ArchiveConversationPayload.
	TypeArchiveConversation = "archive_conversation"
	// TypeUnarchiveConversation is a phone → binary write verb that clears a
	// conversation's archived flag and replies with conversation_updated.
	TypeUnarchiveConversation = "unarchive_conversation"
	// TypeSetConversationMuted is a phone → binary write verb that sets or
	// clears a conversation's durable muted flag from the payload's required
	// muted bool. It replies with conversation_updated and pushes the same
	// record to every interactive conn, so other clients stop alerting without
	// re-listing.
	TypeSetConversationMuted = "set_conversation_muted"
	// TypeSetConversationPinned declares a phone-to-host pin/unpin request.
	// Production handling is pending #3538; replies reuse conversation_updated.
	TypeSetConversationPinned = "set_conversation_pinned"
	// TypeMarkConversationRead is a phone → binary write verb that raises a
	// conversation's host-local read mark (ReadUpTo) toward the payload's
	// required up_to, clamped to the newest durable history entry and never
	// lowered. Every success replies with conversation_updated; only an actual
	// advance also pushes it to every interactive conn.
	TypeMarkConversationRead = "mark_conversation_read"
	// TypeChangeWorkspace is a phone → binary write verb that moves a
	// conversation to another workspace by setting its Cwd (a workspace is a
	// conversation's Cwd; there is no separate workspace id). The target path
	// is confined to $HOME before it is stored. It replies with
	// conversation_updated.
	TypeChangeWorkspace = "change_workspace"
	// TypeSetSystemPrompt is a phone → binary write verb that sets or clears a
	// conversation's durable system prompt, appended to every session that
	// conversation spawns. It is keyed by conversation, not session, so it can
	// be set with no session live; a new value applies from the next session
	// start. system_prompt is nullable so clearing differs from setting "". The
	// byte bound and UTF-8 check live at the registry
	// (conversations.MaxSystemPromptBytes). The reply, conversation_updated,
	// deliberately carries no prompt, because that record goes to every phone
	// on the server-id.
	TypeSetSystemPrompt = "set_system_prompt"

	// Daemon-wide host prompt family (docs/protocol-mobile.md § Daemon-wide host
	// system prompt). Both client → daemon verbs are map-dispatched; the daemon →
	// client reply is outbound only. See the consumer contract in
	// host_system_prompt.go.
	TypeRequestHostSystemPrompt = "request_host_system_prompt"
	TypeSetHostSystemPrompt     = "set_host_system_prompt"
	TypeHostSystemPrompt        = "host_system_prompt"

	// Claude account source status pair (docs/protocol-mobile.md § Claude account
	// source). The client → daemon read verb is map-dispatched; the daemon →
	// client reply is outbound only. See the consumer contract in
	// claude_account.go.
	TypeRequestClaudeAccount = "request_claude_account"
	TypeClaudeAccount        = "claude_account"

	// Claude usage allowance reading pair. The client → daemon read verb is
	// map-dispatched; the daemon → client reply is outbound only. See the
	// consumer contract in claude_usage.go.
	TypeRequestClaudeUsage = "request_claude_usage"
	TypeClaudeUsage        = "claude_usage"

	// Workspace.
	// TypeCreateWorkspaceFolder is a phone → binary write verb that creates a
	// folder on the daemon host under a client-supplied parent path, confined
	// to $HOME. It touches no conversation and replies with
	// workspace_folder_created.
	TypeCreateWorkspaceFolder = "create_workspace_folder"
	// TypeWorkspaceFolderCreated is the binary → phone reply to
	// create_workspace_folder, correlated via in_reply_to. It carries the
	// created folder's canonical (symlink-resolved) absolute path.
	TypeWorkspaceFolderCreated = "workspace_folder_created"
	// TypeRecentWorkspaces is a phone → binary read verb, with an empty
	// payload, for the distinct recently used workspace folders. The list comes
	// only from Cwd values already in the conversations registry, so no
	// untrusted input drives a filesystem operation. It replies with
	// recent_workspaces_list.
	TypeRecentWorkspaces = "recent_workspaces"
	// TypeRecentWorkspacesList is the binary → phone reply to
	// recent_workspaces, correlated via in_reply_to: the distinct workspace
	// paths, most recent first, each with its latest last_used_at.
	TypeRecentWorkspacesList = "recent_workspaces_list"
	// TypeRenameWorkspace is a phone → binary write verb that sets or clears a
	// workspace's display label. label is nullable so clearing differs from
	// setting "". The handler applies the non-blank check and the
	// MaxWorkspaceLabelBytes bound, because
	// conversations.Registry.SetWorkspaceLabel validates nothing. It is keyed by
	// workspace path, which many conversations may share, so it replies with
	// workspace_updated rather than a conversation record.
	TypeRenameWorkspace = "rename_workspace"
	// TypeWorkspaceUpdated carries a workspace's path and stored label (null
	// when cleared). It is the reply to rename_workspace, correlated via
	// in_reply_to, and is also pushed to every other interactive conn. It is a
	// new type rather than a new arm on an existing one because an old client
	// drops an unknown type but would misrender a new meaning on a known one.
	TypeWorkspaceUpdated = "workspace_updated"

	// Push.
	TypeRegisterPushToken = "register_push_token"
)

Envelope types: wire values for Envelope.Type (docs/protocol-mobile.md § Application message types). Every type in this block is in inboundAppTypeSet (envelope.go) except TypeHostSystemPrompt, TypeClaudeAccount and TypeClaudeUsage, which are outbound only; its phone → binary verbs are dispatched through dispatch.Route's Handlers map. The v2-only types follow in their own blocks.

Every Type* constant MUST be declared in this file. cmd/pyry/relay_guard_test.go parses it to collect the constant universe and classifies each type (map-dispatched, switch-intercepted, reply, push and so on); because internal/protocol/compat_test.go's lists are maintained by hand, that guard is the one that fails on a new constant left unclassified. Rationale per family: docs/knowledge/features/protocol-package-constants-codes-go-envelope-types.md.

View Source
const (
	TypeTurnState      = "turn_state"
	TypeAssistantDelta = "assistant_delta"
	TypeToolUse        = "tool_use"
	TypeToolResult     = "tool_result"
	TypeTurnEnd        = "turn_end"
	TypeStall          = "stall"
)

Mobile Protocol v2 interactive events (docs/protocol-mobile.md § Interactive events): binary → phone, pushed only to a phone that negotiated the "interactive" capability, and never dispatched inbound.

MUST NOT be added to inboundAppTypeSet: an old phone never receives these. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeApiRetry   = "api_retry"  // binary → phone, outbound v2 api-retry status
	TypeCompacting = "compacting" // binary → phone, outbound v2 compaction status
)

Mobile Protocol v2 status frames read from claude's stream-json output: the API-error retry and auto-compaction sub-states (docs/protocol-mobile.md § api_retry, § compacting). Like stall, each has a show/clear shape, goes only to an interactive phone, and never opens or closes a turn.

MUST NOT be added to inboundAppTypeSet: an old phone never receives them. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeBackgroundTaskStarted  = "background_task_started"  // binary → phone, outbound v2 background-task open
	TypeBackgroundTaskUpdated  = "background_task_updated"  // binary → phone, outbound v2 background-task change
	TypeBackgroundTaskRoster   = "background_task_roster"   // binary → phone, outbound v2 background-task snapshot
	TypeBackgroundTaskProgress = "background_task_progress" // binary → phone, outbound v2 background-task activity reading
)

Mobile Protocol v2 background-task frames (docs/protocol-mobile.md § background_task_started and the three sections after it). Their subject is work that outlives the turn that started it, such as a shell command claude backgrounded, so a client can tell a finished turn from work still running. background_task_progress is a periodic reading; the others are lifecycle frames and a snapshot. The grouping is by subject, not shape.

The names are the daemon's and follow internal/turnevent's variants, so a claude rename lands in one place (streamsup.emitSystemSubtype's case arms are the authority on claude's subtypes). background_task_roster is named for what it is, a snapshot, not for claude's trigger (background_tasks_changed), so no client reads it as a delta and infers a finish the daemon never observed.

MUST NOT be added to inboundAppTypeSet: an old phone never receives these. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeMCPStatus        = "mcp_status"         // binary → phone, outbound v2 MCP server-status report
	TypeMCPStatusRequest = "mcp_status_request" // phone → binary, inbound v2 control (switch-intercepted)
	TypeMCPReconnect     = "mcp_reconnect"      // phone → binary, inbound v2 control (switch-intercepted)
	TypeMCPToggle        = "mcp_toggle"         // phone → binary, inbound v2 control (switch-intercepted)
)

Mobile Protocol v2 MCP server status and actuation (docs/protocol-mobile.md § mcp_status and the two sections after it). TypeMCPStatus carries a conversation's MCP inventory, pushed live and sent as the correlated reply to each inbound type here. TypeMCPStatusRequest reads it. TypeMCPReconnect and TypeMCPToggle actuate; an accepted actuation is answered with a fresh mcp_status correlated by the request envelope's id, so there is no ack type. The actuators use the claude child's own control-protocol verbs (WriteMCPReconnect and WriteMCPToggle in internal/streamsup); the read verb has a suffix only to avoid colliding with mcp_status.

MUST NOT be added to inboundAppTypeSet: all four are in v2OnlyTypes. relay_guard_test.go files the three inbound types as switch-intercepted and TypeMCPStatus as push+reply.

View Source
const (
	TypeRequestSnapshot = "request_snapshot" // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
	TypeScreenSnapshot  = "screen_snapshot"  // binary → phone, outbound v2 event (plain text only)
)

Mobile Protocol v2 screen snapshot (docs/protocol-mobile.md § Screen snapshot). The daemon renders no screen: handleRequestSnapshot refuses every request_snapshot (conversation.not_found, else server.binary_offline), and screen_snapshot is never emitted and stays declared for reference. Clients read the run configuration from request_session_settings.

MUST NOT be added to inboundAppTypeSet: both are in v2OnlyTypes. relay_guard_test.go files request_snapshot as switch-intercepted and screen_snapshot as push.

View Source
const (
	TypeModalShown     = "modal_shown"     // binary → phone, outbound v2 modal-surfaced event
	TypeModalAnswer    = "modal_answer"    // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
	TypeModalCancel    = "modal_cancel"    // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
	TypeModalDismissed = "modal_dismissed" // binary → phone, outbound v2 modal-resolution event
)

Mobile Protocol v2 modal frames (docs/protocol-mobile.md § Modal). The daemon describes a modal claude raised (a permission prompt, a plan approval, a tool confirmation), the phone answers, and the daemon drives the answer back into claude. modal_shown and modal_dismissed are outbound; modal_answer and modal_cancel are inbound control frames intercepted by dispatchAppFrame, with no dispatch.Route handler. Viewing rides the "interactive" capability; answering is gated separately, per device and default off, by the security model rather than a wire capability.

MUST NOT be added to inboundAppTypeSet: all four are in v2OnlyTypes. relay_guard_test.go files the inbound two as switch-intercepted and the outbound two as push.

View Source
const (
	TypeQueueState     = "queue_state"     // binary → phone, outbound v2 queued-backlog snapshot
	TypeDequeueMessage = "dequeue_message" // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
	TypeSendQueuedNow  = "send_queued_now" // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
)

Mobile Protocol v2 queued-backlog frames (docs/protocol-mobile.md § Queue). A message sent while claude is busy waits in internal/msgqueue. queue_state is the wire form of msgqueue.Snapshot; dequeue_message drives msgqueue.Remove, and send_queued_now drives msgqueue.SendNow, writing the entry into the running turn instead of dropping it. The two inbound verbs are intercepted by dispatchAppFrame. Unlike modal_answer they are ungated for any paired phone (ADR 025 § Security model); queued_msg_id is a per-conversation counter, not a security primitive.

MUST NOT be added to inboundAppTypeSet: all three are in v2OnlyTypes. relay_guard_test.go files the inbound two as switch-intercepted and queue_state as push.

View Source
const (
	TypeDebugBundleChunk = "debug_bundle_chunk" // binary → phone, outbound v2 bundle chunk
	TypeDebugBundleDone  = "debug_bundle_done"  // binary → phone, outbound v2 bundle completion marker
)

Mobile Protocol v2 debug-bundle stream (docs/protocol-mobile.md § Debug bundle). A bundle routinely exceeds one AEAD frame, so the daemon streams it as debug_bundle_chunk frames (one base64 slice each, 0-based contiguous seq) ended by debug_bundle_done, which carries the exact chunk count so the phone can detect truncation. Both ride the asynchronous push path, never the synchronous handler-reply channel.

MUST NOT be added to inboundAppTypeSet: an old phone never receives them. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeSetSessionSettings     = "set_session_settings"     // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
	TypeSessionSettingsUpdated = "session_settings_updated" // binary → phone, outbound v2 reply confirming the change
)

Mobile Protocol v2 session-settings write (docs/protocol-mobile.md § Session settings). set_session_settings changes one session's model, reasoning effort and YOLO (bypass-permissions) mode; session_settings_updated confirms it. SetSessionSettingsPayload uses per-field pointers, so nil means "leave unchanged", distinct from an explicit zero value.

MUST NOT be added to inboundAppTypeSet: both are in v2OnlyTypes. relay_guard_test.go files the request as switch-intercepted and the confirmation as reply.

View Source
const (
	TypeRequestSessionSettings = "request_session_settings" // phone → binary, inbound v2 control carrying RequestSessionSettingsPayload (intercepted pre-dispatch.Route)
	TypeSessionSettings        = "session_settings"         // binary → phone, outbound v2 reply carrying the current run configuration
)

Mobile Protocol v2 session-settings read (docs/protocol-mobile.md § Session settings): a client asks for the current values and for the session id that set_session_settings must address.

RequestSessionSettingsPayload names the conversation. conversation_id is untrusted and used only for an in-memory lookup through handleRequestSessionSettings' conversation-keyed seam; it reaches no log, error string, path or reply. It selects which session the reply describes, and the reported id and values resolve together. Every unresolvable case (an unhosted conversation, one with no live session, an absent or empty id) gets a zero-valued session_settings, never an error and never the shared bootstrap session's id or values.

MUST NOT be added to inboundAppTypeSet: both are in v2OnlyTypes. relay_guard_test.go files the request as switch-intercepted and the answer as reply.

View Source
const (
	TypeRequestSystemPrompt = "request_system_prompt" // phone → binary, inbound v2 control (switch-intercepted)
	TypeSystemPrompt        = "system_prompt"         // binary → phone, one conversation's stored prompt plus a live-session verdict, correlated via in_reply_to
)

Mobile Protocol v2 conversation system-prompt read (RequestSystemPromptPayload, SystemPromptPayload; docs/protocol-mobile.md § Reading a conversation's system prompt). set_system_prompt's ack does not carry the value, so this pair is how a client learns what is stored. A stored prompt takes effect at the next session start, so instead of a second copy of the text the reply carries a three-value verdict comparing it with what the live session was spawned with.

It is a route of its own because the prompt (up to conversations.MaxSystemPromptBytes) would push the all-rows conversations reply past the 65519-byte envelope cap, and SessionSettingsPayload is all zeros exactly when no session resolves. Every unresolvable case, an unhosted conversation included, gets the truthful no_session reply, so there is no error code and the verb is no membership oracle.

MUST NOT be added to inboundAppTypeSet: both are in v2OnlyTypes. relay_guard_test.go files the request as switch-intercepted and the answer as reply.

View Source
const (
	TypeQuestionShown     = "question_shown"     // binary → phone, outbound v2 clarifying-question batch
	TypeQuestionDismissed = "question_dismissed" // binary → phone, outbound v2 question-batch resolution event
)

Mobile Protocol v2 clarifying-question batch (docs/protocol-mobile.md § Question). claude's AskUserQuestion call rides the same approval bridge as a permission prompt (handleApprove parks it in internal/permbridge keyed by tool_use_id, and streamApprovalBridge.Surface raises it), but reaches a client as one question_shown frame per batch rather than as a modal.

It is its own frame family, not a grown modal_shown, for security. ModalShownPayload.DefaultOptionID is the deny option (denyByClass in internal/modalbridge), and default_option_id MUST equal one of options[].id on every modal. A question has no deny option and no safe default, so riding modal_shown would make that invariant class-conditional. ModalAnswerPayload also carries a single OptionID, and claude nests options, each with a description, under each question, so the modal shape fits neither leg. Full argument: docs/knowledge/features/protocol-package-constants-codes-go-envelope-types-question-batch.md

The names are the daemon's: a wire type names what the frame is to a client. claude's words are AskUserQuestion and the keys questions, question, header, options and multiSelect. The singular "question" is a substring of the correct name, so a vocabulary check tests the plural questions and the "ask" every derivation of the tool name carries; that is why the name is not questions_shown (TestQuestionShownType_IsNotClaudesVocabulary).

question_dismissed is its own type because modal_dismissed identifies its target by modal_id and a client routes it to the modal panel. The source values do not carry over: of modal_dismissed's {remote, local, timeout} only timeout applies here, and the caller-disconnect and shutdown paths have no member, so source is a plain string the producer owns (docs/protocol-mobile.md § Question publishes the values).

MUST NOT be added to inboundAppTypeSet: an old phone never receives these. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeQuestionAnswer  = "question_answer"  // phone → binary, inbound v2 control (switch-intercepted)
	TypeQuestionRefused = "question_refused" // phone → binary, inbound v2 control (switch-intercepted)
)

Mobile Protocol v2 clarifying-question answers (QuestionAnswerPayload, QuestionRefusedPayload; docs/protocol-mobile.md § Question): question_answer carries the operator's selections and question_refused says the operator declined. Two types rather than a nullable flag, mirroring modal_answer and modal_cancel.

An answer names each question by its index into the batch, and the daemon reads the text from its own parked copy, so no claude-authored string comes back across the trust boundary. The values are client-authored free text, opaque and checked against nothing. claude's optional top-level freeform response is deliberately not carried; adding it later needs no wire change. The singular "question" is a substring of AskUserQuestion, so neither name may be probed with a strings.Contains on it.

Both are intercepted by dispatchAppFrame, so relay_guard_test.go files them as switch-intercepted, beside modal_answer and modal_cancel. The handler applies no authorization itself: the QuestionResolver seam (questionResolverV2 in cmd/pyry) is the per-device gate.

MUST NOT be added to inboundAppTypeSet: both are in v2OnlyTypes, and IsKnownAppType rejects them with ErrUnknownType.

View Source
const (
	TypeMintPairing   = "mint_pairing"   // phone → binary, inbound v2 control (switch-intercepted)
	TypePairingMinted = "pairing_minted" // binary → phone, one minted pairing as the pair.Encode string, correlated via in_reply_to
)

Mobile Protocol v2 pairing mint (MintPairingPayload, PairingMintedPayload; docs/protocol-mobile.md § Minting a pairing from a paired client). An already-paired client asks the daemon to mint a pairing for another device, so pairing a second device needs no shell on the host (pyry pair).

The names follow the write-verb family (create_conversation → conversation_created), not request_*: the request_* verbs read existing state, and this one creates a credential and a devices.json record, so the type string shows a side effect on the host.

The reply is a bearer credential. Keeping mint_pairing out of inboundAppTypeSet is what stops a v1 client reaching a credential mint at all. The handler MUST answer only an authenticated paired device; the interactive capability is a feature advertisement, not an authorization, and is no substitute. Minting authority moves from "a shell on the host" to "any paired device", widening § Security model threat 4 on purpose; per-device revocation (pyry pair rm) still applies. device_name reaches no claude prompt.

MUST NOT be added to inboundAppTypeSet: both are in v2OnlyTypes. relay_guard_test.go files the request as switch-intercepted and the answer as reply.

View Source
const (
	TypeListApps     = "list_apps"     // client → daemon, discovery request
	TypeApps         = "apps"          // daemon → client, correlated discovery reply
	TypeAppUpdated   = "app_updated"   // daemon → client, whole-record notification
	TypeAppRemoved   = "app_removed"   // daemon → client, tombstone notification
	TypeAppCancel    = "app_cancel"    // client → daemon, list or resource cancellation
	TypeAppCancelled = "app_cancelled" // daemon → client, correlated cancellation reply
)

Hosted-app discovery and lifecycle vocabulary is v2-only and declared ahead of its producers. These constants enable neither routing nor advertisement.

View Source
const (
	TypeAppAssetRequest   = "app_asset_request"   // client → daemon, asset request
	TypeAppAPIRequest     = "app_api_request"     // client → daemon, API request
	TypeAppResponse       = "app_response"        // daemon → client, correlated metadata
	TypeAppResponseChunk  = "app_response_chunk"  // daemon → client, correlated body chunk
	TypeAppResponseCredit = "app_response_credit" // client → daemon, one-chunk credit
)

Hosted resource vocabulary is v2-only. Handlers, producers and capability activation are separate from these declarations.

View Source
const (
	AgentClaude = "claude"
	AgentCodex  = "codex"
)

The closed wire vocabulary of ConversationSummary.Agent.

View Source
const (
	ResetPhaseWrappingUp = "wrapping_up" // the wrap-up turn is running; it writes the handoff note
	ResetPhaseRestarting = "restarting"  // the wrap-up turn is over; claude is being killed and respawned
)

The two values ResettingPayload.Phase can carry (#2453). A CLOSED set, and closed in the strong sense the daemon can actually keep: it authors both tokens itself rather than forwarding one of claude's, so a client switches on two cases and has no third to guess at. Contrast CompactingPayload.Result above, an OPEN set carried verbatim precisely because claude may ship a token at any time.

The two are ORDERED, and one reset emits both — see ResettingPayload.

The Reset prefix rather than Resetting names the DOMAIN, "a reset's phase", rather than the frame it rides on; SystemPromptStatus* in system_prompt.go is the package's precedent for both the shape and the spelling.

View Source
const (
	ResetHandoffPending = "pending" // the note is not resolved yet; only ever seen with ResetPhaseWrappingUp
	ResetHandoffWritten = "written" // a handoff note was written for the successor
	ResetHandoffSkipped = "skipped" // no note was written, and the successor starts without one
)

The three values ResettingPayload.Handoff can carry (#2453). A CLOSED set on the same terms as the phases above: the daemon authors all three.

The set is what lets a client SAY WHETHER A NOTE WAS MADE, which is the part of a reset an operator cannot otherwise find out. It resolves once, on the phase change: pending throughout wrapping_up, then written or skipped on restarting.

ResetHandoffSkipped IS A REPORTED OUTCOME, NOT A MISSING VALUE, and it merges every daemon-side reason a note was not made — the wrap-up turn produced nothing usable, it failed, or it was not run at all. All of them mean the same thing to a client: the successor starts without a note, and nothing the client sends would repair it. No reason field is declared, so no prose channel exists on this frame; whoever adds one owes it a bound and a sanitization statement, as CompactingPayload.ErrorText carries above.

View Source
const (
	SystemPromptStatusNoSession = "no_session" // nothing is running to compare the stored value against
	SystemPromptStatusMatches   = "matches"    // the running session was spawned with the stored value
	SystemPromptStatusDiffers   = "differs"    // the running session was spawned with a DIFFERENT value; the stored one applies at its next start
)

The three values SystemPromptPayload.SessionPromptStatus can carry (#2152). A CLOSED set: the daemon emits one of these three on every reply and never the empty string, so a client switches on three cases and has no fourth to guess at.

The split exists because a stored prompt takes effect at the conversation's NEXT session start (set_system_prompt's own contract), so the stored value alone cannot tell an operator what the child they are typing at is actually running under. These three answer that, and only that.

SystemPromptStatusNoSession MERGES several daemon states on purpose, and the merge is the reply's whole error handling: this daemon does not host the named conversation, it hosts one that is bound to no session, it hosts one bound to a session the pool no longer holds, the request named no conversation at all, or no resolver is wired (foreground / v1). All five mean the same thing to a client — there is no running session to compare against — and none of them is an error the client can repair by sending something different. Distinguishing the first would additionally make the verb a conversation-membership oracle.

View Source
const (
	DefaultThreadQueryLimit = 50
	MaxThreadQueryLimit     = 256
)

Query limits count ordered rows, excluding ties and required extras.

View Source
const (
	TypeNoiseInit = "noise_init"
	TypeNoiseResp = "noise_resp"
	TypeNoiseMsg  = "noise_msg"
)

Inner-frame discriminator values for InnerFrameV2.Type (docs/protocol-mobile.md § Wire shapes table).

View Source
const CapabilityClaudeUsage = "claude_usage"

CapabilityClaudeUsage lets a client detect that this daemon answers request_claude_usage. Detection only: it grants no access and gates nothing, and the verb is answered whether or not it was negotiated.

View Source
const CapabilityContextUsage = "context_usage"

CapabilityContextUsage is the wire vocabulary string a client advertises in its hello.payload.capabilities to say it can ask for a conversation's context breakdown on demand and render the answer, and that the daemon echoes in hello_ack.payload.capabilities when it supports the verb (docs/protocol-mobile.md § Capability negotiation). It detects #2431's TypeRequestContextUsage. A daemon built before it drops the string in the intersection, which is the stale-daemon signal a cross-repo test needs when a commit sha gives it no ordering.

IT DETECTS THE ASK, NOT THE FRAME. A client learns from this string only that it may REQUEST a reading; it says nothing about receiving one. The automatic post-turn context_usage frame (#2371) has shipped on the interactive lane since before this string existed and keeps arriving for a client that never advertises it — so a client must already handle the frame regardless, and gating its renderer on this capability would blank the reading it was receiving before.

Detection only — this string grants no access. The verb gates on CapabilityInteractive alone, exactly as CapabilityModelList's verb does, so a client advertising only this one is negotiated as non-interactive and reaches none of it; and a client advertising interactive WITHOUT this string is answered exactly as before. Gating on it would cut off pyrycode-mobile, which advertises interactive only (ADR 037 makes gating a per-feature decision, not a default). Like its neighbours this is pure vocabulary; the trust decision lives in the consumer, internal/relay, not here.

View Source
const CapabilityHostedAppsV1 = "hosted_apps_v1"

CapabilityHostedAppsV1 names the hosted-app contract. It is declaration-only: support requires registration, supervision and resource routing before advertisement.

View Source
const CapabilityInteractive = "interactive"

CapabilityInteractive is the wire vocabulary string a phone advertises in its hello.payload.capabilities to opt into the v2 interactive event stream, and that the daemon echoes in hello_ack.payload.capabilities when it supports it (docs/protocol-mobile.md § Capability negotiation). This is pure vocabulary — the trust decision (the daemon intersecting the phone's advertised set with its own supported set, never blindly mirroring the phone's claims) lives in the consumer, #608, not here.

View Source
const CapabilityModelList = "model_list"

CapabilityModelList is the wire vocabulary string a client advertises in its hello.payload.capabilities to say it can ask for a conversation's model menu and render the answer, and that the daemon echoes in hello_ack.payload.capabilities when it supports them (docs/protocol-mobile.md § Capability negotiation). It detects the #2124 + #2125 pair as one unit: #2124's daemon-wide retained-vocabulary fallback and #2125's TypeRequestModelList verb. Neither is separately useful — the fallback with no verb gives a client no way to ask, and the verb with no fallback has nothing to answer for a conversation whose bound session has spawned no child — so one string covers both. A daemon built before them drops it in the intersection, which is the stale-daemon signal a cross-repo test needs when a commit sha gives it no ordering.

Detection only — this string grants no access. The verb gates on CapabilityInteractive alone, exactly as it did before this string existed, so a client advertising only this one is negotiated as non-interactive and reaches none of it; and a client advertising interactive without this string is answered exactly as before. Gating on it would cut off pyrycode-mobile, which advertises interactive only (ADR 037 makes gating a per-feature decision, not a default). Like its neighbours this is pure vocabulary; the trust decision lives in the consumer, internal/relay, not here.

View Source
const CapabilityMultiAgent = "multi_agent"

CapabilityMultiAgent is the wire vocabulary string a client advertises in its hello.payload.capabilities to say it understands conversations run by more than one agent, and that the daemon echoes in hello_ack.payload.capabilities when it supports them (docs/protocol-mobile.md § Capability negotiation). The desktop and mobile grouped-menu work codes against this exact string.

UNLIKE its detection-only neighbours, this one changes what the daemon sends. A client that negotiated it reads an agent on every conversations row (ConversationSummary.Agent); a client that did not is never sent a Codex conversation at all, so an app that only knows Claude sees exactly the list it saw before Codex existed. It grants no interactive access: every interactive gate reads CapabilityInteractive alone. Like its neighbours this is pure vocabulary; the trust decision lives in the consumer, internal/relay, not here.

View Source
const CapabilityQuestion = "question"

CapabilityQuestion is the wire vocabulary string a client advertises in its hello.payload.capabilities to say it understands inbound question batches, and that the daemon echoes in hello_ack.payload.capabilities when it supports them (docs/protocol-mobile.md § Capability negotiation). Because the daemon echoes only the intersection with its own supported set, a client detects question support by advertising this string and reading it back: a daemon built before #2020 drops it, which is the stale-daemon signal a cross-repo test needs when a commit sha gives it no ordering.

Detection only — this string grants no access. The interactive event stream, the TypeQuestionShown/TypeQuestionDismissed fan-out and the connect-time question reconcile all gate on CapabilityInteractive alone, so a client advertising only this one is negotiated as non-interactive and receives none of them. Like its neighbour this is pure vocabulary; the trust decision lives in the consumer, internal/relay, not here.

View Source
const CapabilityStopBackgroundTask = "stop_background_task"

CapabilityStopBackgroundTask detects support for stopping one background task. A client advertises it in hello and draws a per-task stop button only when hello_ack echoes it through capability intersection negotiation (ADR 037). Detection only: the stop verb gates on CapabilityInteractive alone; this string grants no interactive access and is not required to use the verb.

View Source
const CapabilityThread = "thread"

CapabilityThread declares support for daemon-built thread items and tagged live state (ADR 042). It is vocabulary only, not yet advertised or negotiated.

View Source
const CapabilityThreadCompact = "thread_compact"

CapabilityThreadCompact declares compact support separately from expansion. Vocabulary alone enables neither negotiation, handlers nor live publication.

View Source
const CapabilityThreadExpansion = "thread_expansion"

CapabilityThreadExpansion is declared ahead of handlers and is not advertised. Negotiation requires both reads wired to the real Store with normal thread and interactive authorization. Vocabulary alone never enables expansion support.

View Source
const CodeStopBackgroundTaskRefused = "stop_background_task.refused"

CodeStopBackgroundTaskRefused merges invalid task ids and seam refusals into one nonretryable answer without exposing child diagnostics or task existence.

View Source
const MaxAttachmentIDsPerMessage = 32

MaxAttachmentIDsPerMessage bounds how many attachment ids one send_message may name (SendMessagePayload.AttachmentIDs below, published by #2036 in docs/protocol-mobile.md § Attachments).

It is the FIRST of this family's two bound idioms — a published NUMBER, a producer-side contract a client must obey to compose a conforming frame, the posture MaxAttachmentChunkBytes and MaxAttachmentIDBytes ship with. It is deliberately not the second: the per-upload byte bound and the concurrency bound behind attachment.too_large / attachment.too_many_uploads are receiver-configured and unpublished, learned by being rejected. A client composing a message needs this one BEFORE it sends, not after.

UNCHECKED HERE, like every bound this package declares. internal/protocol is a stdlib-only leaf data package with no producer, no consumer and no validator; nothing in this package counts the list, and a reader must not mistake a declared bound for one this type enforces. It IS enforced, since #2038, by SendMessage in internal/relay/handlers — the frame's first counter — which refuses an over-bound list with CodeProtocolMalformed rather than truncating it. No wire code is named HERE for that refusal even so; ErrUnknownUpload's doc block is the precedent for declining to publish a mapping this package does not own.

The bound counts ELEMENTS, NOT DISTINCT IDS. A list may repeat one id 32 times, and that counting rule is load-bearing rather than incidental: #2038 DEDUPLICATES a repeat on first occurrence, and it counts this bound against the raw elements BEFORE doing so, so 33 copies of one id is over bound.

Why 32, as arithmetic rather than taste. Each canonical id is exactly 36 bytes and costs 39 inside a JSON array (two quotes and one separator), so 32 ids are 1248 B — under 2% of the 65519-byte application-envelope cap — and the bound never competes with Text for envelope budget. That is also why it is NOT derived from the cap: that derivation yields roughly 1680 ids and would leave no room for the message. The binding constraint is resource rather than bytes, since every id named becomes a directory component the receiver resolves, so 32 bounds that work at a number a receiver does inline without a queue while sitting far above what a person attaches to one message. TestSendMessagePayload_MaxAttachmentIDs_FitV2EnvelopeCap measures the real total rather than trusting this paragraph; if it ever fails, LOWER this constant.

DO NOT OVERSELL IT. The envelope cap already limits an unbounded list to roughly 1680 elements, and a paired device may already send messages that spawn claude turns — orders of magnitude more expensive than 1680 directory resolutions. This bound is contract clarity and bounded work, not a new defence against anything the pairing boundary does not already permit.

View Source
const MaxDeviceNameBytes = 128

MaxDeviceNameBytes bounds MintPairingPayload.DeviceName. UTF-8 BYTES, NOT RUNES, matching every other bound in this package and the envelope-cap arithmetic they budget against.

The value is NOT borrowed from MaxAttachmentFilenameBytes, whose 255 is POSIX NAME_MAX because a filename is a sanitiser input for one path component. A device name is never a path, so that anchor does not transfer even though the constant's shape does. The anchor here is native: a device label is one human-typed line rendered in a `pyry pair list` column and in a client's device list, and 128 bytes is eight times the label `pyry pair` generates when the operator names none ("device-" plus eight hex characters) and far past any hand-typed name, while keeping devices.json records small and one listing row unwrapped.

A LENGTH CEILING IS NOT A SAFETY PROPERTY — MaxAttachmentIDBytes' warning transfers, and it is the reason this paragraph exists rather than a caveat. 128 bytes accommodates an ANSI escape run, a newline-injection payload or "../../../../etc/passwd" several times over, so this constant does nothing about any of them. See DeviceName's own block for who owes what.

View Source
const MaxThreadEnvelopeBytes = 65519

MaxThreadEnvelopeBytes is the encrypted application plaintext cap.

View Source
const MaxWorkspaceLabelBytes = 128

MaxWorkspaceLabelBytes bounds RenameWorkspacePayload.Label. UTF-8 BYTES, NOT RUNES, matching every other bound in this package. An over-bound label is REFUSED, never truncated, and the offending bytes stay out of the error reply.

The value is NOT borrowed from MaxDeviceNameBytes even though it shares its number and its posture: a workspace label and a device name are unrelated fields, and a constant whose only justification is another constant rots the moment either field's use changes. Two native anchors:

A label is one human-typed line rendered as a list row beside a folder path. 128 bytes is far past any hand-typed folder nickname while keeping one row unwrapped.

AND IT IS PICKED AGAINST N LABELS IN ONE REPLY, NOT ONE LABEL IN ISOLATION, which is the arithmetic conversations-registry-crud.md § WorkspaceLabel / SetWorkspaceLabel explicitly deferred to this field. #2208 embeds one label per conversation in a list_conversations reply against the 65519-byte v2 application-envelope cap. Worst-case JSON escaping is 6 bytes per source byte (a control byte becomes \u00XX), so 128 bytes costs at most 768 on the wire plus ~18 for its key — call it ~790 per labelled row on top of that row's existing cost, admitting on the order of 80 fully-escaped worst-case rows. A realistic ASCII label of ~30 bytes costs ~50. Recorded here so #2208 does not have to re-derive it; a larger bound chosen here would have moved that decision into a ticket that cannot revisit it.

A LENGTH CEILING IS NOT A SAFETY PROPERTY — MaxDeviceNameBytes' warning transfers unchanged, and it is restated rather than cross-referenced because the ceiling is exactly what a later reader is most likely to mistake for containment. 128 bytes accommodates an ANSI escape run or a newline-injection payload several times over. The label is an opaque display string: the daemon stores and echoes it, never logs it and never interpolates it into an error message, and rendering it safely is the client's.

View Source
const ThreadProjectionCompact = "compact-v1"

ThreadProjectionCompact selects public roots with full non-tool/agent content and tool/agent headers. Omitted projection selects complete delivery. Selection is connection-and-conversation scoped, covering queries and subsequent live output. First selection or incompatible view change requires version-zero newest-window initialization. Reconnect resumes only successfully completed coverage with matching conversation/projection/epoch; other coverage is unusable. Unknown projections require refusal, never silent complete-view fallback.

View Source
const (
	TypeAttachmentChunk = "attachment_chunk" // phone ↔ binary, one chunk of an attachment's bytes (both directions)
)

TypeAttachmentChunk carries one slice of one attachment's bytes plus the whole transfer's metadata (AttachmentChunkPayload; docs/protocol-mobile.md § Attachments). A file routinely exceeds one AEAD frame, so the sender splits it and the receiver reassembles; the relay stays transport-only.

It is the one bidirectional type: upload (client → daemon, handled by handleAttachmentChunk in internal/relay) and retrieval (daemon → client, sent by StreamAttachment) share the frame, so the two legs cannot drift apart. The trust asymmetry (inbound every field is a client claim, outbound daemon-authored) lives in AttachmentChunkPayload's SECURITY block. There is no completion frame: TotalChunks rides every chunk, so a receiver knows the count from the first one it sees. A retrieval abandoned mid-stream ends in a TypeError correlated via in_reply_to.

MUST NOT be added to inboundAppTypeSet: since the upload leg is inbound, that rejection is what keeps a v1 client from sending one into dispatch.Route. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	TypeAttachmentOffered = "attachment_offered" // binary → phone, unsolicited push: a file exists on the host for this conversation
)

TypeAttachmentOffered tells a client that a file exists on the host for a conversation (AttachmentOfferedPayload; docs/protocol-mobile.md § Attachments), which is how a client learns an attachment id it did not mint. No bytes ride it ("offered", not "sent"); a client that wants them sends request_attachment. TypeMessage could not carry this: it is pushed only for the operator's own message, and widening it would change a record shape history-page decoders already read.

It is an unsolicited push, so nothing correlates it; this block, the § Application message types row and relay_guard_test.go's push entry must agree. Like modal_shown it originates from a claude MCP tool call on the control socket and carries a conversation id but no turn id.

MUST NOT be added to inboundAppTypeSet: that rejection also stops a v1 client sending one to claim that a file exists. v2OnlyTypes in compat_test.go, push in relay_guard_test.go; it has no inbound leg.

View Source
const (
	TypeAttachmentStored = "attachment_stored" // binary → phone, the upload leg's success reply, correlated via in_reply_to
)

TypeAttachmentStored is the upload leg's one success reply: the transfer completed, its claims checked out, and the bytes are on the host under the id the client chose (AttachmentStoredPayload; docs/protocol-mobile.md § Attachments). It is the positive of CodeAttachmentStorageFailed and covers the whole transfer. The name says what the frame is, the daemon's assertion, not the client's action.

It is a reply correlated via InReplyTo, as TypeSessionSettingsUpdated is and as the CodeAttachmentStreamAborted failure on the same leg is, so the payload has no request-id key. InReplyTo names the chunk whose arrival completed the transfer, not the one with the highest index: chunks may arrive in any order and the client cannot predict which envelope closes the set, so the payload also carries the attachment id. This block, the § Application message types row and relay_guard_test.go's reply entry state one decision and must agree.

MUST NOT be added to inboundAppTypeSet: that rejection is what keeps a v1 client from sending one into dispatch.Route. v2OnlyTypes in compat_test.go, reply in relay_guard_test.go.

View Source
const (
	TypeBanner = "banner" // binary → phone, outbound v2 operator-facing text
)

TypeBanner carries text claude printed about the session rather than as part of an answer, such as a hook's block reason (docs/protocol-mobile.md § banner). No other frame could carry it: unrecognized_message is a parser-gap diagnostic, compacting and rate_limited each report one machine state, and the assistant stream carries only what the model said. A single report with no edges. The name derives from none of claude's words (the subtypes informational and notification, the keys content, level and prevent_continuation); TestBannerType_IsNotClaudesVocabulary pins that.

MUST NOT be added to inboundAppTypeSet: that is also the guarantee that nothing accepts a banner from a phone. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeCompactionBoundary = "compaction_boundary" // binary → phone, outbound v2 compaction boundary
)

TypeCompactionBoundary marks a finished compaction: what triggered it and how far the context shrank, so a thread can say why claude no longer remembers what came before (docs/protocol-mobile.md § compaction_boundary). It cannot be a wider compacting payload: claude states the counts on a separate system/compact_boundary line that arrives after the system/status line compacting's falling edge is read from (see turnevent.CompactionBoundary). The name uses the daemon's word, compaction; "boundary" is what the frame marks.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeContextUsage = "context_usage" // binary → phone, outbound v2 context-window reading
)

TypeContextUsage carries one conversation's context breakdown: the model, the totals and percentage, and three independently bounded inventories (categories, MCP tools, memory files), each with its own dropped count (docs/protocol-mobile.md § context_usage). One shape serves both producers: a push after each turn and the correlated reply to request_context_usage. The reading is claude's own arithmetic and informational; control decisions key on contextwindow.Read, and nothing in the daemon gates on what a client does with it.

MUST NOT be added to inboundAppTypeSet: that is also the guarantee that nothing accepts a context reading from a phone. v2OnlyTypes in compat_test.go, push+reply in relay_guard_test.go.

View Source
const (
	TypeHistoryPage = "history_page" // binary → phone, one backward step of a history walk, correlated via in_reply_to
)

TypeHistoryPage is one backward step of a history walk: the entries, the cursor to ask again with, and whether the start of the log was reached (HistoryPagePayload, mirroring history.Page; docs/protocol-mobile.md § Conversation history). It is a reply correlated via InReplyTo, like TypeSessionSettings, and carries no conversation id because the client knows what it asked.

Each entry is one wire envelope's worth (type, payload, timestamp, durable entry id), so a client re-reduces a page oldest first through its live-stream reducer. The id is the log's durable per-conversation id, not Envelope.EventID, which does not survive a restart. A walk ends on at_start, never on an empty entries list (HistoryPagePayload says why). Unlike the request, this frame carries replayed content, claude-authored for assistant entries, so § Security model's threat 1 applies (see HistoryEntry).

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, reply in relay_guard_test.go.

View Source
const (
	TypeInterrupt = "interrupt" // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
)

TypeInterrupt stops the running turn, the remote equivalent of Esc (docs/protocol-mobile.md § Interrupt). The daemon maps it to turnevent.Cancel. Its optional InterruptPayload names the conversation; an absent payload, an absent or empty conversation_id and a body that does not decode all mean the conversation the daemon's cursor points at, which keeps old clients working. A replay just stops the turn again, so there is no nonce or dedup. It requires the negotiated "interactive" capability and is exempt from the per-device permission gate (ADR 025 § Security model); naming a conversation is a validated lookup key, not a widening.

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	TypeModelAnnounced = "model_announced" // binary → phone, outbound v2 announced-model report
)

TypeModelAnnounced reports the model claude says it resolved for the turn, from its system/init line (docs/protocol-mobile.md § model_announced): an identity report. Its model field is what claude announced, while the model field on ScreenSnapshotPayload, SessionSettingsPayload and SetSessionSettingsPayload is the per-session override ("" for the inherited default); the two can disagree.

The name is the daemon's and follows turnevent.ModelAnnounced. claude's word on this path is its subtype, init. "model" is both the subject noun and claude's key, so a vocabulary check MUST NOT test for the substring "model", which the correct name contains.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeModelList = "model_list" // binary → phone, outbound v2 model-list report
)

TypeModelList carries the models array of claude's initialize control reply, so a client can build its model, reasoning-effort and permission-mode menus (docs/protocol-mobile.md § model_list). A capability report, not turn-scoped. It is pushed on the interactive lane and at connect, and is also the unchanged answer to request_model_list.

The name is the daemon's. claude's words here are initialize and models, and model_list contains neither; "model" is the subject noun, so a vocabulary check MUST NOT test for it (see TypeModelAnnounced).

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeModelRefusalFallback = "model_refusal_fallback"
)

Mobile Protocol v2 refusal-fallback report (docs/protocol-mobile.md § model_refusal_fallback). claude emits this fact when it refuses a turn on one model and retries on another. The frame explains a later model change; TypeModelAnnounced remains the authority on which model claude is running.

MUST NOT enter inboundAppTypeSet. This is an outbound interactive push, and the protocol and relay totality guards classify it as v2-only and push-only.

View Source
const (
	TypeModelRefusalNoFallback = "model_refusal_no_fallback"
)

Mobile Protocol v2 refusal-without-fallback report (docs/protocol-mobile.md § model_refusal_no_fallback). claude emits this fact when it refuses a turn and does not retry it on another model. The frame is explanatory only; TypeModelAnnounced remains the current-model authority.

MUST NOT enter inboundAppTypeSet. This is an outbound interactive push, and the protocol and relay totality guards classify it as v2-only and push-only.

View Source
const (
	TypeNewSession = "new_session" // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
)

TypeNewSession starts a fresh session in one conversation (docs/protocol-mobile.md § New session): a kill and respawn under a new session id through the SessionStarter seam, not a /clear keystroke. There is no ack; the client sees the break as session_transition (reason "clear"), and apart from CodeNewSessionWorkspaceRefused the verb is silent. Its optional NewSessionPayload names the conversation; an absent payload, an absent conversation_id and an undecodable body all mean the conversation the daemon's cursor points at. It requires the negotiated "interactive" capability and is exempt from the per-device permission gate (ADR 025 § Security model).

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	TypeRateLimited = "rate_limited" // binary → phone, outbound v2 usage-limit report
)

TypeRateLimited reports that claude's usage-limit window is in a state other than the one measured as benign, so a turn that stops on a limit has a reason on the wire (docs/protocol-mobile.md § rate_limited). A condition report about a window no turn owns. The name follows turnevent.RateLimited and matches what cmd/pyry's eventKind logs for the variant; that agreement is not tested because internal/protocol cannot import cmd/pyry.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeReadWorkspaceFile = "read_workspace_file" // phone → binary, inbound v2 control (switch-intercepted)
)

TypeReadWorkspaceFile reads one regular file as it is on the host now, from the recorded workspace or an admitted read folder of the conversation it names (ReadWorkspaceFilePayload; docs/protocol-mobile.md § read_workspace_file). It is answered exactly as TypeRequestAttachment is: an attachment_chunk stream correlated by in_reply_to, or one CodeAttachmentNotFound or CodeAttachmentStreamAborted TypeError.

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	// TypeRekeyRequest lets either side nudge the peer to start a re-key
	// handshake. The binary is the IK responder (ADR 024), so an inbound
	// rekey_request takes no transport action. relay_guard_test.go files it as
	// switch-intercepted.
	TypeRekeyRequest = "rekey_request"
)

Mobile Protocol v2 control envelope (docs/protocol-mobile.md § Re-key). This and every later Type* block holds v2-only types, which MUST NOT be added to inboundAppTypeSet (envelope.go). Inbound v2 control frames are intercepted in internal/relay/v2session.go's dispatchAppFrame before internal/dispatch.Route, and outbound v2 events go only to v2 clients; IsKnownAppType rejecting them with ErrUnknownType keeps a control frame out of the v1 handler chain and stops a v1 client sending an outbound-only type. internal/protocol/compat_test.go files each in v2OnlyTypes, and cmd/pyry/relay_guard_test.go classifies each from the moment the constant exists.

View Source
const TypeReplySuggestion = "reply_suggestion"

TypeReplySuggestion carries outbound v2 suggestion state, gated by the negotiated "interactive" capability (docs/protocol-mobile.md § reply_suggestion). ReplySuggestionPayload defines its set and explicit-null clear contract. Never dispatched inbound or added to the v1 inboundAppTypeSet; push in relay_guard_test.go.

View Source
const (
	TypeRequestAttachment = "request_attachment" // phone → binary, inbound v2 control (switch-intercepted)
)

TypeRequestAttachment asks the daemon for a stored attachment (RequestAttachmentPayload; docs/protocol-mobile.md § Attachments). The answer is an attachment_chunk stream correlated by in_reply_to, or one CodeAttachmentNotFound or CodeAttachmentStreamAborted TypeError. The name follows the request_* family of read verbs.

The payload names a conversation and an attachment and nothing else. Safety is confinement: the id is a lookup key validated against the daemon's registry before any path join, and naming a conversation is not authorization; RequestAttachmentPayload's block states the rule in full. Correlation rides InReplyTo with no request-id key, as for TypeAttachmentStored, and the committed testdata/request_attachment.json and testdata/attachment_chunk_retrieval.json pin it.

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	TypeRequestContextUsage = "request_context_usage" // phone → binary, inbound v2 control (switch-intercepted)
)

TypeRequestContextUsage asks for a conversation's context breakdown now (RequestContextUsagePayload; docs/protocol-mobile.md § Asking for a context usage reading on demand). The post-turn push is a detail:"summary" reading; this verb gets the costlier detail:"full" one. The answer is context_usage unchanged, correlated by InReplyTo and carrying no EventID, so it never enters the replay ring.

The payload has no detail key; the daemon always asks at "full". Closely spaced asks collapse into one round trip and share its result, so a client-chosen detail would let one client downgrade another's reading.

A refusal is CodeConversationNotFound or CodeContextUsageUnavailable. A malformed payload is tolerated rather than refused: the id only reaches a registry membership check, never a path, so the empty id a failed decode leaves is refused there. Do not copy that tolerance to a verb that joins the id into a path.

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	TypeRequestDebugBundle = "request_debug_bundle" // phone → binary, inbound v2 control (intercepted pre-dispatch.Route)
)

TypeRequestDebugBundle asks for the daemon's debug bundle, built around its recent log ring (docs/protocol-mobile.md § Debug bundle lists the contents). The bundle is daemon-global, so the frame is bare: no payload, and no field that could select another session's data. The answer is the debug_bundle_chunk stream, never the synchronous handler-reply path. Authorization is pairing, enforced at the Noise IK handshake (an unpaired device is refused with 4401), so the verb has no gate of its own.

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	TypeRequestHistory = "request_history" // phone → binary, inbound v2 control (switch-intercepted)
)

TypeRequestHistory asks for conversation-history entries older than the ones a client holds (RequestHistoryPayload; docs/protocol-mobile.md § Conversation history). It reads internal/history's durable log; catch-up after a dropped connection (replayMissed over internal/eventring) is a separate, bounded mechanism. Pages walk backwards, newest first, addressed by an opaque cursor rather than an offset or page number, which a concurrent append would invalidate. RequestHistoryPayload's block carries the handler's rules: the cursor is not a secret or a capability, a Limit of 0 means the daemon chooses, and the conversation id is validated against the registry before any path join.

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	TypeRequestModelList = "request_model_list" // phone → binary, inbound v2 control (switch-intercepted)
)

TypeRequestModelList asks for a conversation's model menu at any time (RequestModelListPayload; docs/protocol-mobile.md § Asking for a model list on demand). It covers a conversation created after the client connected, which neither the live lane nor the connect-time reconcile reaches. The answer is model_list with ModelListPayload unchanged and from the same source, correlated by InReplyTo and carrying no EventID, so it never enters the replay ring and model_list stays a push in relay_guard_test.go. A refusal is a TypeError with CodeConversationNotFound or CodeModelListUnavailable, since an empty models array must never stand in for "unknown".

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, switch-intercepted in relay_guard_test.go.

View Source
const (
	TypeResetting = "resetting" // binary → phone, outbound v2 conversation-reset status
)

TypeResetting reports a conversation reset in progress (docs/protocol-mobile.md § resetting). A reset runs a wrap-up turn that writes a handoff note, then kills and respawns claude under a new session id; without this frame a client sees only a pause. One reset emits two active:true frames before a single active:false; ResettingPayload states that and its closed value sets.

It is grouped alone because its source is the daemon's own reset routine, not claude's output: every value on it is daemon-authored, so nothing claude wrote crosses on it. It is not a turnevent variant and never opens or closes a turn.

MUST NOT be added to inboundAppTypeSet: no phone may send it, and IsKnownAppType rejects an inbound "resetting". v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeResync = "resync" // binary → phone, outbound v2 mid-turn-reconnect resync marker
)

TypeResync tells a reconnecting phone to reload a conversation in full: its hello.last_event_id has aged out of the bounded per-conversation event ring, so the daemon sends this instead of a partial replay (ADR 025 § Backpressure / replay; docs/protocol-mobile.md § resync). Its payload is an inline conversation_id with no named struct.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeSessionError = "session_error" // binary → phone, outbound v2 unsolicited conversation-scoped session-error frame; the code says whether it is terminal
)

TypeSessionError reports a conversation-scoped session problem as an unsolicited frame (docs/protocol-mobile.md § Error codes). Its code says whether the problem is terminal:

  • CodeSessionBlocked is terminal. internal/msgqueue bounded a persistent-failure drain and gave up (the OnGiveUp seam); a client must never read it as transient.
  • CodeSessionChildCrashing is not terminal. claude has exited at startup several times in a row and the daemon is still restarting it. Queued messages are kept, and a CodeSessionBlocked may follow if delivery never recovers.

It answers no request, so SessionErrorPayload carries the conversation identity itself, plus the code and a human-readable message.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeSessionFacts = "session_facts" // binary → phone, outbound v2 session-facts report
)

TypeSessionFacts reports claude's build version and the permission posture it says the child runs under, from the same system/init line as model_announced (docs/protocol-mobile.md § session_facts). The daemon knows what it asked for; only claude knows what it got. An identity report about the child run, kept apart from model_announced, which is about one turn. "Session" names that child run: the frame carries no session identity, and claude's session_id is not the daemon's conversation.

The discriminating words are claude's subtype (init) and keys (claude_code_version, permissionMode). "session" is a substring of the correct name and claude's own word (session_id), so a check MUST NOT test for it, and the session_-prefixed siblings are told apart by equality (TestSessionFactsType_IsNotClaudesVocabulary).

There is no effort field: no init line carries an effort key, even with an effort set, and effortInitPins in internal/streamsup fails if that changes.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeSessionTransition = "session_transition" // binary → phone, outbound v2 session-boundary marker
)

TypeSessionTransition marks a session boundary: a conversation's session rotated (a /clear, an idle eviction, a workspace change), so the phone can draw the boundary rather than infer it (docs/protocol-mobile.md § session_transition). The payload is SessionTransitionPayload.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeSlashCommandList = "slash_command_list" // binary → phone, outbound v2 slash-command-list report
)

TypeSlashCommandList carries the slash commands the running child accepts for a conversation (docs/protocol-mobile.md § slash_command_list), from the commands array of the same initialize reply model_list uses. That array is the source because it carries each command's aliases, which the names-only slash_commands key on system/init does not; reset, the desktop Actions menu's entry, is an alias of clear. A capability inventory of verbs, kept apart from model_list because the subjects differ. There is no inbound request verb: the list is pushed on the interactive lane and at connect.

The name is the daemon's. claude's four words here are initialize, commands, slash_commands and terminal_slash_commands; slash_command_list contains none of them and no "init". The trap is three words wide: command, slash_command and slash are substrings of the correct name, so a vocabulary check tests the plural commands, which both longer keys contain (TestSlashCommandListType_IsNotClaudesVocabulary).

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const TypeStopBackgroundTask = "stop_background_task"

TypeStopBackgroundTask is a phone → binary v2 control verb, intercepted before v1 dispatch (docs/protocol-mobile.md § Stop background task). It requires negotiated interactive and is inert without a configured stopper. CapabilityStopBackgroundTask only lets a client detect support; it is not required to use the verb.

View Source
const TypeSwitchAgent = "switch_agent"

TypeSwitchAgent names a phone → binary v2 agent-switch request (docs/protocol-mobile.md § switch_agent), intercepted by dispatchAppFrame. It remains outside the v1 inboundAppTypeSet.

View Source
const (
	TypeThinkingProgress = "thinking_progress" // binary → phone, outbound v2 thinking-progress reading
)

TypeThinkingProgress is claude's mid-turn proof of life, the daemon's translation of the system/thinking_tokens line (docs/protocol-mobile.md § thinking_progress), so a client can tell a slow answer from a wedged one. A periodic reading with no edges. It carries no reasoning content (ThoughtChunk carries that and is never forwarded, ADR 025), so there is nothing to render as text. The name follows turnevent.ThinkingProgress: "progress" is what the daemon reports, "tokens" is claude's word.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const TypeThreadCompactUpdate = "thread_compact_update"

TypeThreadCompactUpdate is outbound only: the daemon's coalesced live update for a connection joined with the compact projection.

View Source
const (
	TypeToolDenied = "tool_denied" // binary → phone, outbound v2 tool-denial marker
)

TypeToolDenied says which announced tool call claude refused to run, so a blocked tool row looks blocked rather than broken (docs/protocol-mobile.md § tool_denied). It is a frame of its own rather than fields on tool_result: claude's system/permission_denied line arrives before the tool result, and a denial recovered from the result line can arrive after tool_result has shipped (see turnevent.ToolCallDenied). The name says what the frame is about, a tool call; "permission" would suggest the unrelated MCP approval flow.

MUST NOT be added to inboundAppTypeSet: that is also the guarantee that nothing accepts a tool_denied from a phone. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeToolProgress = "tool_progress" // binary → phone, outbound v2 tool-progress reading
)

Mobile Protocol v2 tool-progress reading (docs/protocol-mobile.md § tool_progress). This push-only frame updates the open tool row named by tool_use_id with claude's signed elapsed-seconds reading. It is a report, not a lifecycle edge or an inbound control surface.

MUST NOT be added to inboundAppTypeSet. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const (
	TypeUnrecognizedMessage = "unrecognized_message" // binary → phone, outbound v2 parser-gap diagnostic
)

TypeUnrecognizedMessage carries to the client any stream-json message or content block the parser neither maps nor lists as measured known-ignored (docs/protocol-mobile.md § unrecognized_message), so a claude release that moves something meaningful into a new type is visible rather than lost. It reports a gap in the daemon's mapping, not a claude sub-state, and its payload is the only interactive one that carries raw model-adjacent JSON.

MUST NOT be added to inboundAppTypeSet: an old phone never receives it. v2OnlyTypes in compat_test.go, push in relay_guard_test.go.

View Source
const V2Version = 2

V2Version is the major version number carried in InnerFrameV2.Version. Receivers MUST reject mismatched values with WS close 4421 (protocol mismatch).

Variables

View Source
var (
	ErrUnknownType = errors.New("protocol: unknown envelope type")
	ErrUnsupported = errors.New("protocol: unsupported envelope feature")
)

Sentinel errors returned by IsKnownAppType. Callers (the future WS dispatch layer) distinguish refusal cases via errors.Is and map each sentinel to its dotted-string wire code at the call site:

ErrUnknownType  -> CodeProtocolUnknownType
ErrUnsupported  -> CodeProtocolUnsupported
View Source
var (
	// ErrInvalidThreadUpdate rejects invalid encoding inputs without exposing data.
	ErrInvalidThreadUpdate = errors.New("protocol: invalid thread update")
	// ErrThreadUpdateMetadataTooLarge reports insufficient repeated metadata budget.
	ErrThreadUpdateMetadataTooLarge = errors.New("protocol: thread update metadata leaves no fragment room")
)
View Source
var ErrInvalidThreadQueryLimit = errors.New("protocol: invalid thread query limit")

ErrInvalidThreadQueryLimit rejects negative limits without exposing input.

Functions

func EncodeThreadChildren added in v0.41.0

func EncodeThreadChildren(env Envelope, r ThreadExpansionRequest, p ThreadChildrenPayload, remaining bool) ([][]byte, error)

EncodeThreadChildren packs an ascending detached candidate prefix. Candidates must be public direct children, strictly ordered by (order,id), after Cursor. remaining is authoritative evidence of rows beyond the supplied candidates. The normalized limit is a hard ceiling including ties. No extras are added. All envelopes together, including marker and reserved stamps, fit the shared cap. Stop before the first row that does not fit, without skipping it. If rows remain but none fits, refuse without completing or advancing. Any encoding failure returns nil, including invalid candidates beyond the selected prefix. Envelope metadata, input ownership and refusal rules match EncodeThreadToolBody.

func EncodeThreadReply added in v0.39.0

func EncodeThreadReply(env Envelope, reply any) ([][]byte, error)

EncodeThreadReply encodes a detached complete query result or terminal failure. Supply a ThreadItemsPayload with Final true, all supplied items and exactly one coverage shape, or a ThreadResetPayload/ErrorPayload. No window limit is applied. Items are batched with Final false, followed by one separate empty final marker. Oversized single-item batches reuse ThreadUpdatePart under TypeThreadItems. Every frame fits the shared reserved stamp budget; terminal frames never fragment. Any error returns nil, never a usable prefix. Content is inert and errors are content-free. Supply InReplyTo and variable ConversationID/SessionID before encoding; preserve them afterwards. Other stamping follows EncodeThreadUpdate. Callers own authorization, semantic item validation and ordered delivery.

func EncodeThreadToolBody added in v0.41.0

func EncodeThreadToolBody(env Envelope, r ThreadExpansionRequest, p ThreadToolBodyPayload) ([][]byte, error)

EncodeThreadToolBody encodes an available detached body and separate marker. Each envelope fits MaxThreadEnvelopeBytes with threadStampBudget reservations; supply variable ConversationID/SessionID and InReplyTo before encoding as in EncodeThreadReply. Missing/private/unavailable/wrong-kind/stale reads must use the existing correlated, content-free thread.query_failed refusal instead. Errors return nil output; content remains inert and inputs are never modified.

func EncodeThreadUpdate added in v0.39.0

func EncodeThreadUpdate(env Envelope, update any) ([][]byte, error)

EncodeThreadUpdate encodes one detached added/changed/append DTO value, without modifying inputs or performing I/O. Type and Payload in env are replaced. Every result is a complete Envelope fitting MaxThreadEnvelopeBytes. Ordinary shape is retained when it fits the reserved stamp budget; otherwise all parts carry assembly metadata. Any error returns nil, never a usable partial prefix.

ID, TS, InReplyTo, EventID, HistoryEntryID and both booleans may be stamped later: maximum serialized widths are reserved even when absent. SessionID and ConversationID must be supplied before encoding and must not grow afterwards. Payload/Type must not change. The relay routing wrapper is outside the cap. Inputs must not be mutated concurrently. Content stays inert and errors contain no input values. Consumers own semantic validation and assembly resource limits.

func IsKnownAppType added in v0.16.0

func IsKnownAppType(env Envelope) error

IsKnownAppType reports whether a decrypted inbound app frame is acceptable: its Type is a known inbound app-frame type (a member of inboundAppTypeSet) and env.PayloadEncrypted is false. Returns ErrUnsupported when env.PayloadEncrypted is true (an unsupported inner-frame feature; docs/protocol-mobile.md § Reserved for v2). Returns ErrUnknownType when env.Type is empty or not in inboundAppTypeSet.

Check order: PayloadEncrypted first, Type second. A frame failing both checks reports as ErrUnsupported — the stricter rejection wins.

IsKnownAppType does not validate Payload contents, ID monotonicity, or TS skew; those are dispatcher concerns.

func NormalizeThreadQueryLimit added in v0.39.0

func NormalizeThreadQueryLimit(limit int) (int, error)

NormalizeThreadQueryLimit defaults omitted/zero limits and clamps positives. Handlers must call it before selecting either window or nonzero catch-up.

Types

type AckPayload

type AckPayload struct{}

AckPayload is the body of a generic "ack" envelope; empty by spec (docs/protocol-mobile.md § Message types).

type AlwaysAllowPayload added in v0.16.0

type AlwaysAllowPayload struct {
	Offered bool     `json:"offered"`
	Rules   []string `json:"rules"`
}

AlwaysAllowPayload describes the bounded rules a permission modal can display for a possible "don't ask again" choice. Both fields are always present.

type ApiRetryPayload added in v0.16.0

type ApiRetryPayload struct {
	ConversationID string `json:"conversation_id"`
	Active         bool   `json:"active"`
	Current        int    `json:"current"`
	Total          int    `json:"total"`
}

ApiRetryPayload is the body of an Envelope whose Type == TypeApiRetry (docs/protocol-mobile.md § api_retry). Binary → phone direction; the wire form of the internal-only turnevent.ApiRetry status peer. Like turn_state it is a coarse conversation-level signal, not turn-scoped, so there is no turn_id. Active is the show (true) / clear (false) edge; Current/Total are the parsed `attempt N/M` counter ({0,0} when claude's counter did not parse). No field carries raw banner or screen text. The bridge (#608) supplies ConversationID because the internal ApiRetry marker carries none.

type AppAPIRequestPayload added in v0.39.0

type AppAPIRequestPayload struct {
	AppID          string            `json:"app_id"`
	ReleaseVersion string            `json:"release_version"`
	Path           string            `json:"path"`
	Query          string            `json:"query,omitempty"`
	Method         string            `json:"method"`
	Headers        map[string]string `json:"headers"`
	Body           string            `json:"body"`
}

AppAPIRequestPayload requests a pinned service API. Headers map permitted lowercase names to strings. Body is standard padded base64 of opaque bytes, including the required empty string for no body, with at most 32768 decoded bytes.

func (AppAPIRequestPayload) MarshalJSON added in v0.39.0

func (p AppAPIRequestPayload) MarshalJSON() ([]byte, error)

MarshalJSON emits the required header object even when Headers is nil.

type AppAssetRequestPayload added in v0.39.0

type AppAssetRequestPayload struct {
	AppID          string `json:"app_id"`
	ReleaseVersion string `json:"release_version"`
	Path           string `json:"path"`
	Navigation     bool   `json:"navigation"`
	Query          string `json:"query,omitempty"`
}

AppAssetRequestPayload requests a pinned public asset with GET semantics. Navigation is native-stamped; false distinguishes subresources from SPA loads. Path and Query preserve escaped URL bytes; an empty Query is omitted.

type AppCancelPayload added in v0.39.0

type AppCancelPayload struct {
	AppID     string `json:"app_id,omitempty"`
	RequestID uint64 `json:"request_id"`
}

AppCancelPayload is shared by client app_cancel and daemon app_cancelled. AppID is omitted for list work and required for asset/API work in both directions. RequestID is the original target in 0..9007199254740991; the acknowledgement's Envelope.InReplyTo names the cancel ID and does not assert mutation rollback.

type AppRemovedPayload added in v0.39.0

type AppRemovedPayload struct {
	AppID    string `json:"app_id"`
	Revision uint64 `json:"revision"`
}

AppRemovedPayload is an unsolicited host-scoped tombstone. Revision is in 1..9007199254740991. Removal does not assert deletion of saved app data.

type AppResponseChunkPayload added in v0.39.0

type AppResponseChunkPayload struct {
	AppID string `json:"app_id"`
	Index uint64 `json:"index"`
	Data  string `json:"data"`
}

AppResponseChunkPayload carries 1..32768 opaque bytes as standard padded base64. Index is consecutive from zero; Envelope.InReplyTo names the original resource request, never the response metadata ID. Producers bound final envelopes to 65519 bytes.

type AppResponseCreditPayload added in v0.39.0

type AppResponseCreditPayload struct {
	AppID     string `json:"app_id"`
	RequestID uint64 `json:"request_id"`
	NextIndex uint64 `json:"next_index"`
}

AppResponseCreditPayload grants one next chunk of the original resource request. RequestID is in 0..9007199254740991; NextIndex is the expected index in 0..255. Credit carries no Envelope.InReplyTo and receives no reply.

type AppResponsePayload added in v0.39.0

type AppResponsePayload struct {
	AppID          string            `json:"app_id"`
	ReleaseVersion string            `json:"release_version"`
	Status         int               `json:"status"`
	Headers        map[string]string `json:"headers"`
	SizeBytes      uint64            `json:"size_bytes"`
	TotalChunks    uint64            `json:"total_chunks"`
	SHA256         string            `json:"sha256"`
}

AppResponsePayload supplies metadata once, with Envelope.InReplyTo naming the original asset/API request. Completion requires the exact decoded SizeBytes, TotalChunks and lowercase whole-body SHA256, including the empty-body digest. Assets allow 8388608 bytes/256 chunks; APIs allow 1048576 bytes/32 chunks.

func (AppResponsePayload) MarshalJSON added in v0.39.0

func (p AppResponsePayload) MarshalJSON() ([]byte, error)

MarshalJSON emits the required header object even when Headers is nil.

type AppsPayload added in v0.39.0

type AppsPayload struct {
	Revision   uint64            `json:"revision"`
	Items      []HostedAppRecord `json:"items"`
	NextCursor *string           `json:"next_cursor"`
}

AppsPayload replies to the list ID through Envelope.InReplyTo. Revision is the host page sequence in 0..9007199254740991. Items is always an array; NextCursor is required and null at the end of the walk.

func (AppsPayload) MarshalJSON added in v0.39.0

func (p AppsPayload) MarshalJSON() ([]byte, error)

MarshalJSON emits an empty array for a page without items.

type ArchiveConversationPayload added in v0.16.0

type ArchiveConversationPayload struct {
	ConversationID string `json:"conversation_id"`
}

ArchiveConversationPayload is the body of BOTH archive_conversation and unarchive_conversation frames (docs/protocol-mobile.md § archive). Phone → binary. The two verbs are a symmetric toggle of one durable flag — archive sets IsArchived, unarchive clears it — so one id-only payload serves both. The value-typed ConversationID mirrors DeleteConversationPayload / PromoteConversationPayload; deliberately NOT a reuse of DeleteConversationPayload (semantic coupling / false dependency).

type AssistantDeltaPayload added in v0.15.0

type AssistantDeltaPayload struct {
	ConversationID  string `json:"conversation_id"`
	TurnID          string `json:"turn_id"`
	Seq             int    `json:"seq"`
	ParentToolUseID string `json:"parent_tool_use_id"`
	Text            string `json:"text"`
}

AssistantDeltaPayload is the body of an Envelope whose Type == TypeAssistantDelta (docs/protocol-mobile.md § assistant_delta). Binary → phone direction; an incremental, coalesced chunk of assistant text. Seq is a per-turn, non-negative delta-ordering counter that resets each turn (distinct from the session-monotonic Envelope.ID).

ParentToolUseID names the Agent call that produced attributed text and is empty for main-thread text. It has ToolUsePayload.ParentToolUseID's exact grouping-hint-not-a-capability semantics: clients may join it to a parent ToolUseID for display, but must not treat a match as authority. The key has no omitempty so the main-thread value is always emitted as an empty string.

type AttachmentChunkPayload added in v0.16.0

type AttachmentChunkPayload struct {
	// ConversationID names the conversation the bytes belong to. Meaningful on
	// the UPLOAD leg only; the retrieval leg emits it empty and a receiver
	// ignores it. A lookup key validated against the daemon's registry before it
	// becomes a path component, never a value trusted as sent, and naming a
	// conversation is not authorization. CONTAINMENT IS THAT VALIDATION AND NEVER
	// THE 64-BYTE CEILING — MaxAttachmentIDBytes budgets this field for the
	// envelope arithmetic and describes no shape, the same distinction its own
	// block draws for AttachmentID. Its canonical shape is conversations.ValidID's
	// lowercase UUIDv4, and like AttachmentID it is LOGGABLE ONLY AFTER THAT SHAPE
	// IS VALIDATED. First, matching RequestAttachmentPayload and
	// AttachmentOfferedPayload, whose fixtures' key order this frame's now shares.
	ConversationID string `json:"conversation_id"`

	AttachmentID string `json:"attachment_id"` // the transfer this chunk belongs to; repeated on every chunk
	Index        int    `json:"index"`         // 0-based position in [0, TotalChunks); decides where the bytes land
	TotalChunks  int    `json:"total_chunks"`  // chunk count for the whole attachment, >= 1, identical on every chunk
	Filename     string `json:"filename"`      // inbound the client's own name, outbound the sanitised component the bytes are stored under; display + sanitiser input, never a path
	MimeType     string `json:"mime_type"`     // inbound the client's declared type, outbound sniffed from the stored bytes; a hint, never a verified property
	Size         int64  `json:"size"`          // declared byte length of the WHOLE file, not of this chunk
	SHA256       string `json:"sha256"`        // lowercase hex sha256 of the WHOLE file; always 64 hex characters
	Data         []byte `json:"data"`          // this chunk's raw bytes; base64 on the wire, content-bearing, never logged
}

AttachmentChunkPayload is the body of an Envelope whose Type == TypeAttachmentChunk (docs/protocol-mobile.md § Attachments, published by #1751). One slice of one attachment's bytes, plus the whole transfer's metadata repeated on every chunk. Wire vocabulary only — no producer, no consumer and no validator ship with it; TypeAttachmentChunk's block names the slice that builds each leg.

BOTH DIRECTIONS RIDE THIS ONE TYPE: upload (client → daemon) and retrieval (daemon → client) share it. That is the settled mechanism that stops the two legs drifting once they are built months apart — there is no second shape to keep in step — and it is what makes the SECURITY block below load-bearing, because the trust level of every field depends on a direction the struct cannot report.

Field contracts, which are the whole surface the blocked slices code against:

  • ConversationID names the conversation the bytes belong to, and is MEANINGFUL ON THE UPLOAD LEG ONLY (#2142). Outbound it is emitted empty and a receiver ignores it: a retrieval chunk is correlated by InReplyTo to a RequestAttachmentPayload that already named the conversation, which is the same reason AttachmentStoredPayload and HistoryPagePayload carry none. Inbound it is a LOOKUP KEY VALIDATED AGAINST THE DAEMON'S REGISTRY BEFORE IT BECOMES A PATH COMPONENT, never a value trusted as sent, and NAMING A CONVERSATION IS NOT AUTHORIZATION — RequestAttachmentPayload's block carries that rule in full and this field adopts it rather than restating it. #2143 is what enforces it: handleAttachmentChunk gates the id through the daemon's KnownConversation membership check on EVERY chunk, before the intake and before attachments.EnsureDir joins it into a path.
  • AttachmentID identifies the attachment this chunk belongs to. Every chunk of one transfer repeats it: it is the key an in-flight upload accumulates under (#1741) and the identifier that later resolves to a path on the host (#1743, #2037).
  • Index is the 0-based position of this chunk within the attachment, in [0, TotalChunks). It decides WHERE THE BYTES LAND, so a receiver addresses by it rather than appending.
  • TotalChunks is how many chunks the whole attachment splits into: >= 1, and identical on every chunk of one transfer. A receiver knows the expected count from the first chunk, which is why this frame needs no completion peer of DebugBundleDonePayload. ">= 1" is a shape constraint and NOT a sufficient bound — see the allocation rule below.
  • Filename is a display string and a sanitiser input, never a path, on either leg. Inbound it is the client's own name for the file; outbound it is the sanitised single path component the bytes are stored under, since attachments.Store hands the client's string to SanitizeFilename and keeps only the result — never the client's own bytes.
  • MimeType is a display hint and not a verified property of the bytes, on either leg, and never something to dispatch on in a way that grants the content privileges. Inbound it is the client's declared media type; outbound it is sniffed from the stored bytes, because the declared value is never stored at all — attachments.Store takes a directory, a filename and the data, so there is nothing to echo.
  • Size is the declared byte length of the WHOLE FILE, not of this chunk. int64 mirrors os.FileInfo.Size(); a receiver checks it against the assembled length.
  • SHA256 is the lowercase hex sha256 of the WHOLE FILE, not of this chunk — always 64 hex characters, the representation internal/devices' HashToken already produces and documents.
  • Data is this chunk's raw bytes. []byte auto-encodes as standard base64 via encoding/json, exactly as DebugBundleChunkPayload.Data does. The per-chunk size bound that keeps a frame inside the AEAD cap is #1753's, not a constant here.

No field carries omitempty, for SessionErrorPayload's recorded reason: every field is always present in both directions, so #1753's fixtures pin the full shape. An omitempty added later for tidiness would silently change the wire.

Index and TotalChunks are plain int, not uint32, deliberately. Unsigned would make a negative index structurally impossible, but it would move that rejection into encoding/json's decode error and split ONE reject class ("out-of-range chunk index", #1741) across two layers and two wire codes. Plain int keeps the whole range check in one place — #1741's guard is Index < 0 || Index >= TotalChunks, table-drivable over negative and too-large alike — and it matches the package convention (DebugBundleChunkPayload.Seq, DebugBundleDonePayload.Total). The same holds for a negative Size.

The fields are named Index / TotalChunks, not Seq / Total. Seq on the bundle stream carries a strict succession contract (the next chunk's Seq must equal the count of chunks already seen); this frame does not — a receiver addresses by index and rejects duplicates and out-of-range values rather than requiring succession — so naming the field Seq would import that contract by association. TotalChunks rather than Total because Size sits on the same struct, and a bare "total" beside a "size" reads as a byte count.

THE FRAME CARRIES A conversation_id SINCE #2142, and the omission it replaces was published as a security property for four tickets. That argument — an upload lands in the conversation the authenticated v2 session is already on, so naming one could only let a client steer bytes elsewhere — is reversed here rather than qualified, because what it bought was never isolation between conversations. It was the absence of a field, and it cost two misfiles: an attachment added before a conversation's first message could not be stored at all (the follow-active cursor is stamped only by a successful send_message route, so on a never-messaged conversation it is empty), and a client that sent in A, sent in B and returned to A filed its bytes under B.

The trust level is unchanged by publishing it. A paired client can already name any conversation on SendMessagePayload and can already fetch any conversation's file with RequestAttachmentPayload; what bounds a paired but hostile client is CONFINEMENT — the registry validation and attachments.EnsureDir refusing an escaping directory — and that does not move. Naming a conversation is not authorization, here as there.

The retrieval verb's own conversation_id and this one now do the same kind of work: that one selects which conversation's file to read, this one decides which conversation an upload is filed under (#2143). Both are lookup keys validated against the daemon's registry before they reach a path join, under the one rule. RequestAttachmentPayload's block records what is left of the contrast.

SECURITY: on the INBOUND leg every field is an unverified CLAIM, not a fact — ConversationID included, and it is the claim with the largest blast radius since #2143 acted on it, because it decides WHERE the bytes land. OUTBOUND every field but one is daemon-authored (ConversationID trivially so: the daemon emits it empty), and none of the content metadata is a stored client string echoed back verbatim — nothing a client declares is kept, so the daemon derives what it did not store. That improves their PROVENANCE, not their TRUSTWORTHINESS, and the difference is the whole of this paragraph: docs/protocol-mobile.md § Attachments, "Trust and content hygiene", draws it the same way. One type carries both legs and nothing in it reports which direction a value came from, so a consumer must decide that from where it received the frame.

AttachmentID IS THE EXCEPTION to "daemon-authored". Nothing daemon-side mints one — the client supplies it on every chunk of an upload, attachments.EnsureDir makes it a directory name, and retrieval echoes that same value back byte-identical (internal/relay's attachmentEnvelopes copies what StreamAttachment was handed). So it is client-chosen text on BOTH legs, constrained only by the canonical-shape check below, and that check therefore binds A RECEIVING CLIENT TOO: an id read off an outbound frame is no more path-safe than one read off an inbound one.

PROVENANCE DOES NOT MAKE A VALUE SAFE TO ACT ON. A sniffed text/html is exactly as dangerous to render as a declared one, and a sanitised filename is still attacker-shaped text, so § Attachments keeps every client obligation binding on both legs: sanitise Filename before rendering it, never use it as a path or a filesystem name unsanitised, and NEVER DISPATCH ON MimeType in any way that grants the content privileges. What the derived MimeType does buy is narrower — it is drawn from a closed set of daemon-authored constants (attachmentEnvelopes carries the reasoning), so it can carry neither the log-injection nor the envelope-budget hazard an arbitrary declared string can. That is a property of the value and NOT a slackening of MaxAttachmentMimeTypeBytes, which budgets the inbound leg regardless.

Filename, Size and SHA256 are the claims a reader expects. AttachmentID, Index and TotalChunks are claims too, and theirs is the falsification that actually costs something: TotalChunks is what a receiver would size an accumulator from, Index decides where bytes land (a duplicate or out-of-range value corrupts or escapes the buffer), and AttachmentID keys the in-flight upload and later resolves to a path on the host.

NEVER ALLOCATE FROM A CLAIM. TotalChunks and Size are attacker-chosen integers: make([][]byte, TotalChunks) or make([]byte, Size) on a claimed TotalChunks of 2^31-1 is a multi-gigabyte allocation driven by a single ~60 KB frame, and it is the cheapest attack this frame offers. A receiver range-checks both BEFORE sizing anything, and the two numbers cross-check each other for free: given #1753's published per-chunk raw bound, TotalChunks must equal max(1, ceil(Size / bound)), and both must be within the receiver's own limits. The max(1, …) is not decoration — a bare ceil(Size / bound) is WRONG at Size == 0, where it demands 0 chunks against the documented TotalChunks >= 1. That check is available from the FIRST chunk, before a single byte is accumulated, and attachments.CheckDeclaration is where it runs.

THE RULE DOES NOT LAPSE OUTBOUND, where the two integers are daemon-authored: § Attachments obliges a client to bound what it allocates from a received Size and TotalChunks against its own memory budget and to refuse a transfer larger than it can hold rather than attempt it. The daemon is trusted there, but a fixed-budget client still has a budget.

AttachmentID is validated for canonical shape BEFORE it is used as a path component. It resolves to a file on the host in #1743 and #2037, and a client-chosen id reaching filepath.Join unvalidated is a traversal; conversations.ValidID is the existing canonical-shape precedent, and the deterministic check lands in #1741 / #1743. The id is also NOT a capability: not secret, not unguessable, and never the only thing standing between a caller and a file.

Data is CONTENT-BEARING and NEVER LOGGED — a stronger rule than the one DebugBundleChunkPayload carries, because those are daemon-authored diagnostics and these are a user's own private file bytes. Filename gets the same treatment for two independent reasons: a filename is often private in itself, and a client-supplied string in a line-oriented log is a log-injection shape. Log the attachment id, the index and the total; never the bytes, and never a raw filename. #1744 enforces it. SANITISING DOES NOT LIFT THE RULE, so the retrieval leg's filename is no more loggable than the upload leg's: attachments.SanitizeFilename's own doc block records that its output can forge no log line but that the privacy reason stands untouched.

SHA256 is INTEGRITY, NOT AUTHENTICITY. The same party supplies the bytes and the digest, so a match proves the transfer was not corrupted and proves nothing about whether the content is safe. It must not become an access token either: content-addressed retrieval ("know the hash, fetch the blob") would promote a non-secret claim into a capability. The canonical form is lowercase hex compared for EXACT EQUALITY against a digest the receiver renders the same way — a case-insensitive or prefix comparison is a hole, and a comparison that rejects an uppercase-sending client is an availability bug.

type AttachmentOfferedPayload added in v0.16.0

type AttachmentOfferedPayload struct {
	// ConversationID names the conversation the file belongs to, and is the whole
	// of this frame's correlation. Daemon-asserted; a client FILTERS on it, since
	// the frame is delivered to every attached client rather than routed to one —
	// ModalShownPayload.ConversationID's posture exactly.
	ConversationID string `json:"conversation_id"`

	// AttachmentID names the file, and is the id a client passes back in a
	// RequestAttachmentPayload to fetch the bytes. Daemon-asserted, and the first
	// id on this wire the client did not mint; it obeys § Attachments' published
	// attachment_id shape. Not a capability, and receiving it grants nothing —
	// #2054 re-validates it against the daemon's registry regardless.
	AttachmentID string `json:"attachment_id"`

	// Filename is the file's name for display, and it is claude-AUTHORED — the
	// one field here that is not daemon-asserted, and the reason § Security
	// model's threat 1 lands on this frame. Display text, NEVER a path or any part
	// of one, never evidence of what the bytes are, and never logged raw. At most
	// MaxAttachmentFilenameBytes, documented rather than checked here.
	Filename string `json:"filename"`
}

AttachmentOfferedPayload is the body of an Envelope whose Type == TypeAttachmentOffered (docs/protocol-mobile.md § Attachments, published by #2082). The frame that tells a client a file exists on the host for a conversation — the first thing on this wire to hand a client an attachment_id IT DID NOT MINT. Wire vocabulary only — nothing constructs, decodes or validates it here; #2083 emits it.

ONE DIRECTION ONLY, binary → phone, so there is no leg on which these fields mean something else. AttachmentChunkPayload rides both legs and nothing in it reports which direction a value came from, which is why its SECURITY block has to make a consumer decide trust from where the frame arrived. Here the direction is fixed — but that does NOT make the payload uniformly trusted, and the difference from AttachmentStoredPayload is the whole of the PROVENANCE paragraph below.

NO BYTES RIDE THIS FRAME. It announces; it does not deliver. A client that wants the file asks with RequestAttachmentPayload (#2052) and receives AttachmentChunkPayload frames (#2053). "Offered" rather than "sent" is the name carrying that, and a reader who takes this frame for a delivery looks for a data field that does not exist.

CORRELATION IS ConversationID AND NOTHING ELSE, following ModalShownPayload — the precedent with the same origin, since a permission prompt also begins as an MCP tool call from claude, arrives over the control socket, and is broadcast to attached clients from the control-server handler goroutine. There is no InReplyTo either: nothing solicits this frame, so there is no request envelope to name, which is the difference from AttachmentStoredPayload's outbound-but- correlated shape.

THERE IS NO turn_id, AND THE OMISSION IS A PROPERTY RATHER THAN AN OVERSIGHT. It is the field a reader reaches for first and it is NOT REACHABLE FROM THAT LANE: a turn id is private state on the interactive turn emitter, minted at turn start, and nothing on the control path references it. Publishing one here would either oblige the producer to build a seam nobody has asked for or ship a field that is empty in practice. The consumer does not need it — a client timeline already appends items carrying no turn id at all, its own user messages and session boundaries among them, in arrival order. TestAttachmentOfferedPayload_WireKeys pins the key set so this is checked rather than reviewed.

PROVENANCE IS PER FIELD, and copying AttachmentStoredPayload's blanket "every field is daemon-asserted" across this shape would be false. The two ids are daemon-asserted; FILENAME IS claude-AUTHORED. That is the same rule QuestionShownPayload publishes for its four strings, and the same trap QuestionDismissedPayload's outcome exists to avoid — a subprocess-authored string published under a trusted provenance is rendered by a client as trusted chrome.

SO § Security model's THREAT 1 (PROMPT INJECTION) LANDS ON THIS FRAME, in the INVERSE DIRECTION from SendMessagePayload's AttachmentIDs. Those are client-authored and flow INTO claude; this one flows OUT OF claude toward a client's render surface, which is QuestionShownPayload's direction. #2083 takes the name from the model's own tool call. Every § Attachments obligation on Filename therefore binds unchanged — SANITISE BEFORE RENDERING, NEVER USE AS A PATH OR ANY PART OF ONE, NEVER TRUST AS A DESCRIPTION OF THE BYTES — since a sanitised filename is still attacker-shaped text. Two consequences are worth naming because a client can honour the letter and break the spirit: AN EXTENSION IS NOT EVIDENCE OF CONTENT, so choosing a viewer or a handler from ".html" or ".svg" here is dispatching on a claude-authored string, the hazard MimeType's never-dispatch rule names one field over; and the name is not a claim about what the bytes are. Whether the producer sanitises before announcing is #2083's to decide and changes none of this.

FILENAME IS NEVER LOGGED RAW, SO THIS FRAME IS NOT SAFE TO LOG WHOLE. The rule is stated positively because the natural reading is the opposite one: AttachmentStoredPayload is published as safe to log whole precisely BECAUSE it carries no filename, and it is this frame's nearest sibling, so a reader carries that verdict over and logs a subprocess-authored string verbatim. AttachmentChunkPayload puts the rule on Filename for two independent reasons — a filename is often private in itself, and a string in a line-oriented log is a log-injection shape — and here BOTH ARE STRONGER: nothing on this path strips control characters or terminal escape sequences. The two ids stay loggable once their shape is validated, the family's existing rule.

RECEIVING THIS FRAME IS NOT A CAPABILITY. The id is not secret and not unguessable, and #2054 re-validates it against the daemon's own registry regardless of what was announced, so an announcement grants nothing an unannounced id would not already have. What is genuinely new is that a client learns an id it did not mint, widening what it knows from "files I uploaded" to "files this conversation holds" — safe for a stated reason rather than an assumed one: the frame is DELIVERED TO EVERY ATTACHED CLIENT RATHER THAN ROUTED TO ONE, scoped by ConversationID at the consumer exactly as ModalShownPayload is, every attached client is a paired device, and § Attachments makes PAIRING the authorization boundary with no per-verb gate. The disclosure is to exactly the tier that could already ask.

A HOSTILE OR TRUNCATED PAYLOAD DECODES TO THE ZERO VALUE, NOT TO AN ERROR, since every key is optional to encoding/json — both siblings record the same property. The result is three empty strings, none of which is valid under any published shape, so a consumer must resolve NOTHING from them. The failure this warns about is silent and specific, and RequestAttachmentPayload names it: filepath.Join(dir, "") is dir, so a consumer that skips the shape check and joins the zero value addresses the conversation directory root rather than erroring.

NO omitempty AND NO MarshalJSON. All three fields are always present in the one direction this frame travels, so a decoder may rely on all three; TestAttachmentOfferedPayload_ZeroValue_KeysPresent is the pin, and an omitempty added later for tidiness would silently change the wire. There is no slice field, so QuestionShownPayload.MarshalJSON's nil→[] backing-array argument does not transfer — do not add one by analogy.

NOTHING HERE ENFORCES ANY OF IT, the posture all three siblings ship with: internal/protocol declares shapes and validates none. The two ceilings the published section names are documented rather than checked — AttachmentID obeys § Attachments' attachment_id shape (MaxAttachmentIDBytes is a ceiling for attachment_chunk's envelope arithmetic and NOT that shape), and Filename is bounded by MaxAttachmentFilenameBytes rather than by a second filename rule — and enforcing them belongs to the producer and to each consumer. The producer's half is not cosmetic: unbounded, a claude-authored 100 KB name makes the DAEMON'S OWN outbound frame exceed the envelope cap and be dropped, the self-inflicted availability bug MaxAttachmentFilenameBytes' block already records for the retrieval leg.

THE ALLOCATION HAZARD AttachmentChunkPayload WARNS ABOUT IS ABSENT BY SHAPE: there is no count and no length field here, so NEVER ALLOCATE FROM A CLAIM has nothing to bite on. Stated so the absence reads as a property of the shape rather than as an omission. Whether one turn may offer several files, and any limit on that, belongs to the producer and is learned by being rejected — the #1752 rule against publishing a figure ahead of the code that enforces it.

type AttachmentStoredPayload added in v0.16.0

type AttachmentStoredPayload struct {
	// AttachmentID is the attachment that was stored: the client's own id,
	// repeated on every chunk of the upload and echoed back here. A client
	// matches on it and concludes nothing when it does not recognise the value.
	// Its canonical shape is conversations.ValidID's, published by #1895 —
	// MaxAttachmentIDBytes is a ceiling for the cap arithmetic and not that
	// shape.
	AttachmentID string `json:"attachment_id"`
}

AttachmentStoredPayload is the body of an Envelope whose Type == TypeAttachmentStored (docs/protocol-mobile.md § Attachments, published by #1895). The upload leg's success reply: the transfer completed, its claims were checked, and the bytes are on the host addressable by this id. Wire vocabulary only — nothing constructs, decodes or validates it here; #1897 emits it.

ONE DIRECTION ONLY, binary → phone, which is the whole difference from the frame it answers. AttachmentChunkPayload rides both legs and nothing in it reports which direction a value came from, so its SECURITY block has to make a consumer decide trust from where the frame arrived. Here there is nothing to decide: every field is daemon-asserted, and § Attachments publishes a provenance column saying so.

ONE FIELD, and the id is the CLIENT'S OWN, echoed back. Nothing daemon-side mints an attachment id — the client supplies it on every chunk, attachments.EnsureDir validates its shape before it becomes a path component, and storage keys by it. So "tie the reply to the upload" and "name the attachment that was stored" are the same value, carried once. A second daemon-side handle would be a new identifier with no minting site, no lifecycle and no consumer. The daemon asserts nothing here it did not verify.

Correlation to the request rides the envelope's InReplyTo, not a field, which is why there is no request-id key: TypeAttachmentStored's block has that decision, and the sibling shape is SessionSettingsUpdatedPayload, which likewise carries only the id it confirms. That block also records WHICH chunk InReplyTo names — the one whose arrival completed the transfer, not the highest index — and therefore why this id is the match key a client can actually predict.

WHAT IS DELIBERATELY ABSENT, since every omission here is a decision:

  • No host path, no directory component and no on-disk filename. EnsureDir returns a symlink-resolved absolute path and the natural implementation of "name the attachment that was stored" reaches for it; docs/protocol-mobile.md § Error codes already forbids attachment.storage_failed from carrying the host path or the underlying filesystem error, either of which discloses the daemon's layout, and a success frame leaking what the failure frame is guarded against would undo that mitigation from the other side. TestAttachmentStoredPayload_WireKeys pins the key set so this is checked rather than reviewed.
  • No stored filename in particular. attachments.SanitizeFilename's doc block records that its result is neither unique nor an identifier — distinct client names collide, and a case-insensitive host folds them further — so echoing it would hand a client something it cannot rely on. Retrieval addresses by attachment id — RequestAttachmentPayload names one, #2052 — and the client already knows the name it sent. Keeping it out also keeps this frame clear of the NEVER LOGGED rule AttachmentChunkPayload puts on Filename, SHA256 and Data: this payload carries none of the three and is safe to log whole.
  • No conversation_id. The ABSENCE is unchanged by #2142 giving AttachmentChunkPayload one; the reason it used to borrow is not. A client holding the transfer already knows the conversation — it named one on every chunk of the upload — so echoing it back confirms nothing, which is the same ground the size / sha256 / total_chunks bullet below stands on. This frame was never the one that could steer anything.
  • No size, sha256 or total_chunks. The client sent all three and they were checked against the assembled bytes before this frame can be emitted; echoing them back confirms nothing a client could act on.

No omitempty and no MarshalJSON. The field is always present in the one direction this frame travels, matching QuestionDismissedPayload; and there is no slice field, so there is no nil→[] normalisation to perform and QuestionShownPayload.MarshalJSON's backing-array data-race argument does not transfer. Do not add one by analogy.

SECURITY: receiving this frame IS NOT A CAPABILITY. The id is not secret, not unguessable, and never the only thing standing between a caller and a file — AttachmentChunkPayload's doc states that, and CodeAttachmentNotFound's deliberate merge is what keeps retrieval from becoming a path-existence oracle. It is echoed to exactly the authenticated session that uploaded the bytes, so disclosure widens nothing. A decode of a truncated or hostile payload yields the zero value rather than an error, because every key is optional to encoding/json; the empty string is not a valid attachment id under any published shape, so a consumer matching on it resolves nothing. A client receiving an id it does not recognise ignores the frame — the reading QuestionDismissedPayload publishes for an unrecognised batch — and never presents bytes it did not upload.

type BackgroundTask added in v0.16.0

type BackgroundTask struct {
	TaskID          string   `json:"task_id"`
	ToolCallID      string   `json:"tool_call_id"`
	TaskType        string   `json:"task_type"`
	Description     string   `json:"description"`
	TruncatedFields []string `json:"truncated_fields"`
}

BackgroundTask is one daemon-enriched row of a BackgroundTaskRosterPayload. Claude's roster has three text fields; ToolCallID is joined from the same task's retained start in this session and child lifetime. Empty means no retained match, including unseen or forgotten starts.

TruncatedFields names THIS row's cut fields ("task_id", "task_type", "description", "tool_call_id"), null when nothing was cut.

SECURITY: Description carries the same literal command line as BackgroundTaskStartedPayload.Description, under a tighter producer cap (internal/streamsup/parser.go's maxTaskRosterDescription — here it is a label in a list whose length claude chooses, and the full-length copy already crossed the wire on the background_task_started this row joins back to). The render-never-execute warning is repeated rather than delegated because a LIST of command lines is a more tempting shape to feed somewhere structured than a single one.

type BackgroundTaskProgressPayload added in v0.16.0

type BackgroundTaskProgressPayload struct {
	ConversationID  string   `json:"conversation_id"`
	TaskID          string   `json:"task_id"`
	Description     string   `json:"description"`
	SubagentType    string   `json:"subagent_type"`
	LastToolName    string   `json:"last_tool_name"`
	TotalTokens     int      `json:"total_tokens"`
	ToolUses        int      `json:"tool_uses"`
	DurationMS      int      `json:"duration_ms"`
	TruncatedFields []string `json:"truncated_fields"`
}

BackgroundTaskProgressPayload is the body of an Envelope whose Type == TypeBackgroundTaskProgress (docs/protocol-mobile.md § background_task_progress, #2246). Binary → phone direction; the wire form of turnevent.BackgroundTaskProgress, the fourth background-task frame: the other three open a task, report what happened to it, and list what is alive, and this one says a running task is still working and what it is doing right now.

It opens and closes no turn, so like its siblings there is no turn_id, and the bridge supplies ConversationID because the internal event carries none. TaskID is the join key back to the background_task_started that opened the task. claude's session_id and uuid are absent for their sibling's reason, and so is tool_use_id — the join key is task_id and the opening frame already published the tool call.

A SEPARATE FRAME FROM background_task_updated, NOT A WIDER ONE, and the captured field set is what decided it — the opposite call from #2245's, made on the same test. `description` here is the task's CURRENT ACTIVITY, where `description` on background_task_started is the task's OPENING description; carrying two meanings under one name on one task row is a wire-contract trap a client cannot undo. And `subagent_type` and `last_tool_name` describe the AGENT DOING THE WORK, not what happened to the task, which is what background_task_updated reports. No `patch` is synthesized here or anywhere: that field is contractually claude's own bytes.

RATE. The daemon emits at most one of these per **2 tool calls** a task's own counter advances, so fewer frames cross this wire than claude emits lines — on the committed capture, 2 lines became 1 frame. Two consequences a client must not get wrong, and they are thinking_progress's: the frames do NOT enumerate claude's lines, and the ABSENCE of one within any window does NOT mean the task stalled. A third rides the per-task bound: past the daemon's task-cardinality cap a task receives no progress frames at all, and its opening and terminal frames are unaffected, so a silent row still opens and closes correctly.

TotalTokens, ToolUses and DurationMS are claude's own readings off the emitting line, carried verbatim. CUMULATIVE PER TASK, so two frames for one task carry growing values and MUST NOT be summed — diff them if a rate is wanted. They are not guaranteed monotonic either: a client that subtracts two readings must tolerate a negative result. The daemon accumulates nothing, so no number here is arithmetic it did.

TruncatedFields names the cut fields ("task_id", "description", "subagent_type", "last_tool_name"), null when nothing was cut. The three integers can never appear in it: nothing cuts an int.

SECURITY: Description is model-authored FREE TEXT with no documented length bound, and it is the field this frame exists to carry. Both captured values NAME A FILE the subagent is reading, so in practice a stream of these frames is a stream of path fragments from the operator's host — even though claude's documented path-shaped key is not present on this subtype at all. A client must not read it as a safe label. SubagentType and LastToolName are short model- and tool-authored tokens under the same rule; a short token today is not a guarantee about tomorrow's. Render all three as INERT TEXT; never execute, re-shell, or feed them to an HTML sink, an attribute, or a URL — the sibling warning at BackgroundTaskUpdatedPayload.Summary applies verbatim, and this frame repeats it rather than delegating because these values arrive REPEATEDLY for one row, which is the shape a client is most likely to bind straight into a template. All bounds are the producer's, decided at construction (internal/streamsup/parser.go's maxTaskFieldID / maxTaskDescription), so this struct re-decides no maximum.

type BackgroundTaskRosterPayload added in v0.16.0

type BackgroundTaskRosterPayload struct {
	ConversationID string           `json:"conversation_id"`
	Tasks          []BackgroundTask `json:"tasks"`
	DroppedTasks   int              `json:"dropped_tasks"`
}

BackgroundTaskRosterPayload is the body of an Envelope whose Type == TypeBackgroundTaskRoster (docs/protocol-mobile.md § background_task_roster, #1394). Binary → phone direction; the wire form of turnevent.BackgroundTaskRoster, the aggregate peer of the two scalar frames: they report what happened to ONE task, this reports what is alive at one moment. A SNAPSHOT, not a delta. Not turn-scoped, and the bridge (#1394) supplies ConversationID because the internal event carries none.

Tasks is in claude's own order, truncated from the tail by the producer. An EMPTY roster is meaningful and is still sent: it says nothing is alive, which is exactly the signal a consumer of #1240's symptom needs. The key is therefore always present on the wire and never null — see MarshalJSON.

DroppedTasks is how many entries claude sent beyond the producer's entry cap (internal/streamsup/parser.go's maxTaskRosterEntries) that this frame does NOT carry; 0 when nothing was dropped, so the roster's true size is len(Tasks) + DroppedTasks. The count reports here rather than as a name in a top-level truncated_fields — which is why this payload has none — because a name-only report loses HOW MANY were lost, and each dimension reports where it is decided: a text cut is a property of one entry and rides that entry.

func (BackgroundTaskRosterPayload) MarshalJSON added in v0.16.0

func (p BackgroundTaskRosterPayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Tasks to an empty array, so an empty roster always serialises as "tasks":[] and never as "tasks":null.

This was the file's first custom marshaller (ToolUsePayload's is the second, #1678, and follows this one), and the deviation is deliberate. omitempty is out — eliding the key would erase the frame's whole point, since an empty roster is a POSITIVE statement rather than an absence. Between null and [], [] is the better client contract: it reads as an empty list where null reads as absent/unknown, and a client decoding into a non-optional array type never has to branch. Protocol shapes are expensive to change once a client has shipped against one, so the better shape is worth the nine lines now.

A doc comment would not have been enough. turnevent.BackgroundTaskRoster.Tasks is nil both for an empty roster and when claude omits the key, so the bridge (#1394) mapping it straight through would hand this type a nil slice; without this method that would ship null to a phone while the empty-roster fixture went on asserting [], and nothing in `make check` would notice.

truncated_fields is deliberately NOT normalised the same way: nil and [] say the identical thing there ("nothing was cut") and no consumer branches on the difference, whereas tasks is the frame's subject and its empty value is the signal.

Value receiver, so it applies to the value form the round-trip and the bridge both take, and so the substitution lands on a copy rather than on the caller's slice. The type alias is the standard indirection that keeps json.Marshal from recursing back into this method.

type BackgroundTaskStartedPayload added in v0.16.0

type BackgroundTaskStartedPayload struct {
	ConversationID  string   `json:"conversation_id"`
	TaskID          string   `json:"task_id"`
	ToolCallID      string   `json:"tool_call_id"`
	Description     string   `json:"description"`
	TaskType        string   `json:"task_type"`
	TruncatedFields []string `json:"truncated_fields"`
}

BackgroundTaskStartedPayload is the body of an Envelope whose Type == TypeBackgroundTaskStarted (docs/protocol-mobile.md § background_task_started, #1394). Binary → phone direction; the wire form of turnevent.BackgroundTaskStarted, which announces that claude started work outliving the turn that spawned it. Not turn-scoped, so there is no turn_id — a background task's lifecycle is orthogonal to its turn, which is the whole #1240 point. The bridge (#1394) supplies ConversationID because the internal event carries none.

ToolCallID is claude's tool_use_id under the name ToolUsePayload and ToolResultPayload already use for the same identifier, so a client joins the three with no vocabulary lookup — and it is the name TruncatedFields reports for the field. claude's session_id is deliberately absent: it is claude's session identity, not the daemon's conversation identity, and no v2 payload carries it.

TruncatedFields names the fields the producer cut to fit their caps, using these wire names ("task_id", "tool_call_id", "description", "task_type"); it is null when nothing was cut. It is load-bearing, not decoration — a payload that dropped it would present claude's truncated text to a phone as complete.

SECURITY: Description is claude's label for the task, and for the local_bash task type it is the LITERAL command line. It is safe to RENDER as inert text and never to execute, re-shell, or feed to an HTML sink, an attribute, or a URL. Its bound is the producer's, decided at construction (internal/streamsup/parser.go's maxTaskFieldID / maxTaskDescription), so this struct re-decides no maximum: a second cap here would be a second place the limit is decided, and the two could disagree silently.

type BackgroundTaskUpdatedPayload added in v0.16.0

type BackgroundTaskUpdatedPayload struct {
	ConversationID  string   `json:"conversation_id"`
	TaskID          string   `json:"task_id"`
	Patch           string   `json:"patch"`
	Status          string   `json:"status"`
	Summary         string   `json:"summary"`
	TruncatedFields []string `json:"truncated_fields"`
}

BackgroundTaskUpdatedPayload is the body of an Envelope whose Type == TypeBackgroundTaskUpdated (docs/protocol-mobile.md § background_task_updated, #1394). Binary → phone direction; the wire form of turnevent.BackgroundTaskUpdated, the peer of background_task_started: that frame opens the task, this one reports what happened to it afterwards. It opens and closes no turn either, so like its sibling there is no turn_id, and the bridge (#1394) supplies ConversationID because the internal event carries none. TaskID is the join key back to the background_task_started that opened the task. claude's session_id is absent for its sibling's reason.

TWO OF CLAUDE'S LINES PRODUCE THIS FRAME (#2245), and they fill DISJOINT fields. system/task_updated fills patch and leaves status and summary empty; system/task_notification fills status and summary and leaves patch empty. A non-empty status is therefore what says a terminal state was reported on this frame, and it is the transition a client needs to close a task row that background_task_started opened. No field names the producing line: that would be content the daemon invented, on a frame whose neighbouring field is contractually claude's bytes alone.

Status is CLAUDE'S REPORT, NOT THE DAEMON'S DETECTION. The daemon does not verify that a task reporting a finish has stopped running, and it has observed exactly one token ("completed"); the documented "failed" and "stopped" states have never been captured. It is a plain string rather than a closed set for that reason.

TruncatedFields names the cut fields ("task_id", "patch", "status", "summary"), null when nothing was cut, and carries the same load as its sibling's. Because the two producing lines fill disjoint fields, one frame's list can only name fields from one of them plus "task_id", which both carry.

SECURITY: Summary is model-authored FREE TEXT with no documented length bound, and this warning is stated here rather than delegated to the sibling section for two reasons. It is the family's SECOND field that can carry a literal command line — BackgroundTaskStartedPayload.Description is the first, and in the one captured task_notification line summary IS the task's command. And unlike patch, which a client is told to treat as an opaque blob, summary is prose a client will actually render, so it reaches an HTML sink by the normal path rather than by a mistake. Render it as INERT TEXT; never execute, re-shell, or feed it to an HTML sink, an attribute, or a URL. Status is a short token today but is claude-authored under the same rule. Both bounds are the producer's, decided at construction (internal/streamsup/parser.go's maxTaskFieldID / maxTaskSummary), so this struct re-decides no maximum.

claude's output_file is deliberately ABSENT from this payload. It is documented as a path on the operator's host, and it is not merely unset here — it is never decoded anywhere in the daemon, so no code path holds it. A field that is never declared cannot leak, which is a stronger guarantee than redacting one.

SECURITY: Patch is claude's patch object — what CHANGED about the task — carried WHOLE and unparsed as its serialized text, so nothing here is declared about its contents and no key is enumerated. It is a plain string and NOT json.RawMessage, for UnrecognizedMessagePayload.Raw's reason: the producer truncates it at construction (internal/streamsup/parser.go's maxTaskPatch) and a truncated object is no longer valid JSON, so typing it as raw JSON would be a lie and would break marshalling. A consumer MUST NOT assume it parses, must render it as inert text, and must never feed it to an HTML sink, an attribute, a URL, or anything that executes or re-shells it — a patch's structured shape makes it the more tempting thing to feed somewhere that runs it, and its sibling's Description already carries a literal command line.

The producer also scrubs invalid UTF-8 with an EMPTY replacement and reports the cap cut ONLY, so Patch can differ from claude's bytes without appearing in TruncatedFields. That is a stated limitation of the upstream producer, not of this type.

type BannerPayload added in v0.16.0

type BannerPayload struct {
	ConversationID string `json:"conversation_id"`
	// Level is claude's own key, adopted VERBATIM — the one field here that keeps
	// claude's spelling, where text and stops_turn are renames. It is consequently the
	// one word a vocabulary pin on this frame may NOT check for, the trap
	// TestSlashCommandListType_IsNotClaudesVocabulary records for `commands`.
	//
	// An OPEN SET, on TurnEndPayload.Outcome's rule: treat an unrecognised token as
	// unknown rather than as an error, because claude may ship one at any time.
	// `warning` is the OBSERVED value (claude 2.1.259, the single informational line in
	// the committed operator_system_lines capture); `info`, `notice` and `suggestion`
	// are claude's other DOCUMENTED values for the key and have not been observed on
	// this repo. The two groups are named separately on purpose — presenting four as a
	// set this repo has seen would overstate the evidence.
	//
	// BOUNDED BY THE PRODUCER AND DROPPED RATHER THAN CUT, which is the opposite answer
	// text beside it gets, and the pairing is the trap worth naming on this frame:
	// CompactionBoundaryPayload.Trigger argues it in full. This is a token a client
	// MATCHES, where a cut token matches no known value while still looking like one;
	// text is prose, where a cut sentence still reads as what it is. Empty means claude
	// named no level this client can be offered — either it sent none, or the daemon
	// dropped an oversized one. The drop is not reported and needs none: an emptied
	// scalar is directly observable.
	Level string `json:"level"`
	// Text is claude's `content`, renamed — the field this frame exists to carry. The
	// rename is half of the translation layer the vocabulary pin holds: `content`
	// beside `level` would read as the frame's own body rather than as what claude
	// printed.
	//
	// BOUNDED AT 4 KiB BY THE DAEMON, at the PRODUCER (#2319), and CUT rather than
	// dropped. The bound is stated here as the contract THAT ticket owed rather than as
	// a fact this package enforces: the enforcing constant is streamsup's maxBannerText,
	// landed beside maxCompactTrigger and maxDenialProse, on this repo's standing division
	// that claude's text is bounded where it crosses the subprocess boundary. This
	// shape and the bridge re-decide no maximum — a second cap site is a second place
	// the limit is decided and the two could disagree silently, which is the rule
	// ToolDeniedPayload's doc states.
	//
	// SECURITY: claude-authored text, bounded by the daemon and NOT sanitized, so
	// CompactingPayload.ErrorText's SECURITY paragraph applies for provenance — the
	// render boundary owing control-character and terminal-escape stripping is the
	// CLIENT's. IT APPLIES FOR SHAPE TOO, and this is the RISKIER half of the pair
	// CompactionBoundaryPayload.Trigger is the safer half of. Newlines, terminal
	// escapes, markup, a URL and text impersonating daemon chrome all fit inside 4 KiB,
	// and the observed line contains a host filesystem path and echoes the operator's
	// own prompt back. Never an HTML sink, an attribute or a URL.
	Text string `json:"text"`
	// Truncated says whether the daemon cut text to fit the bound above. It is the
	// PRODUCER's answer carried verbatim, never one the bridge recomputed from the
	// string's length: a second authority on the same fact is a second place it can be
	// decided differently.
	//
	// There is no companion dropped_fields slice, unlike ToolDeniedPayload's pair, and
	// none is owed. text is the only field the daemon cuts, so one bool names it
	// unambiguously — that frame needs a slice because it has six candidate fields —
	// and an emptied level is directly observable, exactly as
	// CompactionBoundaryPayload.Trigger's unreported drop is.
	Truncated bool `json:"truncated"`
	// StopsTurn is claude's `prevent_continuation`, renamed. It says claude will not
	// continue past this banner; the observed value is true, on a hook that refused a
	// prompt.
	//
	// A REPORT, NEVER AN ACTUATOR, and the constraint is restated here rather than left
	// to the type's doc because THIS FIELD'S NAME IS WHAT INVITES THE MISTAKE. It reads
	// like a lever, and a daemon that ever keyed a teardown, a retry suppression or a
	// queue decision on it would hand claude a self-service turn abort — a fabricated
	// line stopping work the operator asked for. A CLIENT owes the same restraint:
	// render it, do not let it cancel anything the operator did not cancel.
	StopsTurn bool `json:"stops_turn"`
}

BannerPayload is the body of an Envelope whose Type == TypeBanner (docs/protocol-mobile.md § banner, #2256). Binary → phone direction; the wire form of turnevent.Banner. Like compacting and unrecognized_message it is conversation-scoped rather than turn-scoped, so there is no turn_id.

THE ABSENT turn_id IS FORCED BY THE PRODUCER SET, not chosen for symmetry with those two. A prompt a hook refuses is never answered, so no turn exists to attribute the refusal to; a notification belongs to claude's own queue and rides no turn at all. There is no turn the daemon could honestly name, and naming one anyway would attach operator-facing text to work it did not come from.

EVERY FIELD IS claude's, AND SO IS THE FACT OF THE BANNER — CompactionBoundaryPayload's class change, landing somewhere sharper. That frame at least reports a compaction the daemon can corroborate from its own parser state; this one reports that claude had something to say, which nothing else on the wire confirms or contradicts.

IT IS THE FIRST FRAME HERE WHOSE WHOLE PURPOSE IS ARBITRARY claude-AUTHORED PROSE with no machine state anchoring it, and that is a class change rather than another prose field. CompactingPayload.ErrorText is prose attached to a compaction the daemon observed; UnrecognizedMessagePayload.Raw is prose explicitly labelled a parser gap. A client renders THIS one as a first-class notice, so text impersonating daemon chrome at level "warning" is the realistic abuse rather than a hypothetical one. Render the whole frame as claude's ASSERTION, attributed to claude, never as the daemon's own finding — the trap QuestionDismissedPayload's outcome field exists to avoid — and render Text as inert text on UnrecognizedMessagePayload.Raw's rule.

NOTHING IN THE DAEMON ACTS ON ANY FIELD HERE — no retry, no backoff, no teardown, no routing — which is what keeps a fabricated banner a misleading label rather than an actuator. StopsTurn is where that constraint is most load-bearing and it is restated at the field, because the field NAME is what invites the mistake.

IT CARRIES NO DATA CLASS AN INTERACTIVE GRANT DOES NOT ALREADY RECEIVE, which is why no narrower capability gate exists. The observed text embeds a host filesystem path and echoes the operator's own prompt back, and ToolUsePayload.Input's verbatim top-level fields already carry both to the same grant.

No omitempty on any field, per this file's rule as stated at ToolResultPayload: absence and the zero value mean the same thing, always emitting the key keeps the testdata fixture pinning the full shape, and a client built before this landed ignores the unknown keys. Every field is a value type — two strings and two bools, no pointer and no slice, unlike CompactionBoundaryPayload's counts and ToolDeniedPayload's report slices — so this frame raises no aliasing question at either seam.

type ChangeWorkspacePayload added in v0.16.0

type ChangeWorkspacePayload struct {
	ConversationID string `json:"conversation_id"`
	Cwd            string `json:"cwd"`
}

ChangeWorkspacePayload is the body of a change_workspace frame (docs/protocol-mobile.md § change_workspace). Phone → binary. Both fields are spec-required: a change_workspace must name a target conversation and a target workspace path.

"Workspace" IS the conversation's cwd — this codebase has no separate workspace-id concept — so the target is a filesystem path (mirroring create/promote cwd), not an id. The path is untrusted (a network-paired party supplies it) and becomes the conversation's spawn workdir on its next fresh session, so the daemon confines it to $HOME (symlink-resolved) before storing the resolved realpath. The reply reuses ConversationUpdatedPayload verbatim (the record still exists and only cwd changed).

Deliberately NOT a reuse of PromoteConversationPayload — promote also carries a required Name, which a workspace change neither has nor means (semantic coupling / false dependency, the rationale the sibling payloads document).

type ClaudeAccountPayload added in v0.36.0

type ClaudeAccountPayload struct {
	Kind   string `json:"kind"`
	Label  string `json:"label"`
	State  string `json:"state"`
	Reason string `json:"reason"`
}

ClaudeAccountPayload is the body of claude_account, daemon → client. All four keys always serialize: Label is the operator-given account label and Reason the short failure reason, each "" when absent. Correlation is solely Envelope.InReplyTo.

type ClaudeUsagePayload added in v0.41.0

type ClaudeUsagePayload struct {
	State string `json:"state"`
	// ObservedAt is the daemon's time when it read claude's line, not claude's.
	ObservedAt *time.Time         `json:"observed_at,omitempty"`
	FiveHour   *ClaudeUsageWindow `json:"five_hour,omitempty"`
	SevenDay   *ClaudeUsageWindow `json:"seven_day,omitempty"`
}

ClaudeUsagePayload is the body of claude_usage, daemon → client. State always serializes; ObservedAt and the windows are omitted in state none, and an observed reading omits a window claude's line did not carry.

type ClaudeUsageWindow added in v0.41.0

type ClaudeUsageWindow struct {
	// Utilization is claude's utilization, as sent: observed as a fraction.
	Utilization *float64 `json:"utilization,omitempty"`
	// ResetsAt is claude's resetsAt in Unix seconds.
	ResetsAt *int64 `json:"resets_at,omitempty"`
}

ClaudeUsageWindow is one allowance window. Pointers with omitempty drop only an absent value, so a utilization of 0 serializes as 0.

type CompactingPayload added in v0.16.0

type CompactingPayload struct {
	ConversationID string `json:"conversation_id"`
	Active         bool   `json:"active"`
	// Result is claude's own compact_result for the compaction that just ended —
	// "success" on the observed success path (claude 2.1.259). An OPEN SET carried
	// verbatim, on TurnEndPayload.Outcome's rule: treat an unrecognised token as
	// unknown rather than as an error, because claude may ship one at any time.
	//
	// ALWAYS EMPTY ON A RISING EDGE. A compaction that has just started has no
	// outcome to report, so a client rendering this field must gate on Active being
	// false. Empty on a FALLING edge means one of three things a client answers
	// identically: claude sent no key, claude sent an empty one, or the daemon closed
	// the banner at its own turn boundary with no closing line to read.
	//
	// Spelled compact_result rather than result because a bare `result` beside
	// `active` reads as the frame's own status — TurnEndPayload.ErrorCategory's
	// spelling argument, and it also keeps the key identical to claude's own, which
	// is what makes a daemon log line and a captured frame comparable by eye.
	Result string `json:"compact_result"`
	// ErrorText is claude's compact_error: free-form prose describing why a
	// compaction failed, absent entirely on the observed success path. It is the
	// field this frame exists to carry — before #2236 a failed compaction and a
	// successful one were the same two bytes on the wire, so a client could only
	// draw an ordinary banner for both.
	//
	// BOUNDED AT 256 BYTES BY THE DAEMON and CUT rather than dropped, unlike
	// ErrorCategory beside it on turn_end: that is a token set, where a cut token
	// would match no known value while looking like one; this is prose, where a cut
	// sentence still reads as what it is. The cut is NOT reported — a client cannot
	// distinguish a cut value from a short one and needs no such distinction.
	//
	// SECURITY: claude-authored text, bounded by the daemon and NOT sanitized, so
	// TurnEndPayload.Outcome's SECURITY paragraph applies for provenance — the render
	// boundary owing control-character and terminal-escape stripping is the CLIENT's.
	// IT DOES NOT APPLY FOR SHAPE, and a client that renders this like its turn_end
	// neighbours gets it wrong. Those are short category tokens; this is arbitrary
	// prose, and newlines, terminal escapes, markup, a URL and text impersonating
	// daemon chrome all fit inside 256 bytes. Render it as inert text —
	// UnrecognizedMessagePayload.Raw's rule, the closer neighbour on shape, never an
	// HTML sink, an attribute or a URL — and attribute it to claude rather than
	// showing it as the daemon's own finding, which is the trap
	// QuestionDismissedPayload's outcome field exists to avoid.
	ErrorText string `json:"compact_error"`
}

CompactingPayload is the body of an Envelope whose Type == TypeCompacting (docs/protocol-mobile.md § compacting). Binary → phone direction; the wire form of the internal-only turnevent.Compacting status peer. Active is the show (true) / clear (false) edge, and ConversationID is bridge-supplied because the internal marker carries none. Not turn-scoped, so there is no turn_id.

CORRECTED 2026-09-08 (#2236): this doc called the frame "banner-only (tui-driver streams no compaction progress)", and both halves were already false when #2227 gave the frame its first real producer — #1348 had deleted the driver the parenthetical rests on, and the stream-json seam that replaced it reads claude's outcome off the closing system/status line. The frame now carries that outcome.

IT IS THE FIRST claude-AUTHORED TEXT ON THIS FRAME, which is a class change rather than two more fields. Before this, every value here was the daemon's own — an id it assigned and a bool it computed from a string comparison — so a reader could treat the whole payload as trusted. Two of the four fields are now claude's, bounded but unsanitized, and the SECURITY paragraph at ErrorText is what a renderer must read before drawing either.

No omitempty on either, per this file's rule as stated at ToolResultPayload: absence and the zero value mean the same thing, always emitting the key keeps the testdata fixture pinning the full shape, and a client built before this landed ignores the unknown keys while one built after decodes an older frame lacking them to the zero value without error.

type CompactionBoundaryPayload added in v0.16.0

type CompactionBoundaryPayload struct {
	ConversationID string `json:"conversation_id"`
	// Trigger is claude's own word for what started the compaction — `manual` on the
	// observed path (claude 2.1.259, a typed /compact), with `auto` claude's other
	// documented value. An OPEN SET carried verbatim, on TurnEndPayload.Outcome's rule:
	// treat an unrecognised token as unknown rather than as an error, because claude may
	// ship one at any time. Empty means claude named no trigger this client can be
	// offered — either it sent none, or the daemon dropped an oversized one.
	//
	// BOUNDED AT 256 BYTES BY THE DAEMON and DROPPED rather than cut, which is the
	// opposite of compact_error next door and the same answer turn_end's three strings
	// get. That field is prose, where a cut sentence still reads as what it is; this is
	// a token a client MATCHES, where a cut token would match no known value while
	// looking like one. The drop is not reported and needs no report: an empty value is
	// directly observable, unlike an absence a client would have to infer.
	//
	// SECURITY: claude-authored text, bounded by the daemon and NOT sanitized, so
	// CompactingPayload.ErrorText's SECURITY paragraph applies for provenance — the
	// render boundary owing control-character and terminal-escape stripping is the
	// CLIENT's. IT DOES NOT APPLY FOR SHAPE, and this one is the safer half of that
	// pair rather than the riskier: this is a short token from an open set, so it takes
	// TurnEndPayload.Outcome's rule — switch on it against known values — and never
	// UnrecognizedMessagePayload.Raw's prose latitude. A client that renders this token
	// verbatim into a sentence is rendering up to 256 bytes claude chose.
	Trigger string `json:"trigger"`
	// PreTokens and PostTokens are claude's context size before and after the
	// compaction, exactly as claude stated them.
	//
	// `null` MEANS claude STATED NO SUCH COUNT and `0` means claude stated zero, and a
	// client MUST NOT collapse them: rendering "24k → 0 tokens" for a boundary with no
	// post count is the failure this shape exists to prevent. Degrade where a count is
	// absent — say the conversation was compacted without claiming a size.
	//
	// NEITHER IS CLAMPED, RANGE-CHECKED OR ORDERED by the daemon, on
	// RateLimitedPayload's rule: they are claude's numbers, not the daemon's. post
	// greater than pre is not rejected and not corrected, and neither is a negative.
	// What the daemon does guarantee is that a value it could not decode as an integer
	// produces no frame at all rather than a frame with an invented number.
	PreTokens  *int `json:"pre_tokens"`
	PostTokens *int `json:"post_tokens"`
}

CompactionBoundaryPayload is the body of an Envelope whose Type == TypeCompactionBoundary (docs/protocol-mobile.md § compaction_boundary, #2237). Binary → phone direction; the wire form of turnevent.CompactionBoundary. Like compacting it is conversation-scoped rather than turn-scoped, so there is no turn_id.

IT IS NOT A WIDER `compacting`, AND IT COULD NOT HAVE BEEN. claude states the trigger and the counts on a separate system/compact_boundary line that arrives AFTER the closing system/status line the falling edge is read off, so the numbers do not exist until that frame has shipped. A client applies this to the divider it has ALREADY drawn from compacting's falling edge — and, per the next paragraph, sometimes draws the divider from this frame alone.

EVERY FIELD IS claude's, AND SO IS THE FACT OF THE BOUNDARY. That is a class change rather than a wider payload, and it is a step beyond the one #2236 made next door: CompactingPayload.active is a bool the DAEMON computes from a string comparison it makes itself, so a client can read that field as the daemon's own observation. No field here is. The daemon publishes this frame for a boundary line that followed no compacting edge at all — deliberately, so an auto-compaction announcing itself differently is still published — which means this frame can be the ONLY evidence a compaction happened. A fabricated line reading pre_tokens 999999 and post_tokens 1 draws a plausible compaction mark where nothing was compacted. Render it as claude's ASSERTION, attributed to claude, never as the daemon's own finding, which is the trap QuestionDismissedPayload's outcome field exists to avoid. NOTHING IN THE DAEMON ACTS ON ANY FIELD HERE — no retry, no backoff, no teardown, no routing — which is what keeps a fabricated value a misleading label rather than an actuator.

NOTHING ELSE FROM claude's compact_metadata CROSSES, and the exclusion is structural rather than a scrub: the daemon's decode target (streamsup's compactMetadata) declares these three fields, so encoding/json discards every other key including ones claude has not shipped yet. The line carries four more, and they are two different classes — cumulative_dropped_tokens and duration_ms are simply unasked-for, while preserved_segment, preserved_messages and logical_parent_uuid carry UUIDS NAMING ENTRIES IN THE OPERATOR'S OWN TRANSCRIPT. Neither claude's session_id nor claude's uuid crosses either, per this file's standing rule.

THE TWO COUNTS DEPART FROM THIS FILE'S NO-omitempty RULE IN SHAPE BUT NOT IN SPIRIT, and the departure is the frame's whole point. Elsewhere here absence and the zero value mean the same thing; here they do not — post_tokens is optional in claude's own shape, so a client that collapses them renders "24k → 0 tokens" for a boundary claude reported without a post count. They are therefore POINTERS, and they still carry NO omitempty: an absent count marshals as a literal `null` rather than dropping the key, which keeps every key always present, keeps the testdata fixtures pinning the full shape, and states the absence instead of leaving a client to infer it. SessionTransitionPayload.WorkspaceCwd is the same shape for the same reason, and SessionSettingsPayload's pointer-plus-omitempty is what this deliberately is not. A client built before this landed ignores the whole frame; the daemon always emits all four keys.

type ContextUsageCategory added in v0.18.0

type ContextUsageCategory struct {
	Name   string `json:"name"`
	Tokens int    `json:"tokens"`
}

ContextUsageCategory is one named contribution to a ContextUsagePayload reading. Both keys remain present even when Name is empty. Name is claude-authored descriptive text, already bounded by the producer; it is a label, never a selector a client may branch on for authority.

type ContextUsageMCPTool added in v0.18.0

type ContextUsageMCPTool struct {
	Name       string `json:"name"`
	ServerName string `json:"server_name"`
	Tokens     int    `json:"tokens"`
}

ContextUsageMCPTool is one MCP tool's contribution to a ContextUsagePayload reading. All three keys remain present even when the strings are empty.

SERVERNAME HERE IS INERT, and the name collision with MCPReconnectPayload.ServerName is the trap this comment exists to defuse. That one crosses an actuation seam verbatim and is validated by nothing in this package or in internal/relay. This one names a contributor to a reading: it is never an actuation target, never an authorization input, and must not be fed to an MCP verb on the strength of having appeared here. Name carries the same constraint.

type ContextUsageMemoryFile added in v0.18.0

type ContextUsageMemoryFile struct {
	Path   string `json:"path"`
	Type   string `json:"type"`
	Tokens int    `json:"tokens"`
}

ContextUsageMemoryFile is one memory file's contribution to a ContextUsagePayload reading. All three keys remain present even when the strings are empty.

PATH IS PATH-SHAPED DESCRIPTIVE TEXT, NOT A FILE HANDLE. Nothing on this path joins, cleans, resolves, or opens it — not this package, and not a later mapper either: normalising the string would imply it names a real file this frame acts on, which it does not. It is workspace-authored and unvalidated, so a client must render it as inert text rather than as a link, and must not open it on the strength of this frame. A committed fixture carries a traversal-shaped path so the pass-through is pinned by a test rather than by this comment alone. Type is claude's own label for the entry and carries the same constraint.

type ContextUsagePayload added in v0.18.0

type ContextUsagePayload struct {
	ConversationID     string                   `json:"conversation_id"`
	Model              string                   `json:"model"`
	TotalTokens        int                      `json:"total_tokens"`
	MaxTokens          int                      `json:"max_tokens"`
	Percentage         int                      `json:"percentage"`
	Categories         []ContextUsageCategory   `json:"categories"`
	DroppedCategories  int                      `json:"dropped_categories"`
	MCPTools           []ContextUsageMCPTool    `json:"mcp_tools"`
	DroppedMCPTools    int                      `json:"dropped_mcp_tools"`
	MemoryFiles        []ContextUsageMemoryFile `json:"memory_files"`
	DroppedMemoryFiles int                      `json:"dropped_memory_files"`

	// AsOf marks this reading as REMEMBERED rather than live (#2461), and is the
	// one key on this frame whose ABSENCE is the ordinary case. Present: the daemon
	// could not take a fresh reading and answered from the summary it stored when
	// claude last reported, and this is when that was. Absent: claude produced this
	// reading in response to this frame's own trigger.
	//
	// A CLIENT MUST READ IT BEFORE TRUSTING THE THREE INVENTORIES, and that is the
	// whole reason the key exists rather than being a nicety. A remembered answer
	// carries empty Categories, MCPTools and MemoryFiles because the daemon never
	// stored them — conversations.ContextUsageReading deliberately holds the five
	// headline values and nothing else — while MarshalJSON's own block promises that
	// an empty inventory is a POSITIVE reading, claude reporting no MCP tools. Those
	// two states are byte-identical without this key. The five headline numbers ARE
	// claude's, on both kinds of answer; it is the breakdown that is missing rather
	// than zeroed, and the three dropped counts are 0 for the same reason.
	//
	// Pointer plus omitempty, this file's ONE departure from its no-omitempty rule
	// (see the header). Both halves are forced. A plain time.Time would encode
	// "0001-01-01T00:00:00Z" on every live frame, because omitempty does not test a
	// struct; and a pointer WITHOUT omitempty — CompactionBoundaryPayload's shape,
	// which is how this file normally bends the rule — would put "as_of": null on
	// every live frame, moving bytes that two shipped producers already emit and
	// that internal/protocol/testdata/context_usage.json pins.
	// HelloClientPayload.LastSeenTS is the precedent for the shape.
	//
	// RFC 3339 WITH A Z OFFSET, and this layer does not enforce that — time.Time
	// marshals with whatever offset it carries. The normalisation lives at the one
	// door that stores a reading, conversations.Registry.SetLastContextUsage, so a
	// producer reaching the wire any other way is the thing to fix rather than a
	// formatter here. Daemon-authored, unlike every other non-id field on this
	// frame: it is the daemon's own clock at the moment it recorded, never a value
	// claude reported.
	AsOf *time.Time `json:"as_of,omitempty"`
}

ContextUsagePayload is the body of an Envelope whose Type == TypeContextUsage. Binary → phone direction; one conversation's context-window breakdown as claude reported it. This is the sole outbound wire shape for both later producers — #2371's post-turn publication and #2293's on-demand reply — so it carries no request verb and no correlation field: a reply rides Envelope.InReplyTo.

IT IS MIXED-PROVENANCE, and that is the field-level fact a reader is likeliest to get wrong. ConversationID is DAEMON-authored: the mapper fills it from the daemon's own registry record, never from claude's bytes. EVERY OTHER STRING here and on all three row types is claude- or workspace-authored descriptive text. Assuming one provenance for the whole struct errs in a harmful direction half the time, because it promotes Model and the row strings to values they were never checked to be. This layer neither validates nor sanitizes them, and a client MUST render each as inert text rather than use it as an actuator, a link, or an authorization input.

THE READING IS INFORMATIONAL, mirroring turnevent.ContextUsage's own constraint: consumers may display it, but it does not replace the daemon-owned contextwindow.Read value that control decisions use. The integers are claude's own and the daemon neither recomputes nor normalizes them, so a client must not assume Percentage is derivable from TotalTokens and MaxTokens, nor that the categories sum to the total.

Each list preserves the producer's descending-token order, and arrives as a PREFIX of it: any cut takes entries off the tail, so a shortened list is never a list with holes. All three keys are always present and never null — see MarshalJSON. Bounds are not re-decided here: internal/streamsup caps every string and list count at construction, and a second cap in this package would be a second place the limit is decided, free to disagree silently — SessionFactsPayload's stated reason. The one bound decided outside the producer is on a dimension it does not cover, the frame's BYTE cost against the v2 application-envelope cap, and it lives in the mapper rather than here for that same no-second-place reason; see the dropped counts below.

THE THREE DROPPED COUNTS ARE INDEPENDENT AND NOT INFERABLE. Each is TWO CUTS' worth of loss: the count its turnevent.ContextUsage counterpart carries — the producer's, recorded when its entry or string caps fired — plus whatever the mapper's own frame budget removed from that same list to keep the envelope under the v2 cap (internal/turnbridge's maxContextUsageListBytes). The mapper ADDS to the base rather than replacing it, so this layer must still not infer loss from a retained list's length, and the three pairs are still never cross-read. Each list's original size stays recoverable as len(list) + its OWN dropped count, across both cuts.

A NON-ZERO COUNT THEREFORE SAYS NOTHING ABOUT HOW MANY ENTRIES ARRIVED, and the sibling's shortcut does not transfer: SlashCommandListPayload.DroppedCommands is the same two-cut arithmetic on a frame with one list, where this frame divides one envelope across three and can cut all three at once. A client that treats a full list as proof nothing was dropped, or an empty one as proof everything was, is wrong in both directions.

func (ContextUsagePayload) MarshalJSON added in v0.18.0

func (p ContextUsagePayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises all three nil inventory slices to empty arrays. An empty inventory is a positive reading — claude reported no MCP tools, or no memory files — so clients receive [] rather than null and never have to distinguish the two. The value receiver keeps normalisation local and does not mutate the caller.

One normaliser on the payload rather than three on the row types: the nil-to-[] question belongs to whoever owns the keys, and the rows encode correctly on their own. MCPStatusPayload is arranged the same way.

type ConversationCreatedPayload

type ConversationCreatedPayload struct {
	ID         string `json:"id"`
	IsPromoted bool   `json:"is_promoted"`
	Cwd        string `json:"cwd"`
	// WorkspaceLabel is the operator-set display name stored for the workspace at
	// this frame's own Cwd (#2210), carrying the same value and the same contract
	// ConversationSummary.WorkspaceLabel does on a list row — see the rationale
	// there. Nullable but never omitted: a workspace with no stored label
	// serializes an explicit null, so a client may treat a missing key as a
	// malformed frame rather than as an unlabelled workspace. Nil is "no label
	// stored"; a non-nil pointer to "" is the distinct explicitly-empty label the
	// registry admits, and presence must come from the accessor's second return
	// rather than from a label != "" comparison, which collapses the two.
	WorkspaceLabel *string   `json:"workspace_label"`
	Name           *string   `json:"name"`
	LastUsedAt     time.Time `json:"last_used_at"`
	// Agent is the agent the created conversation runs on, AgentClaude or
	// AgentCodex (#2647), set only for a client that negotiated
	// CapabilityMultiAgent — ConversationSummary.Agent's rule. omitempty is
	// load-bearing: an older client's reply carries no agent key, byte-identical
	// to the frame it read before agents existed.
	Agent string `json:"agent,omitempty"`
}

ConversationCreatedPayload is the body of a conversation_created frame (docs/protocol-mobile.md § conversation_created). Binary → phone, sent in reply to a create_conversation. ID, IsPromoted, Cwd, LastUsedAt are spec-required and non-nilable. Name is a pointer because the spec example shows "name": null (an unnamed scratch conversation); see the rationale on CreateConversationPayload for why omitempty is omitted.

type ConversationDeletedPayload added in v0.16.0

type ConversationDeletedPayload struct {
	ID string `json:"id"`
}

ConversationDeletedPayload is the body of a conversation_deleted frame (docs/protocol-mobile.md § conversation_deleted). Binary → phone, sent in reply to a delete_conversation. It carries only the deleted conversation's id (the id tag matches ConversationCreatedPayload / ConversationUpdatedPayload): the record no longer exists, so no name/cwd/last_used_at can be projected (contrast ConversationUpdatedPayload). The id is the one fact the ack must identify.

type ConversationSummary

type ConversationSummary struct {
	ID         string  `json:"id"`
	Name       *string `json:"name"`
	IsPromoted bool    `json:"is_promoted"`
	// CurrentSessionID is the stored binding, not a process liveness guarantee.
	// Always serialized, including an empty string when no session is bound.
	CurrentSessionID string `json:"current_session_id"`
	// IsArchived is the conversation's durable archived flag. Always
	// serialized (no omitempty, unlike the on-disk Conversation.IsArchived):
	// a client partitions active vs. archived and counts each side, so it must
	// read the flag on active rows too, where the value is false.
	IsArchived bool `json:"is_archived"`
	// IsMuted is the conversation's durable mute-notifications flag (#2571).
	// Always serialized (no omitempty, unlike the on-disk Conversation.IsMuted):
	// a client reads false explicitly on every row, and treats an absent key
	// as not muted only because an older daemon cannot send it.
	IsMuted bool `json:"is_muted"`

	// PinnedAt is the host-local pin time, or null when unpinned. Always
	// serialized; an absent field from an older host also decodes as unpinned.
	PinnedAt *time.Time `json:"pinned_at"`

	// ReadUpTo is the stored durable history read mark, including zero.
	ReadUpTo uint64 `json:"read_up_to"`
	// LatestEntryID is the newest durable history entry excluding turn_state,
	// stall, api_retry, compacting, and session_transition, or zero if none exists.
	LatestEntryID uint64 `json:"latest_entry_id"`
	// LastShownVersion is raised by adding a shown thread item or appending text
	// to one, not by every item revision. Nil omits it; a pointer to zero emits 0.
	LastShownVersion *uint64 `json:"last_shown_version,omitempty"`
	// ArchivedAt is when the conversation was archived (#2698), so a client
	// orders its Archive screen newest-archived first. A pointer without
	// omitempty, like WorkspaceLabel below: the key is always serialized, and
	// null means an active conversation or one archived before the daemon
	// recorded the time — the client then falls back to LastUsedAt.
	ArchivedAt *time.Time `json:"archived_at"`
	Cwd        string     `json:"cwd"`
	// WorkspaceLabel is the operator-set display name stored for the workspace
	// at this row's own Cwd (#2208), so a client renders the chosen name without
	// a second read verb. It belongs to the workspace, not to this conversation:
	// N rows sharing one Cwd carry one label, and a row in another workspace
	// carries its own.
	//
	// A pointer without omitempty, the same discipline as Name's above, but here
	// the absent omitempty is a client-visible contract rather than only a
	// round-trip property: a workspace with no stored label must serialize an
	// explicit null, and the consuming clients fail closed on a missing key the
	// way they already do for a missing cwd. Nil is "no label stored"; a non-nil
	// pointer to "" is the distinct explicitly-empty label the registry admits.
	WorkspaceLabel *string   `json:"workspace_label"`
	LastMessageTS  time.Time `json:"last_message_ts"`
	LastUsedAt     time.Time `json:"last_used_at"`
	// Agent is the agent that runs this conversation's bound session, AgentClaude
	// or AgentCodex (#2643). Set only for a client that negotiated
	// CapabilityMultiAgent, which always reads a value. omitempty is load-bearing:
	// a client without the capability gets the empty value, so its row carries no
	// agent key and stays byte-identical to the row it read before the field
	// existed.
	Agent string `json:"agent,omitempty"`
}

ConversationSummary is one row of a ConversationsPayload (docs/protocol-mobile.md § conversations). Name is a pointer because the spec admits null on the wire (an unnamed scratch conversation), and is intentionally not tagged json:",omitempty": the spec example shows "name": null explicitly, and omitempty on a nil pointer would drop the key entirely, breaking byte-equivalent round-trip.

type ConversationUpdatedPayload

type ConversationUpdatedPayload struct {
	ID         string `json:"id"`
	IsPromoted bool   `json:"is_promoted"`
	// IsArchived is the conversation's durable archived flag. Always serialized
	// (no omitempty, unlike the on-disk Conversation.IsArchived): a client reads
	// the flag to partition active vs. archived, so it must read it on active
	// rows too, where the value is false — an absent key could not distinguish
	// "restored to active" from "old daemon." Placed right after IsPromoted to
	// mirror ConversationSummary and group the two state bools.
	IsArchived bool `json:"is_archived"`
	// IsMuted is the conversation's durable mute-notifications flag (#2571),
	// read from the stored conversation by every producer. Always serialized
	// (no omitempty, unlike the on-disk Conversation.IsMuted): a client folds
	// this record into its list in place, so a record that dropped the key
	// would read as not muted and a rename would silently unmute the channel.
	IsMuted bool `json:"is_muted"`

	// PinnedAt is the host-local pin time, or null when unpinned. Always
	// serialized; an absent field from an older host also decodes as unpinned.
	PinnedAt *time.Time `json:"pinned_at"`

	// ReadUpTo is the stored durable history read mark, including zero.
	ReadUpTo uint64  `json:"read_up_to"`
	Name     *string `json:"name"`
	Cwd      string  `json:"cwd"`
	// WorkspaceLabel is the operator-set display name stored for the workspace at
	// this frame's own Cwd (#2210), so a client patching a row in place from a
	// pushed frame renders the operator's chosen name without re-listing to find
	// it. Same value, same contract as ConversationSummary.WorkspaceLabel on a
	// list row; nullable but never omitted, and presence comes from the registry
	// accessor's second return, never from a label != "" comparison.
	//
	// That this record admits a workspace label while refusing a system prompt is
	// not a contradiction, and the difference is audience. A prompt reaches no
	// other read path — it is on neither list_conversations nor session_settings
	// — so hanging it on a frame broadcast to every phone on this server-id would
	// create disclosure. The label is already on every list_conversations row
	// (#2208), readable by any paired client on demand, so carrying it here
	// widens no audience: it changes only whether a client learns the value at
	// push time or at its next list. Size points the same way — one 128-byte
	// label on a single-row frame, against 8192 bytes of prompt times every row.
	//
	// The value is an opaque operator-supplied string echoed verbatim. Its
	// 128-byte bound is enforced on the write path and is a size limit, not a
	// safety property: rendering it safely stays the client's job.
	WorkspaceLabel *string   `json:"workspace_label"`
	LastUsedAt     time.Time `json:"last_used_at"`
	// Agent is the conversation's agent, AgentClaude or AgentCodex (#2669), as
	// the conversations row's Agent is resolved. No producer sets it: the relay
	// adds it where the frame is sealed for a conn that negotiated
	// CapabilityMultiAgent, so one rule covers every producer and a conn without
	// that capability reads the frame with no agent key, as before.
	Agent string `json:"agent,omitempty"`
}

ConversationUpdatedPayload is the body of a conversation_updated frame (docs/protocol-mobile.md § conversation_updated). Binary → phone, broadcast to all phones on this server-id. ID, IsPromoted, IsArchived, Cwd, LastUsedAt are required. Name is spec-optional (a previously unnamed conversation can be updated without acquiring a name) and is a pointer for the same round-trip reason given on CreateConversationPayload.

It deliberately carries NO system_prompt field (#2151), unlike rename / archive / change_workspace where this record happens to already hold what changed. Two reasons. Security: this frame is broadcast to all phones on this server-id, so hanging up to 8192 bytes of operator text on it would widen the audience for a value only the requester asked about — a projection type that lacks the field cannot leak it, which is a stronger guarantee than a handler that merely declines to fill it in. Scope: reading the prompt back is #2152, which deliberately does not echo the text either. set_system_prompt therefore replies with an unchanged-looking record that confirms the write without carrying the value.

type ConversationsPayload

type ConversationsPayload struct {
	Conversations []ConversationSummary `json:"conversations"`
}

ConversationsPayload is the body of a conversations frame (docs/protocol-mobile.md § conversations). Binary → phone, sent in reply to a list_conversations request. Order of the Conversations slice is preserved from the wire — the binary is the source of truth for ordering (e.g. most-recently-used first); this type does not reorder.

type CreateConversationPayload

type CreateConversationPayload struct {
	IsPromoted *bool   `json:"is_promoted"`
	Name       *string `json:"name"`
	Cwd        *string `json:"cwd"`
	// Agent names the agent the new conversation runs on, AgentClaude or
	// AgentCodex (#2647); nil (absent or null) means claude. AgentCodex is
	// accepted only from a client that negotiated CapabilityMultiAgent, and any
	// other value is refused — both before anything is created. Unlike the three
	// fields above it is omitempty: it is newer than the spec example, so a request
	// without it keeps that example's exact encoding.
	Agent *string `json:"agent,omitempty"`
	// Model and Effort are the settings the new conversation's session starts on
	// (#2665); nil (absent or null) keeps what a create gives today. A set value
	// is checked against the resolved agent's own vocabulary, by the checks
	// set_session_settings runs, and a refused one creates nothing. An empty
	// string means the agent's own default, as on set_session_settings. omitempty
	// for Agent's reason: a request without them keeps its exact encoding.
	Model  *string `json:"model,omitempty"`
	Effort *string `json:"effort,omitempty"`
}

CreateConversationPayload is the body of a create_conversation frame (docs/protocol-mobile.md § create_conversation). Phone → binary. All three fields are spec-optional — the binary fills server-side defaults when null is on the wire.

Fields are pointers without omitempty so a nil value round-trips as JSON null (matching the spec example's "name": null / "cwd": null) and a pointer-to-zero round-trips as the zero scalar (matching the spec example's "is_promoted": false). omitempty on a nil pointer would drop the key entirely, breaking byte-equivalent round-trip.

type CreateWorkspaceFolderPayload added in v0.16.0

type CreateWorkspaceFolderPayload struct {
	Parent string `json:"parent"`
	Name   string `json:"name"`
}

CreateWorkspaceFolderPayload is the body of a create_workspace_folder frame (docs/protocol-mobile.md § create_workspace_folder). Phone → binary. Both fields are spec-required and value-typed (mirroring PromoteConversationPayload):

Parent — the untrusted parent directory under which to create the folder
         (a "~"/"~/"-prefix anchors at the daemon's $HOME).
Name   — the new folder's single path element. It is untrusted and validated
         by the handler (no path separator, no "..", not absolute, non-empty)
         BEFORE it is joined under Parent, so the folder lands directly under
         Parent and never elsewhere.

The daemon joins Parent + Name, confines the result to $HOME (symlink-resolved), and creates the directory. Deliberately NOT a reuse of any conversation payload: a workspace-folder create names no conversation and carries no id.

type DebugBundleChunkPayload added in v0.16.0

type DebugBundleChunkPayload struct {
	Seq  int    `json:"seq"`
	Data []byte `json:"data"`
}

DebugBundleChunkPayload is the body of an Envelope whose Type == TypeDebugBundleChunk (docs/protocol-mobile.md § Debug bundle). Binary → phone direction; one ordered slice of a streamed bundle.

Seq is 0-based, contiguous, and ascending across a stream — the receiver (ReassembleBundle / the phone) requires the next chunk's Seq to equal the count of chunks already seen, so a reorder, gap, or duplicate fails cleanly rather than corrupting output. Data is the raw bundle slice; []byte auto-encodes as standard base64 via encoding/json, which the phone decodes. The slice is content-bearing bundle bytes — never logged (AC#4).

type DebugBundleDonePayload added in v0.16.0

type DebugBundleDonePayload struct {
	Total int `json:"total"`
}

DebugBundleDonePayload is the body of an Envelope whose Type == TypeDebugBundleDone (docs/protocol-mobile.md § Debug bundle). Binary → phone direction; the completion marker sent after the last debug_bundle_chunk.

Total is the exact number of chunks in the stream. The receiver uses it to detect a truncated stream: a done whose Total does not equal the count of chunks actually received is a count-mismatch error, never accepted as complete.

type DeleteConversationPayload added in v0.16.0

type DeleteConversationPayload struct {
	ConversationID string `json:"conversation_id"`
}

DeleteConversationPayload is the body of a delete_conversation frame (docs/protocol-mobile.md § delete_conversation). Phone → binary. The one required field is the target conversation's id; deletion is permanent (hard delete — the reversible path is archive/unarchive). Mirrors PromoteConversationPayload / RenameConversationPayload's value-typed ConversationID.

type DequeueMessagePayload added in v0.15.0

type DequeueMessagePayload struct {
	ConversationID string `json:"conversation_id"`
	QueuedMsgID    uint64 `json:"queued_msg_id"`
	// AcceptedItemID binds the command to the accepted thread item's ID in 1..2^53-1.
	// RawMessage preserves supplied null and wrong types so handlers reject them
	// instead of going unbound.
	AcceptedItemID json.RawMessage `json:"accepted_item_id,omitempty"`
}

DequeueMessagePayload is the body of an Envelope whose Type == TypeDequeueMessage (docs/protocol-mobile.md § Queue). Phone → binary direction.

This is an inbound v2 *control* envelope, structurally like ModalAnswerPayload / RequestSnapshotPayload: the v2 session manager intercepts it at dispatchAppFrame before dispatch.Route. There is NO dispatch.Route handler — resolving ConversationID to an authorized conversation and applying msgqueue.Remove(convID, QueuedMsgID) is the handler's (#723) job. Unlike modal_answer this is ungated for any paired phone (ADR 025 § Security model). ConversationID is untrusted phone input.

type Envelope

type Envelope struct {
	ID        uint64          `json:"id"`
	Type      string          `json:"type"`
	TS        time.Time       `json:"ts"`
	Payload   json.RawMessage `json:"payload"`
	InReplyTo *uint64         `json:"in_reply_to,omitempty"`

	// EventID is the durable event id (eventring), unique daemon-wide, that the
	// interactive structured stream stamps so a phone can advertise it as
	// last_event_id on reconnect. Distinct from ID (the per-conn envelope
	// counter that resets each reconnect). A pointer + omitempty so every
	// non-interactive / v1 construction site stays byte-identical: absent,
	// not 0. Ring ids are always >= 1, so a non-nil pointer never encodes 0.
	// Set only by the interactive emitter (#649); consumed by #647.
	EventID *uint64 `json:"event_id,omitempty"`

	// HistoryEntryID identifies HistoryEntry.ID, the durable per-conversation
	// entry used by mark_conversation_read.up_to. Distinct from ID and EventID;
	// real entries are >= 1. Nil omits the key and requires history/list fallback.
	// History-backed live producers and ring replay stamp the original successful
	// append's ID; absent or failed storage omits it. This conveys no authorization.
	HistoryEntryID *uint64 `json:"history_entry_id,omitempty"`

	// ConversationID routes supplied thread live state independently of session
	// provenance. Nil omits metadata; a supplied value must be a nonempty JSON
	// string matching the retained source. RawMessage preserves malformed/null
	// values for delivery-boundary validation. It conveys no authorization.
	ConversationID json.RawMessage `json:"conversation_id,omitempty"`

	// SessionID is live-state metadata supplied only for thread-capable delivery.
	// Nil omits metadata; JSON null positively means no producing session; a JSON
	// nonempty string names the producing session. RawMessage preserves omission
	// versus null when decoding and re-encoding. Producers/consumers enforce this
	// shape; it conveys no authorization and does not replace payload session fields.
	SessionID json.RawMessage `json:"session_id,omitempty"`
	// SessionStateCleared with payload {} clears this kind's session-scoped reading.
	// Ordinary updates omit the flag. Delivery consumers enforce the empty payload.
	SessionStateCleared bool `json:"session_state_cleared,omitempty"`

	PayloadEncrypted bool `json:"payload_encrypted,omitempty"`
}

Envelope is the outer wire shape every application frame conforms to (docs/protocol-mobile.md § Message envelope). The Payload field carries the per-type body as a deferred-decode json.RawMessage; per-type structs land in a sibling ticket and slot in via a second-pass json.Unmarshal.

type ErrorPayload

type ErrorPayload struct {
	Code             string `json:"code"`
	Message          string `json:"message"`
	Retryable        bool   `json:"retryable"`
	RetryAfterS      *int   `json:"retry_after_s,omitempty"`
	ConversationID   string `json:"conversation_id,omitempty"`
	MinClientVersion string `json:"min_client_version,omitempty"`
}

ErrorPayload is the body of an "error" envelope (docs/protocol-mobile.md § Message types, § Error codes). RetryAfterS is optional and advisory; it is meaningful only when Retryable is true.

ConversationID names the conversation an error is ABOUT, and it exists for the replies whose subject in_reply_to cannot identify (#2443). Most error replies answer a request that named its own subject, so the client already knows what the refusal is about and the field is omitted — new_session is the exception that minted it: a bare frame names no conversation and rotates the daemon's cursor one, so only the daemon knows which conversation the answer describes. stop_background_task.refused is the correlation exception: it carries the requested conversation id even for a missing task id or an unknown conversation. This is correlation data only and asserts nothing about daemon membership. Omitted (omitempty) by other replies, keeping their earlier wire shape.

SECURITY: except for stop_background_task.refused, the value is DAEMON-AUTHORED and MUST NOT echo a client-supplied id — the discipline V2SessionConfig's RunConfigFor and ModelListFor state for their own reported ids. Other producers set it from the daemon's registry or cursor, never from the request. The stop refusal's reflected id must never be logged.

MinClientVersion is the three-part minimum (e.g. "1.4.0") the host holds for the requesting app, carried by CodeClientUpdateRequired alone (#2576) so the message can stay static. Omitted when unset, which keeps every other error reply byte-identical, and omitted on that code too when the hello's client_version could not be parsed, since the daemon then cannot tell which app's minimum applies. Daemon-authored from the configured minimum, never an echo of the client's client_version.

type HelloAckPayload

type HelloAckPayload struct {
	ProtocolVersion string   `json:"protocol_version"`
	ServerID        string   `json:"server_id"`
	ConnID          string   `json:"conn_id"`
	Capabilities    []string `json:"capabilities,omitempty"`
	WorkspaceRoot   string   `json:"workspace_root,omitempty"`
}

HelloAckPayload is the body of a "hello_ack" envelope sent in response to "hello" (docs/protocol-mobile.md § Message types). ConnID echoes the relay-assigned id back to the phone for diagnostics only.

Capabilities is the daemon's supported feature set echoed back to the phone; omitempty so a daemon advertising nothing round-trips byte-identically with the v1 hello_ack shape. The daemon MUST echo only what it itself supports (the intersection with the phone's advertised set, never a blind mirror of the phone's claims) — that trust decision is #608's, not this wire-type layer's.

WorkspaceRoot is the daemon host's absolute ~/pyry-workspace/ base for resolving relative workspace paths. It is omitted when the daemon cannot determine an absolute home directory or the peer is not authorized to receive host metadata. The producer reports the convention only; it does not create or inspect the path.

type HelloClientPayload

type HelloClientPayload struct {
	Role             string     `json:"role"`
	DeviceName       string     `json:"device_name"`
	ClientVersion    string     `json:"client_version"`
	ClientFeatures   string     `json:"client_features,omitempty"`
	ProtocolVersions []string   `json:"protocol_versions"`
	LastSeenTS       *time.Time `json:"last_seen_ts,omitempty"`
	Token            string     `json:"token,omitempty"`
	Capabilities     []string   `json:"capabilities,omitempty"`
	LastEventID      *uint64    `json:"last_event_id,omitempty"`
}

HelloClientPayload is the body of a "hello" envelope sent by the phone after WS upgrade (docs/protocol-mobile.md § Message types). Role is always "client". LastSeenTS is optional and has NO CONSUMER — it is decoded here and read by nothing, in internal/relay or anywhere else, so it triggers no backfill and a hello carrying it behaves identically to one omitting it (#2090). Kept because it is still accepted wire vocabulary — a decoder that rejected it would be wrong — and because whether real history should exist is #2091's decision, not this type's. A reconnecting phone that wants the tail it missed sends LastEventID below.

ClientFeatures is optional, untrusted self-reported plain text in v2, unrelated to negotiated Capabilities. Preserve it verbatim; empty means no description. Retention and prompt admission are owned by #2898.

Token is the in-band carrier of the device-pairing token under v2 (docs/protocol-mobile.md § Authentication, line 420). Empty under v1 (carried as RoutingEnvelope.Token instead); the omitempty keeps v1 round-trip byte-identical for existing fixtures. SECURITY: Token is plaintext credential material — MUST NOT be logged at any level.

Capabilities is the phone's advertised feature set (e.g. CapabilityInteractive); omitempty so a phone advertising nothing round-trips byte-identically with the v1 hello shape (the key is absent, not null). The daemon intersecting this with its own supported set is #608's job — this field is the advertisement only, no enforcement here.

LastEventID is the durable, daemon-wide-unique event id the phone last saw on the interactive structured stream (the event_id #649 stamps on Envelope). A reconnecting phone advertises it so the daemon can replay the missed tail from the in-memory event ring or signal a resync (#647). A pointer + omitempty so a phone advertising none round-trips byte-identically with today's hello (key absent, not null); ring ids are always >= 1 so a non-nil pointer never encodes 0. SECURITY: untrusted remote input — the consumer (internal/relay) range/shape-validates it and bounds replay by the ring; this wire-type layer does no enforcement.

type HelloServerPayload

type HelloServerPayload struct {
	Role             string   `json:"role"`
	ServerID         string   `json:"server_id"`
	BinaryVersion    string   `json:"binary_version"`
	ProtocolVersions []string `json:"protocol_versions"`
}

HelloServerPayload is the body of a "hello" envelope sent by the binary after WS upgrade (docs/protocol-mobile.md § Message types). Role is always "server".

type HistoryEntry added in v0.16.0

type HistoryEntry struct {
	// ID is the durable per-conversation entry id (history.Entry.ID), monotonic
	// within one conversation's log and stable across daemon restarts.
	ID uint64 `json:"id"`

	// Type is the wire type the stored frame carried. Unvalidated; tolerate an
	// unknown one.
	Type string `json:"type"`

	// Payload is the stored frame's body, verbatim. Replayed content — see the
	// type's trust-class block.
	Payload json.RawMessage `json:"payload"`

	// TS is when the entry was appended.
	TS time.Time `json:"ts"`
}

HistoryEntry is one entry of a HistoryPagePayload: one past wire frame, as it was stored. It MIRRORS history.Entry key for key, which is the whole point — a client re-reduces a loaded page oldest-first through the timeline reducer it already has for the live stream, and that only works if an entry is shaped like the frame it replays.

ID IS THE DURABLE, PER-CONVERSATION ENTRY ID FROM THE LOG, and it is deliberately NOT Envelope.EventID. Ring ids are per-process and do not survive a daemon restart; this one is on disk and does. A client must not join the two namespaces — they are different sequences that both look like small integers.

TRUST CLASS, AND IT IS NOT THE PAGE'S. Type and Payload are REPLAYED CONTENT: the bytes of a frame that was appended to the log, operator-authored for a stored send_message and CLAUDE-AUTHORED for a stored assistant frame. An entry therefore carries EXACTLY THE TRUST CLASS OF THE LIVE FRAME IT MIRRORS, and a client applies the same sanitisation it applies on the live lane. docs/protocol-mobile.md § Security model's threat 1 LANDS on this frame — the opposite of RequestAttachmentPayload, which carries no content at all, so that type's "threat 1 does not land here" does not transfer.

Type is a STORED STRING that nothing re-validates against this package's Type* vocabulary, so a client must tolerate an entry type it does not know rather than treating one as a protocol violation. Payload is carried opaquely and nothing in this package decodes it.

type HistoryPagePayload added in v0.16.0

type HistoryPagePayload struct {
	// Entries are this page's entries, NEWEST-FIRST. A client re-reduces them
	// oldest-first through its existing timeline reducer.
	Entries []HistoryEntry `json:"entries"`

	// Cursor is the position to ask with next, opaque to the client. Empty
	// whenever AtStart is set.
	Cursor string `json:"cursor"`

	// AtStart reports that the start of the log was reached while filling this
	// page. It is the ONLY termination signal; an empty Entries is not one.
	AtStart bool `json:"at_start"`
}

HistoryPagePayload is the body of an Envelope whose Type == TypeHistoryPage (docs/protocol-mobile.md § Conversation history, published by #2113). The daemon's answer to a TypeRequestHistory: one backward step of a walk. It mirrors history.Page. Wire vocabulary only — #2116 emits it.

A WALK TERMINATES ON AtStart, NEVER ON AN EMPTY Entries. A page that fills EXACTLY at the log's first entry reports AtStart false with a usable Cursor; the call after it returns no entries with AtStart true. That is history.Page's own contract, restated here because the tempting client implementation ("stop when a page comes back empty") is wrong against it and the tempting producer implementation (report AtStart only on an empty page) is wrong the other way. Cursor is empty whenever AtStart is set, so the two are never both meaningful.

THE CLAMP BOUNDS ENTRIES, NOT BYTES, and the consequence is a client-visible contract rather than an implementation detail. history.MaxPageEntries caps the entry COUNT; nothing bounds a stored entry's payload, so a full page can exceed the v2 application-envelope cap and be undeliverable as the daemon's OWN outbound frame. A producer may therefore return FEWER ENTRIES THAN ASKED to fit that cap. This is precisely why termination is AtStart and not an entry count: byte-driven truncation is safe only for a client that never infers "short page ⇒ start of log". The byte budgeting itself is #2116's.

NO conversation_id, and that is a decision rather than an omission. Correlation rides the envelope's InReplyTo, the shape SessionSettingsPayload already takes — it answers a request that named a conversation and carries none itself. The cost is stated rather than hidden: a client keeps its outstanding asks keyed by envelope id. The gain is that NOTHING IN A PAGE IS ECHOED BACK FROM THE REQUEST, which is not the same as every field being daemon-authored — each entry's Type and Payload are replayed content, per HistoryEntry's block. TestHistoryPagePayload_WireKeys pins the absence.

func (HistoryPagePayload) MarshalJSON added in v0.16.0

func (p HistoryPagePayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Entries to an empty array, so a page always serialises as "entries":[] and never as "entries":null.

The reachable case is a real one rather than a constructed-zero-value curiosity: history.Store.Page returns Page{AtStart: true} with no entries for a conversation that was never written to, which is the terminal-empty page a walk ends on. null fails the decode of a client whose array type is non-optional — QuestionShownPayload.MarshalJSON's client-decode reason, and here the OTHER half of that block's rationale transfers too: an empty list is a POSITIVE STATEMENT, saying this conversation has nothing older, where an empty question array states nothing legal at all.

Value receiver, so the substitution lands on a copy rather than on the caller's slice, and the type alias keeps json.Marshal from recursing back into this method.

type HostSystemPromptPayload added in v0.32.0

type HostSystemPromptPayload struct {
	SystemPrompt        string `json:"system_prompt"`
	DefaultSystemPrompt string `json:"default_system_prompt"`
}

HostSystemPromptPayload is the body of host_system_prompt, daemon → client. It answers a read or durable write with the current value and shipped reset value. Both strings always serialize, even when current is "". Correlation is solely Envelope.InReplyTo: no conversation/session identifier or live-session verdict is carried. Changes apply at the next session start.

type HostedAppRecord added in v0.39.0

type HostedAppRecord struct {
	AppID          string  `json:"app_id"`
	Title          string  `json:"title"`
	Desired        string  `json:"desired"`
	State          string  `json:"state"`
	ActiveRelease  *string `json:"active_release"`
	PendingRelease *string `json:"pending_release"`
	LastError      *struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"last_error"`
	Revision uint64 `json:"revision"`
}

HostedAppRecord is one discovery item and the whole app_updated payload. Updates are unsolicited and omit Envelope.InReplyTo and session/replay metadata. Release and error keys are required even when null. LastError contains only a safe code and static message, unlike the bridge's separate ErrorPayload. Consumers validate identity, state, required keys and revisions in 1..9007199254740991.

type InnerFrameV2 added in v0.14.0

type InnerFrameV2 struct {
	Version int    `json:"v"`
	Type    string `json:"type"`
	Data    string `json:"data"`
}

InnerFrameV2 is the v2 inner-frame shape carried inside RoutingEnvelope.Frame (docs/protocol-mobile.md § Wire shapes).

type InterruptPayload added in v0.16.0

type InterruptPayload struct {
	ConversationID string `json:"conversation_id,omitempty"`
}

InterruptPayload is the body of an Envelope whose Type == TypeInterrupt (docs/protocol-mobile.md § Interrupt (v2)). Phone → binary direction.

This is an inbound v2 *control* envelope, structurally identical to NewSessionPayload: the v2 session manager intercepts it at dispatchAppFrame before dispatch.Route, and there is NO dispatch.Route handler — resolving ConversationID and stopping that conversation's running turn is the handler's (#2103) job. Like new_session before #2099 the whole payload is OPTIONAL: the frame carried none at all until #2103, so an un-upgraded client sends a bare envelope and MUST keep working.

ConversationID is untrusted phone input and is a validated LOOKUP KEY, never authorization and never a path component — the rule docs/protocol-mobile.md already publishes for request_attachment, attachment_chunk and new_session. Absent, empty, or a body that does not decode at all are ONE value and one meaning: interrupt the conversation the daemon's own cursor points at, which is the pre-#2103 behaviour verbatim. omitempty keeps that the shape a client with nothing to name actually emits, so the wire has one canonical bare form.

type ListAppsPayload added in v0.39.0

type ListAppsPayload struct {
	Cursor string `json:"cursor,omitempty"`
}

ListAppsPayload is a client-to-daemon discovery request. The first page is {}; a subsequent page carries a nonempty opaque cursor validated by the handler.

type ListConversationsPayload

type ListConversationsPayload struct{}

ListConversationsPayload is the body of a list_conversations frame (docs/protocol-mobile.md § list_conversations). Phone → binary. The payload is empty by spec; the type exists so the dispatcher can decode into a concrete value rather than a json.RawMessage.

type MCPReconnectPayload added in v0.17.0

type MCPReconnectPayload struct {
	ConversationID string `json:"conversation_id"`
	ServerName     string `json:"server_name"`
}

MCPReconnectPayload is the body of an Envelope whose Type == TypeMCPReconnect (#2419). It asks the daemon to reconnect one named MCP server inside one conversation. There is no ack type: an accepted actuation answers with a fresh TypeMCPStatus frame correlated by Envelope.InReplyTo, so a client's next render is the list it would have asked for anyway and this payload carries no request id.

BOTH STRINGS ARE UNVERIFIED REMOTE-AUTHORED INPUT, and they are not equally checked downstream, which is the part a reader is most likely to get wrong. ConversationID is a lookup key the relay resolves against the daemon's own registry before anything else sees it. ServerName is checked by NOTHING anywhere in this package or in internal/relay — it crosses the actuation seam verbatim, and the seam's implementation is its sole validator. Neither is logged, returned, or joined into a path by any layer that handles this type; the answer's ConversationID comes from the daemon's own record rather than being echoed back.

Both keys are unconditional so a committed fixture pins the complete wire shape.

type MCPServerStatus added in v0.16.0

type MCPServerStatus struct {
	Name    string `json:"name"`
	Status  string `json:"status"`
	Error   string `json:"error"`
	Scope   string `json:"scope"`
	Version string `json:"version"`
}

MCPServerStatus is one retained server row in MCPStatusPayload. All five keys remain present even when their strings are empty. Error is free-form prose already capped to 256 bytes by the producer; the wire layer does not cap it again. Scope, Status and Version remain open strings rather than validation or authority.

type MCPStatusPayload added in v0.16.0

type MCPStatusPayload struct {
	ConversationID string            `json:"conversation_id"`
	Servers        []MCPServerStatus `json:"servers"`
	DroppedServers int               `json:"dropped_servers"`
}

MCPStatusPayload is the body of an Envelope whose Type == TypeMCPStatus. Binary → phone direction; the conversation-scoped snapshot of MCP servers Claude reported. This is the sole outbound wire shape for both later live publication and on-demand replies. #2373 declares the shape before the request, mapping and publication work in #2374, #2375 and #2276.

Servers preserves Claude's order. Its key is always present and never null — see MarshalJSON. DroppedServers is copied verbatim from turnevent.MCPStatus.DroppedServers by a later mapper; this layer must not infer loss from len(Servers).

Config, tools, serverInfo.name, request ids and the raw Claude response are deliberately absent. Every string in Servers is untrusted Claude-authored text. This layer neither validates nor sanitizes it, and a client must render every field as inert text rather than use it as an actuator.

func (MCPStatusPayload) MarshalJSON added in v0.16.0

func (p MCPStatusPayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Servers slice to an empty array. An empty server list is a positive snapshot, so clients receive "servers":[] rather than null. The value receiver keeps normalisation local and does not mutate the caller.

type MCPStatusRequestPayload added in v0.16.0

type MCPStatusRequestPayload struct {
	ConversationID string `json:"conversation_id"`
}

MCPStatusRequestPayload is the body of an Envelope whose Type == TypeMCPStatusRequest. It asks for the current MCP status of one conversation. Correlation rides Envelope.InReplyTo on the TypeMCPStatus answer, so this payload has no request-id field.

ConversationID is an unverified remote-authored lookup key. The relay decodes it before consulting membership and never logs or returns it as trusted input; the successful answer's id comes from the resolver's daemon-side record. The key is unconditional because absent and empty have the same meaning and a committed fixture pins the complete request shape.

type MCPTogglePayload added in v0.17.0

type MCPTogglePayload struct {
	ConversationID string `json:"conversation_id"`
	ServerName     string `json:"server_name"`
	Enabled        bool   `json:"enabled"`
}

MCPTogglePayload is the body of an Envelope whose Type == TypeMCPToggle (#2419): MCPReconnectPayload's two fields plus the state to move one named MCP server to. Same answer shape, same absence of a request id, and the same split trust in its two strings — see that type's block, which this one does not restate.

Declared flat rather than by embedding MCPReconnectPayload. Embedding would promote the fields for JSON and encode identically, but it would route this verb's wire-shape assertions through a type whose own doc block describes a different verb, and it would couple two wire shapes that are free to diverge later.

ENABLED IS A PLAIN BOOL, NOT A POINTER, and the choice is deliberate in a family where SettingsUpdate reaches for pointers. An absent key therefore decodes as false — "disable" — which is the NON-ESCALATING direction: an omission, a truncation, or a client that forgot the field can only ever turn a server off, never on. A pointer would add a third state (nil) that some layer would then have to interpret, and interpreting it is exactly the judgement internal/relay is forbidden from making on this path — the value crosses the seam as the client sent it and the per-device gate below decides. A plain bool also marshals the key unconditionally, which is what lets the committed fixture pin a complete key set. Contrast marshalMCPToggleEnvelope in internal/streamsup, which does use a pointer: that is the OUTBOUND leg to the claude child, where omitting the key would let the child pick a default, a hazard that has no counterpart on this inbound decode.

type MarkConversationReadPayload added in v0.33.0

type MarkConversationReadPayload struct {
	ConversationID string  `json:"conversation_id"`
	UpTo           *uint64 `json:"up_to"`
}

MarkConversationReadPayload is the body of a mark_conversation_read frame (#2780). Phone → binary. It names a target conversation and the durable history entry id the operator has read up to.

UpTo is a pointer because the key is required: an absent key (or JSON null) decodes to nil and the handler rejects it as protocol.malformed. The uint64 target makes encoding/json enforce the wire range: a negative, fractional, exponent, string, boolean or over-2^64-1 value fails the decode. The reply reuses ConversationUpdatedPayload verbatim.

type MemorySearchProvider added in v0.29.0

type MemorySearchProvider struct {
	ID           string `json:"id"`
	DisplayName  string `json:"display_name"`
	Installed    bool   `json:"installed"`
	Enabled      bool   `json:"enabled"`
	Availability string `json:"availability"`
}

MemorySearchProvider reports installation separately from effective access. An installed but disabled provider has Installed true and Enabled false.

type MemorySearchReport added in v0.29.0

type MemorySearchReport struct {
	Availability string                 `json:"availability"`
	Providers    []MemorySearchProvider `json:"providers"`
}

MemorySearchReport is one agent-and-workspace search-access result. Availability uses the detector's available, unavailable, absent, or unknown vocabulary. An absent provider has no row; providers is always an array when this object is present, including when the detector found no provider rows.

func (MemorySearchReport) MarshalJSON added in v0.29.0

func (r MemorySearchReport) MarshalJSON() ([]byte, error)

MarshalJSON keeps an empty provider list as [] even for a zero-value slice.

type MessagePayload

type MessagePayload struct {
	ConversationID string   `json:"conversation_id"`
	MessageID      string   `json:"message_id"`
	Role           string   `json:"role"`
	Text           string   `json:"text"`
	AttachmentIDs  []string `json:"attachment_ids,omitempty"`
	DeviceName     string   `json:"device_name,omitempty"`
	ClientVersion  string   `json:"client_version,omitempty"`
	ClientSentAt   string   `json:"client_sent_at,omitempty"`
	// QueuedMsgID names the delivered queue entry within ConversationID, matching
	// QueuedItem. Zero omits it for messages without a queue entry, including
	// assistant messages. MessageID is client-chosen and need not be unique.
	QueuedMsgID uint64 `json:"queued_msg_id,omitempty"`
	// SentNow identifies a queued message delivered into a running turn. Clients
	// use its push position; an ordinary drain's late push must not move a settled echo.
	SentNow bool `json:"sent_now,omitempty"`
}

MessagePayload is the body of an Envelope whose Type == TypeMessage (docs/protocol-mobile.md § message). Binary → phone direction; carries either a user-message echo (to other paired devices) or an assistant reply. Role is one of "user", "assistant", "system" per the spec's field table; the type stays string (not a named Role enum) because the binary already treats role-strings as string-typed elsewhere.

AttachmentIDs is set only on the STORED user entry the history log holds (#2596): the ids a send_message named, as the handler resolved them — deduplicated on first occurrence, each past the resolver's canonical-shape check. Same key and element shape as SendMessagePayload.AttachmentIDs. It is omitted when empty, so an assistant emission and an attachment-less user entry marshal exactly as they did before the field existed, and an older decoder ignores the key. It carries ids only, never the on-host path the delivery prompt names.

DeviceName, ClientVersion and ClientSentAt are likewise set only on the stored user entry (#2704): the pairing record's name for the device that sent it, the app version that connection's hello reported (past sessions.AdmitClientVersion), and the client's tap time as the daemon re-formatted it (UTC RFC 3339, client clock, never used for ordering). Each is omitted when empty, so an entry from an older client marshals exactly as before.

type MintPairingPayload added in v0.16.0

type MintPairingPayload struct {
	// DeviceName is the label the minted device is filed under in the registry
	// (devices.Device.Name). OPTIONAL: absent and empty are the SAME case, "the
	// client named no device", which the handler answers by falling back to the
	// label `pyry pair` generates for an unnamed device. There is no presence
	// contract, so there is NO omitempty — RequestSystemPromptPayload's,
	// RequestSessionSettingsPayload's and RequestModelListPayload's stated reason,
	// and keeping the key always on the wire is what lets the committed fixture
	// pin the full shape. TestMintPairingPayload_ZeroValue_KeyPresent reddens if
	// an omitempty is added later for tidiness.
	//
	// AN UNVERIFIED CLAIM, ALWAYS, and the two hazards are named here because
	// MaxDeviceNameBytes does nothing about either. It is rendered to a TERMINAL
	// by `pyry pair list`, so an ANSI escape run in it is a display-forgery vector
	// the renderer owes escaping for; and it is a candidate for a LINE-ORIENTED
	// LOG, the same log-injection shape docs/protocol-mobile.md § Attachments
	// forbids for an unchecked filename. LOGGABLE ONLY AFTER SHAPE VALIDATION,
	// which no code in this package performs.
	//
	// IT NEVER BECOMES A PATH COMPONENT, and that is checked rather than assumed:
	// resolveDevicesPath applies sanitizeName to the INSTANCE name, never to a
	// device name, so this value is a JSON value inside devices.json and nothing
	// more. A future edit that changes that must bring its own canonical-shape
	// check; this bound would not be it.
	DeviceName string `json:"device_name"`
}

MintPairingPayload is the body of an Envelope whose Type == TypeMintPairing (docs/protocol-mobile.md § Minting a pairing from a paired client). Phone → binary direction; an already-paired client asking the daemon to mint a pairing for ANOTHER device.

This is an inbound v2 *control* envelope, structurally like RequestSystemPromptPayload (system_prompt.go): the v2 session manager intercepts it at the dispatch boundary before dispatch.Route is called, so there is no dispatch.Route handler for it. TypeMintPairing's block has the full lane argument and the authentication obligation it places on that handler.

ONE DIRECTION ONLY, phone → binary, so there is no provenance to disambiguate: EVERY FIELD IS AN UNVERIFIED CLAIM, ALWAYS. The frame it is answered with — PairingMintedPayload below — rides the other way and shares no field with it.

NOTHING A CLIENT SENDS IS INPUT TO WHAT THE DAEMON MINTS. The token, the server id, the relay URL and the static pubkey all come from daemon state; this payload names a label and nothing else. That is why there is no nonce, no request id (correlation rides the envelope's InReplyTo — TypeAttachmentStored's decision, transferred unchanged) and no server field, and TestMintPairingPayload_WireKeys pins the whole key set so the absences are checked rather than reviewed.

THERE IS NO FIELD FOR THE REMOTE-PERMISSIONS FLAG, and its absence is a security property rather than an omission. devices.Device.AllowRemotePermissions is documented as never set or carried over the wire, and since #2605 it gates the privileged verbs only — minting a pairing like this one and actuating an MCP server; every authenticated device may answer modals and questions. A field here would let an already-paired client mint a device MORE privileged than an operator granted at the CLI, one that could mint further devices. A MINTED DEVICE IS ALWAYS UNPRIVILEGED; an operator who wants otherwise runs `pyry pair --allow-remote-permissions` with a shell on the host.

A HOSTILE OR TRUNCATED PAYLOAD DECODES TO THE ZERO VALUE rather than to an error for every key-shaped failure, since every key is optional to encoding/json. The ONE decode rejection is the length bound below, and it is the package's first: a DECODE FAILURE IS A REJECTED FRAME, NEVER AN EMPTY-BUT-SUCCESSFUL MINT REQUEST. #2127 answers protocol.malformed on it.

func (*MintPairingPayload) UnmarshalJSON added in v0.16.0

func (p *MintPairingPayload) UnmarshalJSON(b []byte) error

UnmarshalJSON rejects a DeviceName longer than MaxDeviceNameBytes.

THIS IS VALIDATION, NOT NORMALISATION, and it is a deliberate departure from the package's pure-DTO posture rather than a drift into one. SendMessagePayload's UnmarshalJSON — the only other hook here — collapses three empty wire forms and checks nothing; this one refuses. The argument is specific to this field and is not a general licence:

  • Every other bounded string in this package (Filename, AttachmentID) is bounded for a downstream consumer that must check the value's SHAPE anyway, so the constant is cap arithmetic and enforcement belongs at that consumer. device_name has no shape rule at all — it is a free display string — so length is the only check that will ever exist, and there is no second validator downstream to carry it.
  • Three implementations are being written against this contract at once (#2127 and two client slices), none able to see the others. A bound living only in a doc comment is a bound each of them implements differently or forgets.
  • The reject is FAIL-CLOSED. Truncating instead would let the label a client displays differ from the one the daemon stored, on a frame whose whole subject is which device a credential belongs to.

THE ERROR NEVER CARRIES THE BYTES. It names the category, the bound and the observed count — internal/pair's ErrInvalidPayload rule, applied because the value is remote-authored and the rejection reaches a line-oriented log. A device name's LENGTH is not sensitive; its content is untrusted.

UNKNOWN FIELDS STAY IGNORED. This decodes through the alias rather than through a json.Decoder with DisallowUnknownFields, which would turn every future client sending a field this daemon predates into a rejected frame and break the forward-compatibility rule docs/protocol-mobile.md § Application message types states. TestMintPairingPayload_UnknownFieldIgnored pins it against exactly that edit.

The alias type is a defined type with no methods, which is what keeps json.Unmarshal from recursing back into this method — SendMessagePayload's reason in the same direction. The receiver is a pointer, as encoding/json requires for an Unmarshaler, so this writes only through the caller's own value, and it writes NOTHING on the reject path.

type ModalAnswerPayload added in v0.15.0

type ModalAnswerPayload struct {
	ModalID     string `json:"modal_id"`
	OptionID    string `json:"option_id"`
	AnswerToken string `json:"answer_token"`
	AlwaysAllow bool   `json:"always_allow,omitempty"`
}

ModalAnswerPayload is the body of an Envelope whose Type == TypeModalAnswer (docs/protocol-mobile.md § Modal). Phone → binary direction.

This is an inbound v2 *control* envelope, structurally like RequestSnapshotPayload / TypeRekeyRequest: the v2 session manager intercepts it at dispatchAppFrame before dispatch.Route. There is NO dispatch.Route handler — the interception, validation (against the daemon's current outstanding ModalID, #703/#706), and dedup live in the producer.

AnswerToken is a client-minted idempotency key (uniqueness and stability matter, secrecy does not): it lets the daemon collapse a replayed or reordered modal_answer to a no-op (#703). It is NOT the authorization — authorization is ModalID validity (#706) plus the per-device gate (#702).

type ModalCancelPayload added in v0.15.0

type ModalCancelPayload struct {
	ModalID string `json:"modal_id"`
}

ModalCancelPayload is the body of an Envelope whose Type == TypeModalCancel (docs/protocol-mobile.md § Modal). Phone → binary direction; cancels an outstanding modal from the phone.

Like ModalAnswerPayload this is an inbound v2 control envelope intercepted at dispatchAppFrame before dispatch.Route — there is NO dispatch.Route handler.

type ModalDismissedPayload added in v0.15.0

type ModalDismissedPayload struct {
	ModalID string `json:"modal_id"`
	Outcome string `json:"outcome"`
	Source  string `json:"source"`
}

ModalDismissedPayload is the body of an Envelope whose Type == TypeModalDismissed (docs/protocol-mobile.md § Modal). Binary → phone direction; notifies the phone that a modal was resolved.

Outcome is the selected ModalOption.ID when answered, or a producer-defined sentinel for cancel/timeout (plain string; the sentinel vocabulary is #703's, documented not enforced). Source is the closed set {remote, local, timeout}: remote = a phone modal_answer/modal_cancel, local = answered/cancelled at the desktop TTY, timeout = deny-on-timeout fired. Plain string, not a named enum.

type ModalOption added in v0.15.0

type ModalOption struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

ModalOption is a single, ordered choice offered by a ModalShownPayload. ID is the stable identifier ModalAnswerPayload.OptionID and ModalShownPayload.DefaultOptionID reference; Label is the human-readable display text.

type ModalShownPayload added in v0.15.0

type ModalShownPayload struct {
	ConversationID  string             `json:"conversation_id"` // outbound routing/scoping key; daemon-asserted, client filters on it (#1065). Inbound answers carry no conversation_id — see doc.
	ModalID         string             `json:"modal_id"`
	Class           string             `json:"class"`
	Title           string             `json:"title"`
	Prompt          string             `json:"prompt"`
	Options         []ModalOption      `json:"options"`
	DefaultOptionID string             `json:"default_option_id"`
	AlwaysAllow     AlwaysAllowPayload `json:"always_allow"`
	// The remaining fields are optional Claude-authored display context. They
	// are never daemon-derived from tool input or used as permission authority.
	// Reason preserves an open JSON shape; ReasonType preserves an open string
	// vocabulary. DefaultToNo is a client-selection hint, not a timeout verdict.
	Reason      json.RawMessage `json:"reason,omitempty"`
	ReasonType  string          `json:"reason_type,omitempty"`
	BlockedPath string          `json:"blocked_path,omitempty"`
	Description string          `json:"description,omitempty"`
	DefaultToNo bool            `json:"default_to_no,omitempty"`
}

ModalShownPayload is the body of an Envelope whose Type == TypeModalShown (docs/protocol-mobile.md § Modal). Binary → phone direction; surfaces a modal to the phone. It rides the "interactive" capability (#607) — viewing a modal is ungated; answering is gated separately, per-device (#702).

ConversationID is an outbound routing/scoping key (#1065): the daemon asserts it from active.CurrentConversation() so interactive clients filter display by conversation — a modal carrying conversation A's tool title/input summary is scoped to conns following A and never rendered by a conn viewing B. It is daemon-derived, not attacker-derived, and joins the client-side scoping model TurnStatePayload/QueueStatePayload already use. Declared first (leading, no omitempty), mirroring those sibling payloads. The INBOUND anti-forgery model is unchanged: ModalAnswerPayload/ModalCancelPayload carry NO conversation_id, and an answer is authorized by resolving its ModalID server-side against the registry (plus the per-device gate #702) — a phone still cannot assert which conversation an answer targets. Adding this outbound key does not loosen that inbound guarantee.

ModalID is a one-time, opaque, unguessable nonce minted per surfaced modal (by #703). It is the correlation key an inbound answer is resolved against: the daemon matches ModalID to its own outstanding-modal state and never trusts a phone-asserted conversation. Options is ordered — the JSON-array order is the canonical display/selection order. DefaultOptionID MUST equal one of Options[].ID (documented invariant; the producer enforces it). Class is a plain string over a closed wire set (e.g. "permission"), not a named enum (leaf-data convention, matching MessagePayload.Role); the exhaustive class vocabulary is #703's to finalize.

type ModelAnnouncedPayload added in v0.16.0

type ModelAnnouncedPayload struct {
	ConversationID string `json:"conversation_id"`
	Model          string `json:"model"`
	Truncated      bool   `json:"truncated"`
}

ModelAnnouncedPayload is the body of an Envelope whose Type == TypeModelAnnounced (docs/protocol-mobile.md § model_announced, #1616). Binary → phone direction; the wire form of turnevent.ModelAnnounced, which reports the model claude named for the current turn on its system/init line.

Emitted since #1638: the shape was declared here (#1616) so a client could be written against it, and #1638 added turnbridge.MapEvent's case for the variant — the sequencing #1405 used ahead of #1410.

Like RateLimitedPayload it is conversation-scoped rather than turn-scoped, so there is no turn_id, and receiving one neither opens nor closes a turn: a per-turn announcement is not a turn boundary (turnevent.ModelAnnounced's own doc). The bridge (#1638) supplies ConversationID because the internal event carries none. claude's session_id and cwd are deliberately absent for BackgroundTaskStartedPayload's reason plus #1380's — one is claude's session identity and the other the operator's local filesystem path, neither is the daemon's conversation identity, and neither is even declared on the producer's decode target (streamsup's systemInitLine), so this payload cannot carry them even by accident.

The value's semantics are NOT restated here: turnevent.ModelAnnounced's field comments are their single source of truth, in the manner ThinkingProgressPayload delegates its two consumer hazards. Named and delegated: Model is claude's identifier VERBATIM and never empty; claude echoes an identifier at least as specific as the one it was given, so the value is not reliably dated and need not appear in any published model list, which makes a lookup miss ORDINARY rather than an error; and bounded-and-UTF-8-valid is all it is. A consumer-facing statement of each is in docs/protocol-mobile.md § model_announced.

Truncated is a bool rather than the siblings' TruncatedFields []string, following UnrecognizedMessagePayload: this payload bounds a SINGLE string, so a name list would be permanently either nil or ["model"] — a variable-length container carrying one bit, plus a name the reader must check against the only field there is. The slice exists on the background-task and rate-limit payloads because they bound two to four fields and the report has to say which. It is load-bearing either way — a payload that dropped it would present claude's cut text to a phone as complete.

Three v2 payloads already carry a wire field named model — ScreenSnapshotPayload, SessionSettingsPayload and SetSessionSettingsPayload — and all three mean the per-session OVERRIDE, where "" means "inherited default, no override". This one means what claude ANNOUNCED for the turn, and in the ordinary case the two disagree: the override is "" while claude has named a concrete model. The name is kept (turnevent's field name in snake_case, per the convention RateLimitedPayload states) and the distinction is drawn by cross-reference in docs/protocol-mobile.md, which is what reaches a client author reading only one of the existing rows.

SECURITY: Model is a claude-authored string that crossed the subprocess trust boundary. It is safe to RENDER as inert text and must never be fed to an HTML sink, an attribute, or a URL; the daemon bounds it but does not sanitize it — no control-character or terminal-escape stripping happens on this path — so it stays untrusted, model-influenced text all the way to the client, and the render boundary owing the sanitization is the CLIENT's. Its bound is the producer's, decided at construction (internal/streamsup/parser.go's maxModelField), so this struct re-decides no maximum: a second cap here would be a second place the limit is decided, and the two could disagree silently. Nor is there a charset check — internal/relay's validModel bounds a PHONE-supplied override and is deliberately a different rule; applying it here would reject identifiers claude legitimately announces. The constraint on turnevent.ModelAnnounced follows the data onto the wire: it is a REPORT, never a control input, so a client MUST NOT branch security-relevant behaviour on Model.

type ModelListPayload added in v0.16.0

type ModelListPayload struct {
	ConversationID string        `json:"conversation_id"`
	Models         []ModelOption `json:"models"`
	DroppedModels  int           `json:"dropped_models"`
}

ModelListPayload is the body of an Envelope whose Type == TypeModelList (docs/protocol-mobile.md § model_list — that section lands with the fixtures in #1705). Binary → phone direction; the wire form of the model inventory claude returns from a control_request with subtype initialize: the set of models it will accept for this conversation. A SNAPSHOT of what claude will accept, not a delta, and conversation-scoped rather than turn-scoped — receiving one neither opens nor closes a turn.

Declared here (#1704) ahead of its producer so a client can be written against the shape — the sequencing #1405 used ahead of #1410 and #1616 ahead of #1638. The producer has since landed: turnbridge.MapEvent's turnevent.ModelList arm constructs it (#1848), and cmd/pyry's resolveBoundModelList (#1857) is a second production path that routes a session's retained list back through that same arm rather than filling the fields itself.

ConversationID is present and unfilled by this ticket — the producer supplies it at mapping time, the seam every v2 interactive payload uses. claude's own session_id is deliberately absent for BackgroundTaskStartedPayload's reason: claude's session identity is not the daemon's conversation identity.

Models is claude's list reduced to ONE ROW PER FAMILY, in claude's own order, truncated from the tail by the producer. Claude Code publishes its family rows (default, opus, fable, sonnet, haiku) followed by pinned rows (claude-opus-5, claude-opus-4-7 and more); a pyry session follows the latest model of a family, so 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). That runs where streamsup first reads the list, before the entry cap, so DroppedModels below counts rows cut from the reduced list. The key is always present on the wire and never null; see MarshalJSON.

DroppedModels is how many entries the producer cut beyond its entry cap that this frame does NOT carry; 0 when nothing was dropped, so the list's true size is len(Models) + DroppedModels. The decode now COUNTS IT (#1812): streamsup's maxModelListEntries bounds the entry count and turnevent.ModelList.DroppedModels carries what it cut, which is this field's honest source. #1848 joined the two: MapEvent's arm carries turnevent.ModelList.DroppedModels through verbatim and never recomputes it from len(Models). The field was declared ahead of both (#1704) because a wire with nowhere to put a drop discards it silently, and a permanent 0 reads as "nothing was dropped", which is a lie rather than a gap. The count reports here rather than as a name in a top-level truncated_fields — which is why this payload has none, BackgroundTaskRosterPayload's stated reason — because a name-only report loses HOW MANY were lost, and each dimension reports where it is decided: a text cut is a property of one entry and rides that entry as ModelOption.TruncatedFields.

A lookup can MISS, and that is ordinary rather than an error. claude announces an identifier at least as specific as the one it was given (turnevent.ModelAnnounced's own doc, measured in #1601), so a client resolving a model_announced identifier against this list may find nothing; this shape does not assume every announced identifier appears here. ModelOption.DisplayName is the intended join — the announcement names a concrete dated identifier while a client's rows are alias families.

func (ModelListPayload) MarshalJSON added in v0.16.0

func (p ModelListPayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Models to an empty array, so a model list always serialises as "models":[] and never as "models":null.

This implements BackgroundTaskRosterPayload.MarshalJSON's reason unchanged, and that whole rationale transfers: omitempty is out because an empty list is a POSITIVE statement rather than an absence, and between null and [], [] reads as an empty list where null reads as absent/unknown, so a client decoding into a non-optional array type never has to branch. ModelOption.MarshalJSON normalises its own EffortLevels for a DIFFERENT reason — read it there, so the asymmetry is not taken for an accident — and deliberately leaves TruncatedFields alone.

This method cannot do the entry's job for it. Assigning a fresh slice to this copy's own Models field is safe, but reaching THROUGH it into p.Models[i] would mutate the caller's backing array, which for a shared payload is a data race as well as a correctness bug; and a payload-level normalisation would not fire at all when a ModelOption is marshalled on its own.

Value receiver, so it applies to the value form a round trip and a bridge both take, and so the substitution lands on a copy rather than on the caller's slice. The type alias is the standard indirection that keeps json.Marshal from recursing back into this method.

type ModelOption added in v0.16.0

type ModelOption struct {
	ResolvedModel    string   `json:"resolved_model"`
	Value            string   `json:"value"`
	DisplayName      string   `json:"display_name"`
	EffortLevels     []string `json:"effort_levels"`
	SupportsAutoMode bool     `json:"supports_auto_mode"`
	TruncatedFields  []string `json:"truncated_fields"`
	Agent            string   `json:"agent,omitempty"`
	Family           string   `json:"family,omitempty"`
}

ModelOption is one row of a ModelListPayload (docs/protocol-mobile.md § model_list, #1704). Its fields are a subset of the per-entry keys claude's initialize reply carries and nothing invented. description and supportsFastMode are deliberately not carried — neither has a named consumer — and supportsEffort is subsumed by EffortLevels once the empty encoding below is decided. Adding a field later is cheap, and every entry multiplies against the 65519-byte v2 application-envelope cap.

ResolvedModel is what Value resolves to RIGHT NOW: the concrete identifier. It closes the question pyrycode-desktop#561 raised and could not — that ticket's shape is "send the family name, it resolves to the newest in the family", and it flags that the operator is then moved to a new model without choosing to. Publishing the resolution BEFORE the first turn is what lets a client show which model a family currently means, instead of inferring it from an announcement after the fact.

Value is the argument you pass. After the producer's family reduction (see ModelListPayload.Models) it is a family name on every row of a family claude publishes one for: an alias (sonnet), a bracketed variant (opus[1m]), or default. Only a family claude publishes no family row for keeps one pinned id, its newest (claude-fable-5[1m] in a 2.1.239 capture). A client still cannot derive a family by splitting Value on "-"; a multi_agent client reads Family. A pinned id a client sends anyway is resolved to its family by the daemon before it is checked against this list or stored.

Value round-trips, and a client author reading only this struct has to be told what shape does. The only inbound path that accepts a model is set_session_settings, gated by internal/relay's validModel, whose rule (widened at #1838 for exactly these rows) accepts "" or, within a 64-byte bound, a value whose first byte is alphanumeric, whose remaining bytes are in [A-Za-z0-9._-], and which may carry ONE trailing bracket group — non-empty, balanced, unnested, the value's final element, and drawn from that same closed byte class. Every value claude has been measured to publish satisfies it, the bracketed variant rows included. The group is bounded that way rather than by adding two bytes to the charset because the rule is #845's argv-injection defense: read validModel for what each clause buys and for the two sinks that depend on it.

DisplayName is claude's human label, carried because it is the cleanest way to match a per-turn model_announced identifier to a client's alias-family row without a mapping table.

EffortLevels are the reasoning-effort levels this model supports. The key is always present on the wire and never null — see MarshalJSON, and read its rationale, which is NOT ModelListPayload.MarshalJSON's. Measured 2026-08-22, all five levels claude returns (low, medium, high, xhigh, max) are accepted by internal/relay's validEffort, whose enum is CLOSED — so a level claude adds in future would be published here and refused inbound. Since #1838 widened validModel this is the ONLY field in the struct carrying that direction hazard; Value carried the same one until then, and validEffort is deliberately not widened alongside it because no level claude publishes is refused today.

SupportsAutoMode is whether claude accepts auto permission mode for this model: claude refuses the request per model, so a client greys the option out when this is false (pyrycode-desktop#682). It collides with nothing in the daemon's own vocabulary — set_permission_mode carries default / acceptEdits / bypassPermissions / plan, and auto is claude's mode name, which the daemon does not currently send. Absent in claude's reply (Haiku's entry omits it) decodes to false, which is the correct reading.

TruncatedFields names THIS row's cut fields, null when nothing was cut. The producer records FOUR names, in this order: "resolved_model", "value", "display_name", "effort_levels". "effort_levels" is the one reporting on a LIST rather than a value, and it covers three outcomes — an element cut to fit the per-element cap, the list shortened to fit the count cap, or both — appearing at most once per entry in every case, because the report names FIELDS and a list is one field. turnevent.ModelOption's TruncatedFields is the source of truth for that vocabulary. Deliberately NOT normalised the way EffortLevels is — see MarshalJSON. It is load-bearing rather than decoration: a row that dropped it would present claude's cut text to a phone as complete, and would offer back a Value the client was never told was truncated.

SECURITY: ResolvedModel, Value, DisplayName and every string in EffortLevels are claude-authored strings that crossed the subprocess trust boundary. They are safe to RENDER as inert text and must never be fed to an HTML sink, an attribute, or a URL; the daemon bounds them but does not sanitize them — no control-character or terminal-escape stripping happens on this path — so they stay untrusted, model-influenced text all the way to the client, and the render boundary owing the sanitization is the CLIENT's. Their bound is the producer's, decided at construction, so this struct re-decides no maximum and declares no charset check: a second cap here would be a second place the limit is decided, and the two could disagree silently.

The family's convention sentence — it is a REPORT, never a control input — needs one amendment here, because Value is the first field in the family a client is meant to send BACK. Publishing a value does not make it trusted: it is still claude's text arriving on an inbound path, and the daemon re-validates it at internal/relay's validModel rather than trusting that it came from a list the daemon itself published.

Agent and Family are set only on the merged list a multi_agent client receives (#2651): Agent is AgentClaude or AgentCodex, and Family is a Codex entry's family name or the family alias of a Claude entry's Value, which is the Value itself on a family row. Both are omitempty, and that is what keeps every other client's frame byte-identical to the one it read before they existed: no producer on an older client's path sets them, so neither key reaches it.

func (ModelOption) MarshalJSON added in v0.16.0

func (o ModelOption) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil EffortLevels to an empty array, so a row always serialises as "effort_levels":[] and never as "effort_levels":null. It deliberately leaves TruncatedFields alone, which stays null when nothing was cut.

The reason is NOT ModelListPayload.MarshalJSON's, and the asymmetry between the two is not an accident. An empty effort list is not a positive statement here, it is a COLLAPSE: Haiku's entry omits supportedEffortLevels entirely, and a client's behaviour is identical for absent and empty (no effort control). The wire therefore states ONE position for both, and [] is the one that spares every row an optional-array branch. The daemon-internal value does NOT keep the absent/empty distinction either: turnevent.ModelOption.EffortLevels reads an absent key, a JSON null and a published empty array as ONE reading, spelled nil (#1828). The wire's position is stated here independently of that spelling, because an undeclared position is one #1848 would have had to invent — and, the two having landed on the same collapse, #1848's mapping needed no fork to bridge.

TruncatedFields is exempt for BackgroundTaskRosterPayload.MarshalJSON's own carve-out reason, unchanged: nil and [] say the identical thing there ("nothing was cut") and no consumer branches on the difference.

This method cannot be folded into the payload's: a payload marshaller normalising entries in place would mutate the caller's backing array unless the slice were copied first, and it would not fire at all when a ModelOption is marshalled on its own.

Value receiver and the type alias, for ModelListPayload.MarshalJSON's reasons.

type ModelRefusalFallbackPayload added in v0.16.0

type ModelRefusalFallbackPayload struct {
	ConversationID  string   `json:"conversation_id"`
	OriginalModel   string   `json:"original_model"`
	FallbackModel   string   `json:"fallback_model"`
	Scope           string   `json:"scope"`
	RefusalCategory string   `json:"refusal_category"`
	Banner          string   `json:"banner"`
	TruncatedFields []string `json:"truncated_fields"`
	DroppedFields   []string `json:"dropped_fields"`
}

ModelRefusalFallbackPayload reports that claude refused a turn on one model and retried it on another. It is conversation-scoped: the daemon has no request or claude message identity that can honestly join the refusal to an assistant_delta, so no turn_id, request_id, or message UUID is published. ModelAnnouncedPayload remains the authority on which model claude is running.

Every value except ConversationID is claude-authored, bounded by the producer and not sanitized. OriginalModel and FallbackModel are opaque identifiers; Scope and RefusalCategory are open strings carried verbatim. In particular, RefusalCategory is claude's assertion about the request, never a daemon finding and never an actuator. Banner may echo refused user text and must be rendered as inert text attributed to claude, never fed to an HTML sink, URL, command, or shell.

TruncatedFields and DroppedFields use this frame's wire-key vocabulary. Nil means no published field was reported and intentionally marshals as null, not []; neither field uses omitempty and this type must not gain a MarshalJSON.

type ModelRefusalNoFallbackPayload added in v0.16.0

type ModelRefusalNoFallbackPayload struct {
	ConversationID  string   `json:"conversation_id"`
	OriginalModel   string   `json:"original_model"`
	RefusalCategory string   `json:"refusal_category"`
	Banner          string   `json:"banner"`
	TruncatedFields []string `json:"truncated_fields"`
	DroppedFields   []string `json:"dropped_fields"`
}

ModelRefusalNoFallbackPayload reports that claude refused a turn without retrying it on another model. It is conversation-scoped because the daemon has no request or claude message identity that can join it to an assistant_delta. ModelAnnouncedPayload remains the current-model authority.

Every value except ConversationID is bounded but unsanitized claude-authored data. OriginalModel is opaque and RefusalCategory is claude's open assertion, never a daemon finding or actuator. Banner may echo refused user text and must be rendered as inert, claude-attributed text, never passed to an HTML sink, URL, command, or shell.

TruncatedFields and DroppedFields use this frame's wire-key vocabulary. Nil means no published field was reported and intentionally marshals as null, not []; neither field uses omitempty and this type must not gain a MarshalJSON.

type NewSessionPayload added in v0.16.0

type NewSessionPayload struct {
	ConversationID string `json:"conversation_id,omitempty"`
}

NewSessionPayload is the body of an Envelope whose Type == TypeNewSession (docs/protocol-mobile.md § New session). Phone → binary direction.

This is an inbound v2 *control* envelope, structurally like DequeueMessagePayload: the v2 session manager intercepts it at dispatchAppFrame before dispatch.Route, and there is NO dispatch.Route handler — resolving ConversationID and rotating that conversation's session is the handler's (#2099) job. Unlike its siblings the whole payload is OPTIONAL: the frame carried none at all until #2099, so an un-upgraded client sends a bare envelope and MUST keep working.

ConversationID is untrusted phone input and is a validated LOOKUP KEY, never authorization and never a path component — the rule docs/protocol-mobile.md already publishes for request_attachment and, since #2142, for attachment_chunk. Absent, empty, or a body that does not decode at all are ONE value and one meaning: rotate the conversation the daemon's own cursor points at, which is the pre-#2099 behaviour verbatim. omitempty keeps that the shape a client with nothing to name actually emits, so the wire has one canonical bare form.

type NullableString added in v0.20.0

type NullableString struct {
	// contains filtered or unexported fields
}

NullableString preserves an optional nullable JSON string's three states. Its zero value is unavailable and can be omitted with the omitzero tag; NewNullableString(nil) is present JSON null, and a non-nil value is a present JSON string. The type stays comparable so payloads containing it remain comparable.

func NewNullableString added in v0.20.0

func NewNullableString(value *string) NullableString

NewNullableString returns a present nullable string. A nil value represents explicit JSON null rather than omission.

func (NullableString) IsZero added in v0.20.0

func (s NullableString) IsZero() bool

IsZero reports whether the nullable string is unavailable and should be omitted by encoding/json's omitzero handling.

func (NullableString) MarshalJSON added in v0.20.0

func (s NullableString) MarshalJSON() ([]byte, error)

MarshalJSON preserves a present string or null. The containing field's omitzero tag handles the unavailable state before this method is called.

func (*NullableString) UnmarshalJSON added in v0.20.0

func (s *NullableString) UnmarshalJSON(data []byte) error

UnmarshalJSON records that the key was present and accepts only a JSON string or null.

func (NullableString) Value added in v0.20.0

func (s NullableString) Value() (*string, bool)

Value returns the nullable string and whether its key was present. A present nil value represents explicit JSON null.

type PairingMintedPayload added in v0.16.0

type PairingMintedPayload struct {
	// Pairing is the pair.Encode string: the {server, relay, token,
	// server_static_pubkey} tuple as base64url (URL-safe alphabet, no padding).
	// A CREDENTIAL — see the block above for the handling rule.
	Pairing string `json:"pairing"`
}

PairingMintedPayload is the body of an Envelope whose Type == TypePairingMinted (docs/protocol-mobile.md § Minting a pairing from a paired client). Binary → phone direction; the daemon's answer to a mint_pairing, correlated by InReplyTo.

PAIRING IS A PLAINTEXT BEARER CREDENTIAL. It is never logged, no field decoded out of it is ever logged, and it must never leave the AEAD-sealed envelope — under docs/protocol-mobile.md § Security model threat 3 the relay sees only ciphertext, and carrying this string anywhere else would hand the token to the one party v2 exists to keep it from. internal/pair's package doc binds ITS callers; that rule does not reach a different type in a different package on its own, which is why it is restated here.

THE ENCODED STRING TRAVELS ALONE, and that is the frame's whole shape decision. The four fields inside it are pair.Payload's — server, relay, token, server_static_pubkey — and three of them are values the asking client already holds: it is paired, and connected through that relay to that server. Only the token is new, and it is the secret. Carrying the four flat alongside would put a bearer credential on the wire twice and invite a client to treat the loose copy as the less sensitive one. Carrying none of them leaves one source of truth, keeps the frame near 400 bytes against the 65519-byte application-envelope cap, and means this package needs no import of internal/pair — which is what keeps this leaf package leaf-shaped.

NO FIELD OF THE REQUEST IS ECHOED INTO THE REPLY, and that is checked rather than borrowed from a neighbour that enumerated different fields: pair.Payload has exactly four fields and none of them is a name, so this payload is daemon-authored end to end and the client's device_name reaches no outbound frame.

OPAQUE ON THIS WIRE. A client hands the string to its existing pairing dialog unchanged — both the phone and the desktop already accept a pasted pair.Encode string — so no client needs to parse one, and pair.Decode remains the only decoder anywhere.

NO EXPIRY FIELD, deliberately. devices.Device.RedeemBy stamps an unredeemed pairing's deadline, but its semantics are #1528/#1529's and this slice cannot honour them; publishing the field ahead of the behaviour is the shape #2090 stands as the example of. Whether a client should see the deadline is #2127's call — it is the first ticket blocked on the window work and so the first that knows the answer.

CORRELATION RIDES THE ENVELOPE'S InReplyTo, so the payload carries NO REQUEST-ID KEY and no conversation id — this verb is not conversation-scoped at all.

type PromoteConversationPayload

type PromoteConversationPayload struct {
	ConversationID string `json:"conversation_id"`
	Name           string `json:"name"`
	Cwd            string `json:"cwd"`
}

PromoteConversationPayload is the body of a promote_conversation frame (docs/protocol-mobile.md § promote_conversation). Phone → binary. All three fields are spec-required: a promoted conversation must carry a name and an effective cwd, and the conversation_id must resolve to an existing row.

type Question added in v0.16.0

type Question struct {
	Text        string           `json:"question"`
	Header      string           `json:"header"`
	Options     []QuestionOption `json:"options"`
	MultiSelect bool             `json:"multi_select"`
}

Question is one question of a QuestionShownPayload batch, carrying claude's own per-question keys: the question text, its header, its ordered options and its multiSelect flag.

Text's wire key is question, claude's own key, as SlashCommand keeps all four of claude's. The Go name diverges only because Question.Question stutters at every call site.

MultiSelect is a plain bool on the wire, key multi_select — claude's camelCase multiSelect snake-cased, exactly as SlashCommand.ArgumentHint snake-cases argumentHint. Under the no-omitempty discipline the wire always states a position, so an absent key is not representable outbound and there is no tri-state to mint here; the absent-versus-well-formed-false question is real but it is #1965's, on the decode side.

Options is ordered, always present on the wire and never null; see MarshalJSON.

This shape carries NO TRUNCATION REPORT, unlike SlashCommand.TruncatedFields and ModelOption.TruncatedFields, and the omission is a decision rather than an oversight. Its consequence is #1965's: a producer that cuts a long question or description has nowhere to report the cut, so an over-long field must be rejected fail-closed rather than silently truncated — or this type comes back and grows the field. Cutting silently would present claude's truncated text to a client as complete.

SECURITY: Text, Header, and every QuestionOption's Label and Description are CLAUDE-authored strings that crossed the subprocess trust boundary to a client render surface — ModelOption's trust level, not SlashCommand's lower workspace-authored one. They are safe to RENDER as inert text and must never be fed to an HTML sink, an attribute, or a URL; the daemon does not sanitize them — no control-character or terminal-escape stripping happens on this path — so they stay untrusted text all the way to the client, and the render boundary owing the sanitization is the CLIENT's. Their bound is the parse's (#1965) and the producer's (#1973): this struct re-decides no maximum and declares no charset check, because a second cap here would be a second place the limit is decided and the two could disagree silently.

func (Question) MarshalJSON added in v0.16.0

func (q Question) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Options to an empty array, so a question always serialises as "options":[] and never as "options":null.

The out-of-contract reason is QuestionShownPayload.MarshalJSON's, stated there once for both arrays because it is genuinely the same one — read it there rather than expecting a distinction this method does not have. ModelOption's normaliser and its payload's are the opposite case, two in one family whose reasons really do differ, each stating its own.

The one reason that is this method's alone: it CANNOT BE FOLDED into the payload's. A payload marshaller normalising entries in place would reach through p.Questions[i] into the caller's backing array, which for a payload shared between an emitter goroutine and a per-connection fan-out is a data race as well as a correctness bug; and it would not fire at all when a Question is marshalled on its own.

Value receiver and the type alias, for QuestionShownPayload.MarshalJSON's reasons.

type QuestionAnswerEntry added in v0.16.0

type QuestionAnswerEntry struct {
	QuestionIndex int      `json:"question_index"`
	Values        []string `json:"values"`
}

QuestionAnswerEntry is one question's answer inside a QuestionAnswerPayload: which question, and the values chosen for it.

It is QuestionAnswerEntry rather than QuestionAnswer because QuestionAnswer beside QuestionAnswerPayload differs only by the family's frame-body suffix, so the pair reads as "the payload of a QuestionAnswer" rather than "the body of a question_answer frame". The nested types under question_shown did not need the disambiguation — Question is not QuestionShown — so this suffix is bought rather than inherited.

QuestionIndex is the entry's index into the batch's questions array, the canonical display order QuestionShownPayload publishes. The wire key is question_index and not index because an entry quoted or logged on its own must not read as "the index of this answer". The daemon reads the question text from its own parked copy keyed on the payload's QuestionBatchID; nothing about the question travels back.

THE INDEX IS CARRIED, NEVER RANGE-CHECKED HERE, and the consequence has to be loud because it is a panic rather than a wrong answer: subscripting the parked batch with a negative or over-large index panics, so #1985 owes an EXPLICIT range check before indexing. Two more obligations fall on the same reader and are named here rather than left to be discovered — a duplicate or missing index across entries must not resolve to a silently partial or last-write-wins answer, and an Answers array far longer than the parked batch must not become unbounded work per inbound frame. internal/protocol enforcing no bound is the same design that leaves the outbound batch's bounds to questionbridge.Parse (#1965); it is not a guarantee this type makes.

It is a plain int rather than an unsigned type on purpose. A uint would reject -1 at decode and still accept 1<<62 — half-closing the door while turning a range problem into a decode-error surprise — and it would smuggle a bounds decision into a package that makes none.

Values are the strings chosen for this question, ordered, always present and never null; see MarshalJSON. They are CLIENT-AUTHORED AND OPAQUE, and they are NEVER CHECKED against the batch's offered labels: claude's contract permits free text anywhere and requires no value to be one of the labels, so a validator rejecting an unlisted value would reject a legal answer. More than one value is the multi_select case; one is the ordinary one.

SECURITY: these strings are REMOTE-AUTHORED — they crossed the network from a paired but not trusted client, the opposite direction from Question's claude-authored ones, so § Security model's threat 1 does not describe them. What they do reach is claude's context, via #1985 feeding them back as the blocked tool call's result. That grants nothing new: a paired client can already put arbitrary text into the conversation with send_message, so an answer sits at exactly that trust tier — recorded because the shape invites the opposite reading, that an answer is somehow more constrained than a message.

func (QuestionAnswerEntry) MarshalJSON added in v0.16.0

func (e QuestionAnswerEntry) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Values to an empty array, so an entry always serialises as "values":[] and never as "values":null.

The out-of-contract reason is QuestionAnswerPayload.MarshalJSON's, stated there once for both arrays because it is genuinely the same one — read it there rather than expecting a distinction this method does not have.

The one reason that is this method's alone is Question.MarshalJSON's, and it transfers verbatim: it CANNOT BE FOLDED into the payload's. A payload marshaller normalising entries in place would reach through p.Answers[i] into the caller's backing array, which for a payload shared between goroutines is a data race as well as a correctness bug; and it would not fire at all when an entry is marshalled on its own.

Value receiver and the type alias, for QuestionAnswerPayload.MarshalJSON's reasons.

type QuestionAnswerPayload added in v0.16.0

type QuestionAnswerPayload struct {
	QuestionBatchID string                `json:"question_batch_id"`
	AnswerToken     string                `json:"answer_token"`
	Answers         []QuestionAnswerEntry `json:"answers"`
}

QuestionAnswerPayload is the body of an Envelope whose Type == TypeQuestionAnswer (#1983). PHONE → BINARY direction — the first inbound frame in this family; everything above it is outbound. It carries the operator's selections for a batch question_shown surfaced.

Like ModalAnswerPayload this is an inbound v2 CONTROL envelope, structurally like RequestSnapshotPayload / TypeRekeyRequest: it is intercepted at internal/relay/v2session.go's dispatchAppFrame BEFORE dispatch.Route, and there is no dispatch.Route handler for it. #1984 added that case and the handler behind it, which decodes this shape and hands it to a resolver seam; #1985 resolves an answer against the daemon's parked batch. The guard classification that follows from being switch-intercepted is argued in TypeQuestionAnswer's doc block (codes.go); read it there.

There is NO conversation_id, though question_shown carries one, and QuestionDismissedPayload's reason transfers whole: the batch id is the sole correlation key, and a shape carrying both would admit a disagreeing pair someone has to adjudicate. Here that absence is also the SECURITY property — ModalAnswerPayload's, unchanged: the daemon resolves QuestionBatchID against its own outstanding-batch state and never trusts a phone-asserted conversation.

AnswerToken is ModalAnswerPayload's field verbatim, including its reasons: a CLIENT-MINTED IDEMPOTENCY KEY whose uniqueness and stability matter and whose secrecy does not, and which is NOT the authorization. The daemon's actual dedup is the one-shot consume of QuestionBatchID, exactly as modal_answer's is of ModalID. Neither field here is a secret and both are safe to log — stated so that #1984's handler neither invents a redaction rule nor assumes one exists.

Answers is ordered, always present on the wire and never null; see MarshalJSON. ARRAY ORDER IS NOT THE CORRELATION: a client should emit entries in batch order, but QuestionAnswerEntry.QuestionIndex is what selects, so a decoder must never infer the question from an entry's array position.

No field carries omitempty, § Modal's and QuestionShownPayload's discipline unchanged.

THIS PACKAGE ENFORCES NO BOUNDS ON THIS SHAPE, by the same design that leaves the outbound batch's bounds to questionbridge.Parse. Answers may be arbitrarily long, an entry may repeat or omit an index, and a value may be arbitrarily large; the only operative limit today is the transport's AEAD frame cap, which bounds total bytes and not entry count. Those are obligations on whoever decodes (#1984) and resolves (#1985), and they are enumerated on QuestionAnswerEntry rather than implied here. One belongs to the decode itself and is DISCHARGED by #1984's handler: a decode failure MUST be a rejected frame, never an empty-but-successful answer, and its error must not embed the raw payload — those bytes are remote-authored and nothing on this path strips terminal escape sequences. The rule stays stated as a rule because it binds every future decoder of this shape, not only the first; note that it is a rule about a decode ERROR, so a payload of `null` — which decodes cleanly into the zero value — is not a rejected frame but an unknown batch, and judging it is the resolver's, not the decoder's.

func (QuestionAnswerPayload) MarshalJSON added in v0.16.0

func (p QuestionAnswerPayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Answers to an empty array, so an answer always serialises as "answers":[] and never as "answers":null.

The reason is genuinely SHARED with QuestionAnswerEntry.MarshalJSON's Values, so it is stated once here for both. Both empty arrays are OUT OF CONTRACT: an answer with no entries says nothing a refusal does not say better, which is why question_refused is its own type, and an entry with no values selects nothing. [] is the encoding that leaves such a frame decodable by a client whose array type is non-optional, where null fails that decode outright — the client-decode half of BackgroundTaskRosterPayload.MarshalJSON's rationale, and the other half ("an empty list is a positive statement") deliberately does not transfer, for QuestionShownPayload.MarshalJSON's reason.

Value receiver, so the substitution lands on a copy rather than on the caller's slice, and the type alias keeps json.Marshal from recursing back into this method — SlashCommandListPayload.MarshalJSON's reasons.

type QuestionDismissedPayload added in v0.16.0

type QuestionDismissedPayload struct {
	// QuestionBatchID is the batch being cleared: QuestionShownPayload's own
	// nonce, echoed back. A client matches on it and clears nothing when it does
	// not recognise the value.
	QuestionBatchID string `json:"question_batch_id"`

	// Outcome is how the batch ended — a PRODUCER-DEFINED SENTINEL, plain string,
	// vocabulary owned by #1973/#1985 and documented rather than enforced, exactly
	// as ModalDismissedPayload.Outcome is #703's.
	//
	// IT MUST NEVER CARRY A CLAUDE-AUTHORED OPTION LABEL. The rule is stated
	// positively because the natural implementation violates it: QuestionOption
	// carries no id and claude's answer protocol selects by label, so an answer
	// path reporting which option was chosen reaches for that string first — and
	// it crossed the subprocess trust boundary. Putting it here would silently
	// move this frame to question_shown's trust tier while its published
	// provenance still said daemon-asserted, and a client would render it as
	// trusted chrome. A client that needs the label reads it from the batch it
	// already holds, keyed on QuestionBatchID.
	Outcome string `json:"outcome"`

	// Source is what resolved the batch. Plain string, NOT modal_dismissed's
	// closed {remote, local, timeout} — that set is provably short here, because
	// two of the producer's terminal paths (a caller disconnect, a daemon
	// shutdown) have no member in it and neither is a timeout nor an answer.
	// TypeQuestionDismissed's doc block carries the per-value carry-over reading;
	// docs/protocol-mobile.md § Question publishes it.
	//
	// A client must read an UNRECOGNISED value as "resolved, cause unknown" and
	// never as an answer. Getting that backwards renders a daemon safe-deny as the
	// operator's own choice, and the values a client written today will not
	// recognise are precisely the two the producer has yet to name.
	Source string `json:"source"`
}

QuestionDismissedPayload is the body of an Envelope whose Type == TypeQuestionDismissed. Binary → phone direction; the frame that retires a batch a client is rendering, so no panel is left up for an ask that is already dead. Declared by #1974, emitted by #1973 (the no-answer terminal paths) and #1985 (the answered one); nothing constructs it here.

Field for field with ModalDismissedPayload, including the ABSENCES. QuestionBatchID plays ModalID's role — the nonce QuestionShownPayload carries, which is what matches a dismissal to the batch it clears.

There is NO conversation_id, though question_shown carries one, and the modal frame's reason transfers whole: the batch id is the sole correlation key, and a shape carrying both would admit a disagreeing pair someone has to adjudicate. A client holding the batch already knows its conversation.

No omitempty on any field, § Modal's and QuestionShownPayload's discipline unchanged, and NO MarshalJSON: there is no slice field here, so there is no nil→[] normalisation to perform. QuestionShownPayload.MarshalJSON's backing-array data-race argument is specific to a normaliser reaching through a shared slice and does not transfer — do not add one here by analogy to the sibling.

SECURITY: this frame carries NO CLAUDE-AUTHORED BYTE, which is the property that separates it from QuestionShownPayload's trust tier, and it holds only because Outcome does what its paragraph says. All three fields are daemon-asserted. Consequences worth having in one place: § Security model's threat 1 (prompt injection reaching a remote render surface) does NOT land on this frame; no field can carry a byte of the parked tool input into a log; and the frame's length is daemon-determined rather than subprocess-influenced, which matters in a family that ships no truncated_fields and so could not report a cut.

The nonce is DEAD once this frame lands, and receiving it is not a capability. A retired batch resolves nothing server-side, the way a stale modal_id resolves nothing under first-answer-wins (#703/#706). It is echoed to exactly the interactive-capability-gated audience that received question_shown, so disclosure widens nothing.

type QuestionOption added in v0.16.0

type QuestionOption struct {
	Label       string `json:"label"`
	Description string `json:"description"`
}

QuestionOption is one choice offered by a Question: Label is the short display text, Description the longer line under it. It is QuestionOption rather than a bare Option because ModalOption already exists in this package, and a bare Option beside it would read as the generic one.

label and description are the COMPLETE per-option key set, and that is measured rather than assumed. claude's contract gives each option an optional preview carrying an HTML fragment, emitted only when toolConfig.askUserQuestion's previewFormat is set; pyry never sets it — neither previewFormat nor toolConfig appears anywhere under cmd/ or internal/ (verified 2026-09-01) — so preview is absent BY CONSTRUCTION rather than dropped. Recorded the way SlashCommandListPayload records its own measured key set, so that if pyry ever sets previewFormat the first reader finds the sentence saying why the field is not here.

There is no id, unlike ModalOption's {id, label}: claude's answer protocol selects an option by its LABEL. The inbound answer (#1983) therefore does NOT identify an option by echoing that claude-authored string back — a selection names its question by INDEX and carries client-authored values, so no label makes the return trip; see QuestionAnswerEntry. Publishing a label here would not have made it trusted on the way back either way — the amendment ModelOption.Value's report-only convention sentence carries — and the daemon resolves an answer against its own parked copy regardless.

The same label is why QuestionDismissedPayload.Outcome is forbidden from carrying one: see that field's paragraph.

SECURITY: both strings are covered by Question's paragraph, which credits all four of the batch's claude-authored strings at once.

type QuestionRefusedPayload added in v0.16.0

type QuestionRefusedPayload struct {
	QuestionBatchID string `json:"question_batch_id"`
	AnswerToken     string `json:"answer_token"`
}

QuestionRefusedPayload is the body of an Envelope whose Type == TypeQuestionRefused (#1983). Phone → binary direction; the operator declined to choose, so the batch is resolved without any selection.

It is its OWN TYPE rather than a QuestionAnswerPayload with an empty Answers array or a nullable flag, mirroring TypeModalCancel beside TypeModalAnswer and following the same precedent question_dismissed set: a distinct meaning gets a distinct type, so a reader routes on the frame's name rather than on a value's shape. A refusal carries no answers, and a shape able to express "answered with nothing" would need someone to adjudicate it against a genuine refusal.

Field for field with QuestionAnswerPayload minus Answers, INCLUDING THE ABSENCE: no conversation_id, for that type's reasons. AnswerToken is carried — a refusal is as replayable as an answer, and the daemon's dedup is the same one-shot consume of QuestionBatchID. No omitempty on either field.

NO MarshalJSON: there is no slice field here, so there is no nil→[] normalisation to perform. QuestionAnswerPayload.MarshalJSON's backing-array argument is specific to a normaliser reaching through a shared slice and does not transfer — do not add one here by analogy to the sibling, the note QuestionDismissedPayload carries for the same reason.

SECURITY: this frame carries NO FREE TEXT AT ALL, which makes it the narrowest surface in the family — both fields are ids a client echoes back. Like its sibling it is switch-intercepted as of #1984, and being intercepted grants no inbound capability: that handler applies no authorization, and what keeps it fail-safe is a resolver seam left nil at every construction site. The interactive gate and the per-device answer gate (#702) stay the resolver's to apply, default deny, with #1986 installing the latter before anything is wired.

type QuestionShownPayload added in v0.16.0

type QuestionShownPayload struct {
	ConversationID  string     `json:"conversation_id"`
	QuestionBatchID string     `json:"question_batch_id"`
	Questions       []Question `json:"questions"`
}

QuestionShownPayload is the body of an Envelope whose Type == TypeQuestionShown. Binary → phone direction; the wire form of one clarifying-question batch. The name is the mechanical <Type>Payload the family uses (TypeModalShown → ModalShownPayload, TypeSlashCommandList → SlashCommandListPayload).

ConversationID is ModalShownPayload's #1065 outbound routing/scoping key, unchanged and for its reasons: daemon-asserted, never filled from claude's tool input, so interactive clients filter display by conversation. Present and unfilled by this ticket — the producer supplies it at mapping time.

QuestionBatchID plays ModalID's role exactly, and all four of that paragraph's properties carry across: a one-time, opaque, UNGUESSABLE nonce minted per surfaced batch, which an inbound answer is resolved against server-side rather than trusting a phone-asserted conversation. "Unguessable" is what obliges #1975's minting to crypto/rand, mirroring #703's for ModalID. Adding this outbound key loosens no inbound guarantee.

It is QuestionBatchID rather than QuestionID because this payload also declares a nested Question type: a question_id key sitting beside a questions array would read as that type's key, and Question carries no id at all, so the misreading is not idle. The _batch_ is what makes the field self-describing to #1973 and to pyrycode-desktop#849. QuestionDismissedPayload below carries the same key, which is what lets a client match a dismissal to the batch it clears.

Questions is in claude's own order — the JSON-array order is the canonical display order. The key is always present on the wire and never null; see MarshalJSON.

func (QuestionShownPayload) MarshalJSON added in v0.16.0

func (p QuestionShownPayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Questions to an empty array, so a batch always serialises as "questions":[] and never as "questions":null.

The reason is genuinely SHARED with Question.MarshalJSON's Options, so it is stated once here for both rather than split into two manufactured halves. Both empty arrays are OUT OF CONTRACT: the documented bounds are 1-4 questions and 2-4 options, so neither "questions":[] nor "options":[] is reachable in a well-formed batch, and a nil slice is only reachable from a constructed zero value or a producer bug. [] is the encoding that leaves such a frame decodable by a client whose array type is non-optional, where null fails that decode outright.

That is one half of BackgroundTaskRosterPayload.MarshalJSON's rationale — the client-decode half — and the OTHER half deliberately does not transfer here. "An empty list is a positive statement" is true of an empty roster, which says the daemon has no background tasks, and false of an empty question array, which states nothing legal at all.

Value receiver, so the substitution lands on a copy rather than on the caller's slice, and the type alias keeps json.Marshal from recursing back into this method — SlashCommandListPayload.MarshalJSON's reasons.

type QueueStatePayload added in v0.15.0

type QueueStatePayload struct {
	ConversationID string       `json:"conversation_id"`
	Queued         []QueuedItem `json:"queued"`
}

QueueStatePayload is the body of an Envelope whose Type == TypeQueueState (docs/protocol-mobile.md § Queue). Binary → phone direction; the wire form of msgqueue.Snapshot(convID). Queued is ordered (FIFO/enqueue order, the options []ModalOption precedent). ConversationID is the daemon's own resolved id (#722), never attacker-derived.

type QueuedItem added in v0.15.0

type QueuedItem struct {
	QueuedMsgID uint64    `json:"queued_msg_id"`
	MessageID   string    `json:"message_id"`
	Text        string    `json:"text"`
	TS          time.Time `json:"ts"`
}

QueuedItem is one element of QueueStatePayload.Queued — the wire form of msgqueue.QueuedMessage (the producer #722 maps QueuedMessage.ID → QueuedMsgID). Named for its role in the array (the ModalOption precedent), not after the engine type, to keep it wire-scoped.

TWO fields are untrusted, client-originated transit content, not one: Text and MessageID (see the producer/handler #722/#723 for the never-log discipline). The two ids sit adjacent but their provenance is opposite, and nothing in the type says so — QueuedMsgID is the daemon's own per-conversation counter, while MessageID is a string the client chose. Do not read them as a matched pair.

MessageID (#2092) is the message_id from the send_message that produced this item, relayed byte-for-byte: never trimmed, lower-cased or re-encoded, "" when the client sent none, and never minted by the daemon. It exists so a client can merge this row with the optimistic echo it drew when the operator hit send — in interactive mode no user-message event is streamed, so that echo is the client's only record of its own message. It addresses nothing: dequeue_message still resolves conversation_id + queued_msg_id, and no code path reads this to route, authorize, match or dedupe. queue_state fans out to EVERY interactive connection, so a client sees ids it never minted and must merge only against echoes it minted itself — uniqueness across devices is enforced nowhere.

type RateLimitedPayload added in v0.16.0

type RateLimitedPayload struct {
	ConversationID  string   `json:"conversation_id"`
	Status          string   `json:"status"`
	LimitType       string   `json:"limit_type"`
	ResetsAt        int64    `json:"resets_at"`
	Utilization     *float64 `json:"utilization"`
	TruncatedFields []string `json:"truncated_fields"`
}

RateLimitedPayload is the body of an Envelope whose Type == TypeRateLimited (docs/protocol-mobile.md § rate_limited, #1405). Binary → phone direction; the wire form of turnevent.RateLimited, which reports that claude's usage-limit window is in a state other than the one measured-benign one.

Like ThinkingProgressPayload it is conversation-scoped rather than turn-scoped, so there is no turn_id, and receiving one neither opens nor closes a turn: a usage-limit window is orthogonal to whichever turn happened to observe it (turnevent.RateLimited's own doc). The bridge (#1410) supplies ConversationID because the internal event carries none. claude's session_id and uuid are deliberately absent for BackgroundTaskStartedPayload's reason plus #1380's — they are claude's session identity and claude's per-line message id, neither of which is the daemon's conversation identity, and the parser never decodes them so this payload cannot carry them even by accident.

Status is the field that says WHY the frame fired, and its value set beyond the benign one is ALMOST ENTIRELY UNMEASURED: exactly one non-benign value is on record (allowed_warning, the weekly warning band) and no capture of a limit actually in force exists on any claude version. A plain string, not a closed enum, so the set gets measured the first time a real limit fires rather than the daemon inventing one it has no evidence for. The producer's gate is deliberately loud in the same direction: any non-empty status other than the measured-benign one emits, so an unrecognised status surfaces and a human looks rather than a real limit vanishing. Dropping Status from this payload would silence that one layer later.

THE BENIGN STATUS IS NOT ALWAYS SILENT, and a client that assumed it was reads this frame backwards. Since #2250 the gate publishes a benign reading that FOLLOWS a non-benign one on the same parser — the falling edge, which exists so a client can take a quota banner down. Two things follow for a decode. The benign value is the ONE value worth comparing against, and it is the only one measured stable on every claude version on file; everything else stays an opaque label. And the frame is not the limit lifting: claude reports one window per line and chooses which, so a benign reading is claude declining to report a non-benign window. See docs/protocol-mobile.md § rate_limited, which states both readings for a client, and turnevent.RateLimited for the daemon-side argument.

LimitType is WHICH limit is in force (five_hour and seven_day are the observed values, the second riding the one non-benign status), a plain string for Status's reason. The falling edge therefore names a DIFFERENT limit than the warning it clears — every benign reading on record says five_hour — so a client that keys a banner by this value never matches the frame that takes it down; key it on the conversation. ResetsAt is when claude says it lifts, as unix seconds, 0 when claude did not report it. Neither wire name tracks claude's key: claude's are rateLimitType and resetsAt under rate_limit_info, while these are turnevent.RateLimited's own field names in snake_case, so a claude rename does not move them. status coincides with claude's spelling but is the daemon's chosen name for the field — it is what the producer's bound() reports it as — and a generic English word rather than a vocabulary import. utilization coincides the same way and for the same reason, which is why it is NOT a member of the claude-key enumeration TestRateLimitedType_IsNotClaudesVocabulary forbids on the wire.

Utilization is how much of the window claude says is spent, and it is a POINTER so null on the wire means claude reported nothing while 0 means claude reported an untouched window. A client that reads a missing reading as zero renders a fresh quota as an exhausted one, which is the failure this shape exists to prevent — turnevent.RateLimited.Utilization's own doc is the single source of truth for that argument and for why 0 cannot absorb absence the way ResetsAt's 0 can. The daemon always emits the key, so an absent reading is a literal null and never a dropped key. It is not in TruncatedFields and has no cap, for ResetsAt's reason: a float64 cannot grow.

TruncatedFields names the fields the producer cut to fit its cap, using these wire names ("status", "limit_type", in that order); it is null when nothing was cut, never an empty array, which is why this type has no MarshalJSON. The nil-normalising guard above is BackgroundTaskRosterPayload.Tasks's and does not generalise: an empty roster is a positive statement, whereas nothing-was-cut is an absence. It is load-bearing, not decoration — a payload that dropped it would present claude's truncated text to a phone as complete.

SECURITY: Status and LimitType are claude-authored strings that crossed the subprocess trust boundary. They are safe to RENDER as inert text and must never be fed to an HTML sink, an attribute, or a URL; the daemon bounds them but does not sanitize them, so they stay untrusted, model-influenced text all the way to the client. Their bound is the producer's, decided at construction (internal/streamsup/parser.go's maxRateLimitField), so this struct re-decides no maximum: a second cap here would be a second place the limit is decided, and the two could disagree silently. The constraint on turnevent.RateLimited follows the data onto the wire — it is a REPORT, never a control input, so a client MUST NOT branch security-relevant behaviour on Status.

BOTH NUMBERS ARE CLAUDE'S AND BOTH ARE UNVALIDATED IN BOTH DIRECTIONS, and saying so of one while adding a second is how a client concludes the second was checked. ResetsAt must not be assumed to lie in the future, or in a sane range at all. Utilization is NOT a bounded fraction: it must not be assumed to lie in 0..1 either, so scaling a progress bar or a gauge by it without a range check is this field's realistic bug, and a value above one is not evidence of anything but what claude sent. Neither is clamped, rounded or rejected anywhere on the path.

type ReadWorkspaceFilePayload added in v0.26.0

type ReadWorkspaceFilePayload struct {
	// ConversationID names the conversation whose workspace is read. A lookup
	// key validated against the daemon's registry, not authorization.
	ConversationID string `json:"conversation_id"`

	// Path names the file, relative to the conversation's workspace or
	// absolute. A relative path resolves against the workspace, never the
	// daemon's own directory.
	Path string `json:"path"`
}

ReadWorkspaceFilePayload is the body of an Envelope whose Type == TypeReadWorkspaceFile (#2598). The frame a client sends to read one regular file LIVE from a conversation's workspace or admitted read folders. No stored copy is made or served, so an edit between two requests shows in the second answer. The answer is RequestAttachmentPayload's: an attachment_chunk stream correlated by in_reply_to, whose attachment_id the daemon mints per transfer.

ONE DIRECTION ONLY, phone → binary, and EVERY FIELD IS AN UNVERIFIED CLAIM, exactly as on RequestAttachmentPayload. That block's rules carry over whole: the conversation id is a lookup key validated against the daemon's registry before anything resolves, and naming a conversation is not authorization.

THE PATH IS THE FIRST FILESYSTEM PATH A CLIENT NAMES ON THIS WIRE. It is confined to the workspace or admitted read folders, including symlink resolution. Relative paths use only the workspace; extra roots require an absolute path. Both requested and resolved leaves must avoid the case-insensitive denylist: exact .env, any .env.*, exact id_rsa/id_dsa/id_ecdsa/id_ed25519, and suffixes .key/.pem/.p12/.pfx/.keychain/.keychain-db. This is a filename heuristic, not content inspection or a guarantee that admitted files contain no secrets. Regular files of any type retain the bounded byte stream and byte-sniffed MIME. Confinement, not the path's shape, bounds a paired but hostile client.

NEVER LOG OR ECHO THE PATH. It names host layout and its leaf is a filename, which docs/protocol-mobile.md § Attachments bans from logs for a privacy reason; every refusal is the one static CodeAttachmentNotFound, which does not say why.

NO omitempty AND NO MarshalJSON, for RequestAttachmentPayload's reason: both keys are always present. A hostile or truncated payload decodes to two empty strings, and an empty conversation id names nothing.

type RecentWorkspace added in v0.16.0

type RecentWorkspace struct {
	Path       string    `json:"path"`
	LastUsedAt time.Time `json:"last_used_at"`
}

RecentWorkspace is one row of a RecentWorkspacesListPayload (docs/protocol-mobile.md § recent_workspaces_list): one distinct workspace folder — its absolute path and the most-recent LastUsedAt across the conversations that share it. Neither field carries omitempty (reply-side discipline: the client reads both on every row to label and sort the list). path matches WorkspaceFolderCreatedPayload.Path; last_used_at matches Conversation.LastUsedAt / ConversationSummary.LastUsedAt.

type RecentWorkspacesListPayload added in v0.16.0

type RecentWorkspacesListPayload struct {
	Workspaces []RecentWorkspace `json:"workspaces"`
}

RecentWorkspacesListPayload is the body of a recent_workspaces_list frame (docs/protocol-mobile.md § recent_workspaces_list). Binary → phone, sent in reply to a recent_workspaces request. Ordering is the source of truth: entries are most-recent-first, deduped so each distinct workspace path appears exactly once. The slice is always non-nil so an empty result marshals as "workspaces":[] rather than null.

type RecentWorkspacesPayload added in v0.16.0

type RecentWorkspacesPayload struct{}

RecentWorkspacesPayload is the body of a recent_workspaces frame (docs/protocol-mobile.md § recent_workspaces). Phone → binary. The payload is empty by spec; the type exists so the dispatcher can decode into a concrete value rather than a json.RawMessage (mirrors ListConversationsPayload).

type RegisterPushTokenPayload

type RegisterPushTokenPayload struct {
	Platform   string `json:"platform"`
	Token      string `json:"token"`
	DeviceName string `json:"device_name"`
}

RegisterPushTokenPayload is the body of a register_push_token frame (docs/protocol-mobile.md § register_push_token). Phone → binary, sent on every WS connect; the binary persists (platform, token, device_name) in devices.json and de-duplicates against the stored triple.

Platform is "fcm" (Android) or "apns" (iOS). The wire type stays a plain string: an enum would force a converter at every internal call site for no observable wire-format gain, and per-spec the dispatcher is the validation point.

All three fields are required (no omitempty, no pointers).

type RenameConversationPayload added in v0.16.0

type RenameConversationPayload struct {
	ConversationID string `json:"conversation_id"`
	Name           string `json:"name"`
}

RenameConversationPayload is the body of a rename_conversation frame (docs/protocol-mobile.md § rename_conversation). Phone → binary. Both fields are spec-required: a rename must name a target conversation and a new display title.

Deliberately NOT a reuse of PromoteConversationPayload — promote also carries a required Cwd, which a rename neither has nor means. The reply reuses ConversationUpdatedPayload verbatim.

type RenameWorkspacePayload added in v0.16.0

type RenameWorkspacePayload struct {
	Path  string  `json:"path"`
	Label *string `json:"label"`
}

RenameWorkspacePayload is the body of a rename_workspace frame (docs/protocol-mobile.md § Renaming a workspace). Phone → binary.

Path  — the workspace being named: the exact cwd string stored on one or more
        conversations. A LOOKUP KEY AND NOTHING MORE — the daemon compares it
        byte-for-byte against stored cwds and uses it as a map key. It is never
        resolved, joined, stat-ed, opened or passed to a process, and a path
        matching no conversation is refused with CodeWorkspaceNotFound.
Label — the operator-chosen display name, NULLABLE so the three states stay
        distinct: null (or an absent key) clears, a blank-after-trimming value
        is REFUSED, and any other string is stored verbatim — untrimmed — up to
        MaxWorkspaceLabelBytes.

Neither field carries omitempty. On Label that is load-bearing rather than stylistic: omitempty would collapse the deliberate null into an absent key, and while both decode to nil, only the explicit null survives a byte-level round-trip against the reply fixture.

The bound and the non-blank check are the HANDLER's, not this type's. There is no UnmarshalJSON here: MintPairingPayload's decode-time check argues in its own comment that it is a deliberate departure from this package's pure-DTO posture and "not a general licence", justified by that field having no downstream validator. This field has one, and keeping every malformed branch together in the handler is what lets each carry its own static message.

type ReplySuggestionPayload added in v0.35.0

type ReplySuggestionPayload struct {
	ConversationID string  `json:"conversation_id"`
	SessionID      string  `json:"session_id"`
	Revision       uint64  `json:"revision"`
	SuggestedReply *string `json:"suggested_reply"`
}

ReplySuggestionPayload is the body of an Envelope whose Type == TypeReplySuggestion. Declared, not yet emitted: a daemon-to-client v2 state frame gated by the negotiated "interactive" capability.

Revision is positive and increases per conversation within one daemon lifetime. Clients replace suggestion state by conversation/session, ignore lower revisions, and discard cached suggestions on a fresh handshake. SuggestedReply is inert, single-line UTF-8 text of at most 1024 bytes. Only explicit null clears state; omission and an empty string do not. No field uses omitempty, so a nil SuggestedReply always emits the clear signal.

Emission and semantic validation belong to later consumers. Ordinary JSON decoding into this DTO does not distinguish an omitted suggestion from null.

type RequestAttachmentPayload added in v0.16.0

type RequestAttachmentPayload struct {
	// ConversationID names the conversation whose attachment is wanted. A lookup
	// key validated against the daemon's registry before it resolves anything, and
	// not authorization; the empty string names nothing and resolves nothing.
	ConversationID string `json:"conversation_id"`

	// AttachmentID names the attachment wanted within that conversation. The
	// client's own id, the one it repeated on every chunk of the upload; the empty
	// string is not a valid id under any published shape.
	AttachmentID string `json:"attachment_id"`
}

RequestAttachmentPayload is the body of an Envelope whose Type == TypeRequestAttachment (docs/protocol-mobile.md § Attachments, published by #2052). The frame a client sends to ask the daemon for a stored attachment. Wire vocabulary only — nothing constructs, decodes or validates it here; #2054 answers it and #2053 streams the bytes back as AttachmentChunkPayload frames.

ONE DIRECTION ONLY, phone → binary, and that is the whole difference from the frame it is answered with. AttachmentChunkPayload rides both legs and nothing in it reports which direction a value came from, so its SECURITY block has to make a consumer decide trust from where the frame arrived. Here there is nothing to decide: EVERY FIELD IS AN UNVERIFIED CLAIM, ALWAYS.

TWO FIELDS, and no third. It names a conversation and an attachment; correlation to the answer rides the envelope's InReplyTo, which is why there is no request-id key — TypeAttachmentStored's block has that decision, and both terminals of this leg already correlate that way (the answering chunks, and the CodeAttachmentStreamAborted TypeError). The committed testdata/attachment_chunk_retrieval.json rides in_reply_to 91 and testdata/request_attachment.json is the envelope 91 it answers, so a request-id key added here would leave a landed fixture describing a different scheme. TestRequestAttachmentPayload_WireKeys pins the key set so this is checked rather than reviewed.

THE ASYMMETRY WITH AttachmentChunkPayload IS NARROWER THAN IT WAS. That frame carries a conversation_id too since #2142 — the "an upload could only steer bytes elsewhere" argument this block used to rest on was reversed, because the property it bought was the absence of a field rather than isolation between conversations. What survives is a difference in what the two ids DO: this one selects which conversation's file to read, while the chunk's decides which conversation an upload is filed under (#2143). Both are the same kind of value under the same rule, and the rule is the paragraph below.

THE CONVERSATION ID IS A LOOKUP KEY, NEVER A VALUE TRUSTED AS SENT, and this is the security property the whole frame rests on. It is validated against the daemon's own registry BEFORE IT REACHES A PATH JOIN — not merely before bytes go out — and NAMING A CONVERSATION IS NOT AUTHORIZATION. § Naming a message's attachments states the same rule for send_message's attachment_ids and says where the safety lives: "Nothing about the id's shape or its randomness does this work — confinement does." A reader who takes this field for a free-form selector has been handed exactly the capability the rest of that section spends pages denying. A client must not read "UUIDv4" as a claim of unguessability.

BOTH IDS OBEY THE SAME SHAPE, the lowercase UUIDv4 § Attachments publishes under "The attachment_id shape" — 36 bytes, '-' at 8/13/18/23, '4' at 14, one of 89ab at 19 — which is conversations.ValidID's shape byte for byte. Lowercase is load-bearing rather than cosmetic: an id becomes a directory name, and a case-insensitive host (APFS by default) folds two ids into one directory otherwise. Containment follows from that shape and NEVER from a length ceiling, which is also why this type adds no Max* constant of its own: MaxAttachmentIDBytes exists for attachment_chunk's envelope arithmetic, a ceiling there was read as the shape once already, and a second one here would enforce nothing while inviting the same mistake.

NOTHING HERE ENFORCES ANY OF IT. internal/protocol declares shapes and validates none, the posture both siblings ship with. The canonical-shape check on either id and the registry validation the published contract promises are #2054's, which owns the reject path and the CodeAttachmentNotFound code to answer with — a deliberately merged code whose message is static and never echoes the requested id or the resolved path, because two distinguishable answers would make this verb a path-existence oracle for a traversal probe.

A HOSTILE OR TRUNCATED PAYLOAD DECODES TO THE ZERO VALUE, NOT TO AN ERROR, since every key is optional to encoding/json — AttachmentStoredPayload records the same property. The result is two empty strings, and the empty string is not a valid id under any published shape, so a consumer must resolve NOTHING from them. The failure this warns about is silent and specific: filepath.Join(dir, "", "") is dir, so a consumer that skips the shape check and joins the zero value addresses the conversation directory root rather than erroring. QuestionAnswerPayload's published obligation is the shape to follow — a decode failure is a rejected frame, never an empty-but-successful request — and discharging it is #2054's.

NO omitempty AND NO MarshalJSON. Both fields are always present in the one direction this frame travels, so a decoder may rely on both; TestRequestAttachmentPayload_ZeroValue_KeysPresent is the pin, and an omitempty added later for tidiness would silently change the wire. There is no slice field, so QuestionShownPayload.MarshalJSON's nil→[] argument does not transfer.

THE ALLOCATION HAZARD AttachmentChunkPayload WARNS ABOUT IS ABSENT BY SHAPE: there is no count and no length field here, so NEVER ALLOCATE FROM A CLAIM has nothing to bite on. Stated so the absence reads as a property of the shape rather than as an omission. This type declares no bound of its own either — the transport's envelope cap is the only byte limit, and a client learns any receiver limit by being rejected rather than by reading a figure published ahead of the code that enforces it.

SECURITY: SENDING THIS FRAME IS NOT A CAPABILITY, and neither is receiving an answer to it. Authorization is pairing, enforced structurally at the Noise IK handshake, exactly as § Attachments records for both existing legs; there is no per-verb gate on this one and none is invented here. What bounds a paired but hostile client is confinement, not secrecy. Both fields are client-supplied strings and are LOGGABLE ONLY AFTER THEIR SHAPE IS VALIDATED — raw, either is the log-injection shape § Attachments already forbids for Filename. The payload carries no content-bearing bytes, so once validated it is safe to log whole. Nothing here is claude-authored and nothing here becomes prompt content, so § Security model's threat 1 does not land on this frame — the opposite of SendMessagePayload's AttachmentIDs, which does reach claude.

type RequestClaudeAccountPayload added in v0.36.0

type RequestClaudeAccountPayload struct{}

RequestClaudeAccountPayload is the body of request_claude_account, client → daemon. It encodes as {} and reads the connected daemon's account source.

type RequestClaudeUsagePayload added in v0.41.0

type RequestClaudeUsagePayload struct{}

RequestClaudeUsagePayload is the body of request_claude_usage, client → daemon. It encodes as {}.

type RequestContextUsagePayload added in v0.18.0

type RequestContextUsagePayload struct {
	ConversationID string `json:"conversation_id"`
}

RequestContextUsagePayload is the body of an Envelope whose Type == TypeRequestContextUsage (docs/protocol-mobile.md § context_usage, published by #2431). The frame a client sends to ask for one conversation's context breakdown now, rather than waiting for the next turn to end.

ONE DIRECTION ONLY, phone → binary, so there is no provenance to disambiguate: EVERY FIELD IS AN UNVERIFIED CLAIM, ALWAYS. The frame it is answered with — ContextUsagePayload above — rides the other way and shares no type with it, so that type's mixed-provenance rule says nothing about this one. Here there is no mixture to reason about: the single field is remote-authored, full stop.

IT NAMES A CONVERSATION, because a context window is conversation-scoped and this wire is multi-conversation. THE ID IS A LOOKUP KEY, NEVER A VALUE TRUSTED AS SENT: it is resolved against the daemon's own registry, the reported conversation_id in the reply comes out of the RESOLVED RECORD rather than being echoed back, and NAMING A CONVERSATION IS NOT AUTHORIZATION — authorization is pairing, enforced structurally at the Noise_IK handshake.

LIKE RequestModelListPayload AND UNLIKE RequestHistoryPayload, THE ID NEVER BECOMES A PATH COMPONENT. That single difference is why a decode failure of this payload is TOLERATED rather than rejected: it leaves ConversationID empty, which reaches only a registry membership check and is refused there, where an empty path component would have resolved to a directory root.

NO DETAIL KEY, and its absence is a decision rather than an omission. The daemon always asks claude at detail:"full"; see TypeRequestContextUsage's block for why a client-selected detail would let one client downgrade another's reading once closely-spaced asks collapse.

CORRELATION RIDES THE ENVELOPE'S InReplyTo, so the payload carries NO REQUEST-ID KEY — TypeAttachmentStored's decision, transferred unchanged. TestRequestContextUsagePayload_WireKeys pins the key set so this is checked rather than reviewed.

NO omitempty AND NO MarshalJSON, matching RequestModelListPayload and MCPStatusRequestPayload. There is no presence contract: absent and empty are the SAME case, "no conversation named", which names nothing and is refused, so nothing needs to tell them apart. TestRequestContextUsagePayload_ZeroValue_KeyPresent reddens if an omitempty is added later for tidiness — and the zero value is a REACHABLE state here, being exactly what the tolerated decode failure leaves.

type RequestHistoryPayload added in v0.16.0

type RequestHistoryPayload struct {
	// ConversationID names the conversation whose history is wanted. A lookup key
	// validated against the daemon's registry before it resolves anything, and not
	// authorization; the empty string names nothing and resolves nothing.
	ConversationID string `json:"conversation_id"`

	// Cursor is the position handed back by the previous page, echoed verbatim.
	// EMPTY MEANS "START AT THE NEWEST" — the first ask of a walk has nothing to
	// echo yet, so empty is the normal opening value and not a missing one.
	Cursor string `json:"cursor"`

	// Limit is how many entries the client wants, and its ZERO IS MEANINGFUL: 0
	// (whether sent as 0 or omitted entirely) asks the DAEMON TO CHOOSE, and must
	// never be read as a request for zero entries. history.Store.Page refuses a
	// limit below 1, so an absent key reaching it as a literal 0 would turn every
	// client that omits the field into an error — which is why the zero is
	// assigned a meaning here rather than left to the handler.
	//
	// A positive value is honoured up to history.MaxPageEntries, where it is
	// CLAMPED rather than refused. A negative value is a reject condition (#2116
	// owns its code).
	//
	// NEVER ALLOCATE FROM THIS CLAIM. It is the one count in this vocabulary and
	// AttachmentChunkPayload's NEVER ALLOCATE FROM A CLAIM rule applies verbatim:
	// hand it to history.Store.Page and let the clamp decide, rather than sizing
	// any buffer from an attacker-chosen integer.
	Limit int `json:"limit"`
}

RequestHistoryPayload is the body of an Envelope whose Type == TypeRequestHistory (docs/protocol-mobile.md § Conversation history, published by #2113). The frame a client sends to ask for older entries of a conversation it already has open. Wire vocabulary only — nothing constructs, decodes or validates it here; #2116 answers it and owns every reject below.

ONE DIRECTION ONLY, phone → binary, so there is no provenance to disambiguate: EVERY FIELD IS AN UNVERIFIED CLAIM, ALWAYS. That is the same posture RequestAttachmentPayload ships with and for the same reason — the frame it is answered with rides the other way and shares no type with it.

PAGED, NEWEST-FIRST, WALKING BACKWARDS. A client opens a conversation at its most recent entries and asks for older ones as the operator scrolls up; it never reads forward from the beginning. The shape mirrors history.Store.Page, which is what serves it.

THE CURSOR, NOT AN OFFSET AND NOT A PAGE NUMBER. Both of those are invalidated by appends landing while the operator scrolls; a cursor names a position in an append-only file that nothing ever rewrites. It is minted by the daemon's log, OPAQUE on this wire, and a client only ever echoes back what it was handed. history.parseCursor is the ONLY validator anywhere — nothing above internal/history may parse one.

OPACITY IS A CONVENTION, NOT A SECURITY PRIMITIVE, and the distinction has to be stated because base64 invites the opposite reading. A cursor is NOT A SECRET AND NOT A CAPABILITY: it is trivially reversible and it carries the conversation id the client already knows. It is bound to that conversation by parseCursor, and it is deliberately unsigned — a MAC would imply an authorization it does not carry, where authorization is pairing, enforced structurally at the Noise IK handshake.

IT NAMES A CONVERSATION, because history.Store.Page's precondition is a bound conversation and this wire is multi-conversation — TypeRequestSessionSettings and TypeRequestAttachment both name one. THE ID IS A LOOKUP KEY, NEVER A VALUE TRUSTED AS SENT: it is validated against the daemon's own registry BEFORE IT REACHES A PATH JOIN, and NAMING A CONVERSATION IS NOT AUTHORIZATION. RequestAttachmentPayload's block carries that rule in full, and it is the same rule here.

CORRELATION RIDES THE ENVELOPE'S InReplyTo, so the payload carries NO REQUEST-ID KEY — TypeAttachmentStored's block has that decision and it transfers unchanged. TestRequestHistoryPayload_WireKeys pins the key set so this is checked rather than reviewed, and the committed testdata/history_page.json rides in_reply_to 140 answering the envelope 140 of testdata/request_history.json, so a request-id key added later would leave a landed fixture describing a different scheme.

A HOSTILE OR TRUNCATED PAYLOAD DECODES TO THE ZERO VALUE, NOT TO AN ERROR, since every key is optional to encoding/json. A DECODE FAILURE IS A REJECTED FRAME, NEVER AN EMPTY-BUT-SUCCESSFUL REQUEST — QuestionAnswerPayload's published obligation, and discharging it is #2116's. The specific silent failure this warns about: the empty conversation id names nothing, and joining it into a path resolves to the log ROOT rather than erroring.

NO omitempty AND NO MarshalJSON. All three keys are always present, so a decoder may rely on all three, and Limit's zero is MEANINGFUL rather than absent (see its own comment). TestRequestHistoryPayload_WireKeys marshals a zero value, so an omitempty added later for tidiness reddens there.

SECURITY: SENDING THIS FRAME IS NOT A CAPABILITY, and neither is receiving an answer. There is no per-verb gate and none is invented here; what bounds a paired but hostile client is confinement to the conversation it named plus the daemon's validation of that name. Both strings are client-supplied and are LOGGABLE ONLY AFTER THEIR SHAPE IS VALIDATED — raw, either is the log-injection shape § Attachments already forbids for a filename, and history.cursorRefusal already declines to echo a cursor for exactly that reason. Any bound on concurrent or repeated history requests is receiver-configured and unpublished, learned by being rejected.

type RequestHostSystemPromptPayload added in v0.32.0

type RequestHostSystemPromptPayload struct{}

RequestHostSystemPromptPayload is the body of request_host_system_prompt, client → daemon. It encodes as {} and reads the connected daemon's setting.

type RequestModelListPayload added in v0.16.0

type RequestModelListPayload struct {
	// ConversationID names the conversation whose model menu is wanted. A lookup
	// key resolved against the daemon's registry, and not authorization; the empty
	// string names nothing and resolves nothing.
	ConversationID string `json:"conversation_id"`
}

RequestModelListPayload is the body of an Envelope whose Type == TypeRequestModelList (docs/protocol-mobile.md § model_list, published by #2125). The frame a client sends to ask for a conversation's model menu on demand, rather than waiting for the live turn lane or the next connect.

ONE DIRECTION ONLY, phone → binary, so there is no provenance to disambiguate: EVERY FIELD IS AN UNVERIFIED CLAIM, ALWAYS. The frame it is answered with — ModelListPayload above — rides the other way and shares no type with it, so the never-empty and DroppedModels contracts stated there say nothing about this one.

IT NAMES A CONVERSATION, because a model menu is conversation-scoped on this wire and this wire is multi-conversation; TypeRequestSessionSettings and TypeRequestHistory both name one. THE ID IS A LOOKUP KEY, NEVER A VALUE TRUSTED AS SENT: it is resolved against the daemon's own registry, the reported id in the reply comes out of the RESOLVED RECORD rather than being echoed back, and NAMING A CONVERSATION IS NOT AUTHORIZATION — authorization is pairing, enforced structurally at the Noise_IK handshake.

UNLIKE RequestHistoryPayload THE ID NEVER BECOMES A PATH COMPONENT. That single difference is why a decode failure here is TOLERATED rather than rejected: it leaves ConversationID empty, which reaches only a registry membership check and is refused there, where an empty path component would have resolved to a directory root. Do not copy this tolerance to a verb that joins the id into a path.

CORRELATION RIDES THE ENVELOPE'S InReplyTo, so the payload carries NO REQUEST-ID KEY — TypeAttachmentStored's decision, transferred unchanged. TestRequestModelListPayload_WireKeys pins the key set so this is checked rather than reviewed.

NO omitempty AND NO MarshalJSON, matching RequestSessionSettingsPayload — its stated reason applies verbatim. There is no presence contract: absent and empty are the SAME case, "no conversation named", which names nothing and is refused, so nothing needs to tell them apart. Keeping the key always on the wire lets a fixture pin the full shape, and TestRequestModelListPayload_ZeroValue_KeyPresent reddens if an omitempty is added later for tidiness.

SECURITY: SENDING THIS FRAME IS NOT A CAPABILITY, and neither is receiving an answer. There is no per-verb gate beyond the negotiated interactive capability, which is settled at handshake and cannot be influenced by anything in this payload. The id is loggable only AFTER it has been resolved against the registry — raw it is an arbitrary client string, and that is the log-injection shape § Attachments already forbids for a filename. The payload carries no count and no length, so there is nothing here a hostile value could size.

type RequestSessionSettingsPayload added in v0.16.0

type RequestSessionSettingsPayload struct {
	ConversationID string `json:"conversation_id"`
}

RequestSessionSettingsPayload is the body of an Envelope whose Type == TypeRequestSessionSettings (docs/protocol-mobile.md § Session settings). Phone → binary direction; a client asking what the current run configuration is and which session to address a change to.

This is an inbound v2 *control* envelope, structurally like RequestSnapshotPayload (snapshot.go): the v2 session manager intercepts it at the dispatch boundary before dispatch.Route is called, so there is NO dispatch.Route handler for it.

ConversationID names the conversation the client is asking about (#1586), and since #1610 it SELECTS the session the reply describes. Before it the frame was genuinely bare, so a client had no way to say which conversation it meant. It is untrusted network input used for exactly one thing — an in-memory resolution through the handler's conversation-keyed run-configuration seam — and never reaches a log line, an error string, a filesystem path, or the reply.

NO omitempty, matching RequestSnapshotPayload and deliberately UNLIKE the sibling SetSessionSettingsPayload above, whose per-field pointers encode a presence contract. There is no presence contract here: absent and empty are the SAME case — "no conversation named", which names no session and so is answered with the zero-valued reply — so nothing needs to tell them apart. Keeping the field always on the wire lets a fixture pin the full shape.

Scope: naming a conversation the daemon does not host, naming one bound to no known live or dormant session, or naming none at all are answered with a zero-valued SessionSettingsPayload, never an error frame and never another session's values. Naming a hosted, bound conversation reports THAT session's id, stored model and stored effort together (see SessionSettingsPayload below). Its permission pair comes only from the current child's last confirmation; when no confirmation or no current child exists, that pair remains zero while the resolved stored fields remain present.

type RequestSnapshotPayload added in v0.15.0

type RequestSnapshotPayload struct {
	ConversationID string `json:"conversation_id"`
}

RequestSnapshotPayload is the body of an Envelope whose Type == TypeRequestSnapshot (docs/protocol-mobile.md § Screen snapshot). Phone → binary direction; an on-demand request for a one-shot text picture of the current screen.

This is an inbound v2 *control* envelope, structurally like TypeRekeyRequest: the v2 session manager intercepts it at the dispatch boundary before dispatch.Route is called. There is NO dispatch.Route handler for it — the interception, render, and push are the consumer ticket's job, so the next reader should not look for a handler that isn't there.

type RequestSystemPromptPayload added in v0.16.0

type RequestSystemPromptPayload struct {
	// ConversationID names the conversation whose stored prompt is wanted. A
	// lookup key resolved against the daemon's registry, and not authorization;
	// the empty string names nothing and resolves nothing.
	ConversationID string `json:"conversation_id"`
}

RequestSystemPromptPayload is the body of an Envelope whose Type == TypeRequestSystemPrompt (docs/protocol-mobile.md § Reading a conversation's system prompt). Phone → binary direction; a client asking what system prompt one conversation holds and whether the running session was spawned with it.

This is an inbound v2 *control* envelope, structurally like RequestSessionSettingsPayload (settings.go): the v2 session manager intercepts it at the dispatch boundary before dispatch.Route is called, so there is NO dispatch.Route handler for it. That is the one place it departs from its own write half, TypeSetSystemPrompt, which IS map-dispatched — a client sends the two verbs the same way, and the daemon routes them differently.

ONE DIRECTION ONLY, phone → binary, so there is no provenance to disambiguate: EVERY FIELD IS AN UNVERIFIED CLAIM, ALWAYS. The frame it is answered with — SystemPromptPayload below — rides the other way and shares no field with it.

THE ID IS A LOOKUP KEY, NEVER A VALUE TRUSTED AS SENT: it is resolved against the daemon's own conversations registry and is spent on nothing else. It reaches no reply, no log line, no error string and no filesystem path, and NAMING A CONVERSATION IS NOT AUTHORIZATION — authorization is pairing, enforced structurally at the Noise_IK handshake, plus the negotiated interactive capability the handler gates on.

UNLIKE RequestHistoryPayload THE ID NEVER BECOMES A PATH COMPONENT. That single difference is why a decode failure is TOLERATED rather than rejected: it leaves ConversationID empty, which resolves nothing and is answered with the constant reply below, where an empty path component would have resolved to a directory root. Do not copy this tolerance to a verb that joins the id into a path.

NO omitempty, matching RequestSessionSettingsPayload and RequestModelListPayload — their stated reason applies verbatim. There is no presence contract: absent and empty are the SAME case, "no conversation named", which names nothing and is answered with the constant reply, so nothing needs to tell them apart. Keeping the key always on the wire lets a fixture pin the full shape, and TestRequestSystemPromptPayload_ZeroValue_KeyPresent reddens if an omitempty is added later for tidiness.

CORRELATION RIDES THE ENVELOPE'S InReplyTo, so the payload carries NO REQUEST-ID KEY — TypeAttachmentStored's decision, transferred unchanged.

type ResettingPayload added in v0.19.0

type ResettingPayload struct {
	ConversationID string `json:"conversation_id"`
	Active         bool   `json:"active"`
	// Phase is ResetPhaseWrappingUp or ResetPhaseRestarting while Active, "" once the
	// reset is over. It exists so the pause has a name: the two phases fail
	// differently and take visibly different lengths of time.
	Phase string `json:"phase"`
	// Handoff is ResetHandoffPending, ResetHandoffWritten or ResetHandoffSkipped while
	// Active, "" once the reset is over. It resolves on the phase change, never
	// mid-phase.
	Handoff string `json:"handoff"`
}

ResettingPayload is the body of an Envelope whose Type == TypeResetting (docs/protocol-mobile.md § resetting, #2453). Binary → phone direction, gated on the already-negotiated interactive capability. Like compacting it is conversation-scoped rather than turn-scoped, so there is no turn_id, and emitting it never opens or closes a turn.

IT HAS compacting's SHAPE AND NONE OF ITS PROVENANCE, which is the one thing to carry away from the adjacency. Every status peer before it is the wire form of a stream-json detector reading claude's own output, and CompactingPayload beside it carries two claude-authored strings under a SECURITY paragraph. NOTHING ON THIS FRAME IS claude's: the id is one the daemon assigned, Active is a bool it computed, and Phase and Handoff are tokens it selected from the closed sets above. A client must not inherit the neighbour's render rules from the neighbourhood — there is no untrusted text here to strip, escape or attribute.

THE HANDOFF NOTE'S CONTENT DOES NOT CROSS THIS WIRE, and that is the design decision the paragraph above rests on rather than a gap. The note is prose a claude wrap-up turn writes; Handoff reports only WHETHER one was made. A field carrying the note itself would be this frame's one genuinely untrusted value and would need a bound, a sanitization statement and a render rule; none is declared, so none is owed.

ONE RESET EMITS TWO RISING EDGES BEFORE ONE FALLING EDGE, and this is where the frame departs from compacting's strict edge pair:

active:true  phase:wrapping_up  handoff:pending
active:true  phase:restarting   handoff:written | skipped
active:false phase:""           handoff:""

A REPEATED active:true CARRYING A NEW PHASE IS A PHASE CHANGE, NOT A SECOND RESET. A client that treats every rising edge as a new reset draws two. Every rising sequence ends in a falling edge, on success and on every error path.

Phase and Handoff are MEANINGFUL ONLY WHILE Active IS TRUE. A falling edge carries both as the empty string, so a client switching exhaustively over either set needs a case for "" — gate on Active rather than adding a fourth token. No omitempty on any field, per this file's rule as stated at ToolResultPayload: the key is always on the wire and its zero value is the statement.

type RoutingEnvelope

type RoutingEnvelope struct {
	ConnID string          `json:"conn_id"`
	Frame  json.RawMessage `json:"frame"`

	// Token carries the phone's device-pairing token from the relay to
	// the binary on the FIRST phone→binary frame for a given ConnID
	// only. Empty on subsequent frames and on every binary→phone frame.
	// Populated by the relay from the phone's x-pyrycode-token HTTP
	// header at WS upgrade; never echoed back to the phone. Wire spec:
	// docs/protocol-mobile.md § Routing envelope.
	//
	// SECURITY: the binary's dispatcher and gate closure MUST NOT log
	// Token at any level. The token is plaintext credential material;
	// the field is retained on the wire type but currently has no live
	// consumer (the v1 first-frame gate that read it was removed).
	Token string `json:"token,omitempty"`

	// CloseCode, when non-zero on a binary→relay routing envelope, asks
	// the relay to forward Frame (if non-empty) to the phone and then
	// close that phone's WS with this WS close code. Zero on every
	// phone→binary frame. Non-zero on a relay→binary envelope, it is the
	// relay's close notice: that phone's WS has ended with this close code,
	// Frame is absent, and the binary tears down the ConnID's session
	// without replying (#2601). Wire spec: docs/protocol-mobile.md
	// § Routing envelope, § Error codes (close-code row 4401).
	CloseCode uint16 `json:"close_code,omitempty"`
}

RoutingEnvelope wraps an Envelope with the relay-prepended conn_id used on the binary↔relay leg only (docs/protocol-mobile.md § Routing envelope). Phones never see it; the relay strips it before forwarding frames to phones and prepends it before forwarding frames to the binary.

Frame is json.RawMessage so the relay can splice without parsing payloads — a structural property of the design (the relay holds zero per-user state).

Token and CloseCode are direction-restricted relay-prepended fields, both omitempty so existing fixtures and wire bytes for non-auth / non-close paths are byte-identical to the pre-#308 shape.

type ScreenSnapshotPayload added in v0.15.0

type ScreenSnapshotPayload struct {
	ConversationID string    `json:"conversation_id"`
	Text           string    `json:"text"`
	TS             time.Time `json:"ts"`
	Model          string    `json:"model"`
	Effort         string    `json:"effort"`
	YOLO           bool      `json:"yolo"`
	UsedTokens     int       `json:"used_tokens"`
	WindowTokens   int       `json:"window_tokens"`
}

ScreenSnapshotPayload is the body of an Envelope whose Type == TypeScreenSnapshot (docs/protocol-mobile.md § Screen snapshot). Binary → phone direction; the one-shot text picture answering a request_snapshot.

Text is plain rendered text only, NEVER raw terminal control codes. This preserves ADR 025's no-raw-bytes invariant and the substrate seal: the snapshot is a literal-screen picture rendered to text, not a stream of escape sequences. TS records when the snapshot was rendered; it is a time.Time whose monotonic-clock reading strips on JSON marshal, so callers MUST compare it with time.Time.Equal, never == or reflect.DeepEqual.

Model, Effort, and YOLO reflect the bootstrap session's persisted per-session settings so the phone can render the current model / reasoning effort / permissions posture. Model and Effort are the per-session override; an empty string means "inherited daemon default, no override". YOLO is bypass-permissions (--dangerously-skip-permissions) on/off; false means permissions enforced (the fail-safe default). All three carry no omitempty (like the fields above) so an empty model/effort stays distinguishable from unset and yolo:false is explicit on the wire rather than dropped.

UsedTokens and WindowTokens carry the bootstrap session's current context-window occupancy (#857) so the phone can render an "N% used (X of Y)" gauge as UsedTokens / WindowTokens without a separate protocol. UsedTokens is the current context size on the latest usage-bearing transcript entry (input + cache-read + cache-creation + output), NOT a running total; a post-compaction snapshot therefore reports a smaller figure. WindowTokens is the context-window size; a zero WindowTokens means the daemon has no trustworthy window reading, and covers two cases (#2100): the usage seam was not wired (foreground / unwired), and the used count came out ABOVE the window the daemon believed, which disproves the belief. Either way a client should treat "X of Y" as unavailable rather than divide by zero. The two differ in what UsedTokens carries — zero in the first case, the true current context size in the second — but no client renders them differently, which is why one zero covers both rather than a second wire field distinguishing them. Both carry no omitempty (like the fields above) so used_tokens:0 / window_tokens:0 stay distinguishable from unset rather than dropped.

type SendMessagePayload

type SendMessagePayload struct {
	ConversationID string   `json:"conversation_id"`
	MessageID      string   `json:"message_id"`
	Text           string   `json:"text"`
	AttachmentIDs  []string `json:"attachment_ids,omitempty"` // optional (#2036); every element is an unverified claim that becomes a path component — validate its canonical shape before use
	// ClientSentAt is when the client says Send was tapped (#2704), on the
	// client's own clock: optional, RFC 3339. Raw bytes rather than a string so a
	// wrongly typed value cannot fail the whole decode — an unparseable value is
	// dropped and the message is still accepted. Untrusted: SendMessage in
	// internal/relay/handlers parses it and the daemon stores only its own
	// re-formatting, never these bytes, and never logs it.
	ClientSentAt json.RawMessage `json:"client_sent_at,omitempty"`
}

SendMessagePayload is the body of an Envelope whose Type == TypeSendMessage (docs/protocol-mobile.md § send_message). Phone → binary direction.

AttachmentIDs names the uploaded attachments this message carries (#2036), so the daemon can name them instead of inferring the set from upload order or arrival timing. Wire vocabulary only: nothing produces, consumes or validates it here. Element order is the client's own presentation order and is NOT a correlation key — ids identify attachments, positions identify nothing, QuestionAnswerEntry's rule. #2038 is the consumer, and it composes the prompt naming each attachment's on-host path in this order, deduplicated on first occurrence.

EVERY ELEMENT IS AN UNVERIFIED CLAIM, and it BECOMES A DIRECTORY COMPONENT beneath the resolved conversation directory. Its canonical shape — the lowercase UUIDv4 form docs/protocol-mobile.md § Attachments publishes under "The attachment_id shape" — is validated BEFORE it reaches filepath.Join; conversations.ValidID is that check, the one attachments.EnsureDir already applies on the upload leg. An element reaching a path unvalidated is a traversal, and MaxAttachmentIDBytes does not help: 64 bytes accommodates "../../../../etc/passwd" several times over, so containment is a consequence of the SHAPE and never of any length ceiling. No named type marks the untrusted elements, matching AttachmentChunkPayload, which carries the same hazard on a plain string field with a doc block rather than a wrapper type.

THE SHAPE CHECK IS LOAD-BEARING A SECOND TIME, against § Security model threat 1 (prompt injection). AttachmentStoredPayload is exempt from that threat because it carries no client-authored byte; every element here is client-authored and #2038 composes claude's input from it. A shape-validated id draws from [0-9a-f-] only and CANNOT carry injection text, while an unvalidated element reaches claude verbatim. The two hazards are independent and one check answers both — which is why it is not optional even for a consumer that never touches the filesystem.

THE ELEMENTS ARE NOT A CAPABILITY. What keeps the field safe is CONFINEMENT: a named id resolves only under the message's OWN conversation, the one the authenticated v2 session is already on, decided daemon-side from session context and never client-asserted. That is what stops "name any id, get its bytes into your prompt", and it is a property of THIS field's resolution — not one borrowed from a sibling frame. This block used to anchor it to AttachmentChunkPayload's deliberately absent conversation_id; that frame carries one since #2142, so the anchor is gone while the property is untouched. Do NOT argue UUIDv4-therefore-unguessable anywhere on this field: the family's published stance is that the id is not secret, not unguessable and never the only thing between a caller and a file, so an entropy claim would quietly promote it to the capability it is documented not to be.

LOGGABLE ONLY AFTER SHAPE VALIDATION. § Attachments permits logging an attachment id — but for a value that has been checked. Raw, an element is an arbitrary client-supplied string in a line-oriented log, the same log-injection shape the section forbids for filename and for the same reason.

It carries the package's ONLY omitempty, and the departure is the point rather than an oversight. send_message is a v1-compatible inbound type, so a client predating this field sends three keys and always will: the empty-case wire form is the KEY ABSENT ENTIRELY, which is exactly what those clients already emit. The nil→[] MarshalJSON that QuestionShownPayload, BackgroundTaskRosterPayload, ModelListPayload and ToolUsePayload carry is a shape precedent and not a placement one — every one of them is an outbound, daemon-authored v2 frame. QuestionAnswerPayload is the near miss, genuinely inbound and still normalising, but it is v2-only and has carried its array since it was minted, so "always present" was true of every client that ever sent one. Here it would be false on arrival. Do not add a MarshalJSON by analogy: omitempty already elides nil and empty-non-nil alike, so the two directions are symmetric without one, and TestSendMessagePayload_ZeroValue_KeyAbsent pins it.

func (*SendMessagePayload) UnmarshalJSON added in v0.16.0

func (p *SendMessagePayload) UnmarshalJSON(b []byte) error

UnmarshalJSON collapses the three empty wire forms — key absent, null, and [] — to one in-memory value, so no consumer can branch on which of them arrived.

Without it that guarantee is FALSE, and the gap is the most common Go slice trap: encoding/json decodes [] to an empty NON-NIL slice while an absent key and null both leave nil. len(x) == 0 agrees across all three, but x == nil does not — so a consumer can tell [] from the other two, and #2038 is the consumer that reads this field.

This is NORMALISATION AT THE DECODE BOUNDARY, not validation: nothing is checked and nothing is rejected on content, so the package overview's "pure DTOs, no methods, no Validate()" posture is departed from once, deliberately, and only where a parser-differential ambiguity on an attacker-controlled inbound frame belongs.

A DECODE FAILURE IS PROPAGATED, NEVER SWALLOWED into an empty list — an ill-typed attachment_ids must be a rejected frame rather than a silent "this message names no attachments" read off garbage. The one production decode site, SendMessage in internal/relay/handlers, answers protocol.malformed on it; encoding/json's error carries the field path and the offending value's KIND, never the remote-authored bytes, so the handler logging it satisfies the rule QuestionAnswerPayload's doc block publishes for its own decoder.

The alias type is a defined type with no methods, which is what keeps json.Unmarshal from recursing back into this method — SlashCommandListPayload.MarshalJSON's reason, in the decode direction. The receiver is a pointer, as encoding/json requires for an Unmarshaler, so this writes only through the caller's own value; the decoded strings are freshly allocated and alias nothing in b.

type SendQueuedNowPayload added in v0.31.0

type SendQueuedNowPayload struct {
	ConversationID string `json:"conversation_id"`
	QueuedMsgID    uint64 `json:"queued_msg_id"`
	// AcceptedItemID has the same binding contract as DequeueMessagePayload.AcceptedItemID.
	AcceptedItemID json.RawMessage `json:"accepted_item_id,omitempty"`
}

SendQueuedNowPayload is the body of an Envelope whose Type == TypeSendQueuedNow (docs/protocol-mobile.md § Queue). Phone → binary direction. It is DequeueMessagePayload's shape and posture exactly — an inbound v2 control the session manager intercepts, ungated for any paired client on an interactive connection, ConversationID untrusted — and asks for the named entry to be written into the running claude turn rather than dropped (#2729).

type SessionCapabilities added in v0.27.0

type SessionCapabilities struct {
	Interrupt          bool     `json:"interrupt"`
	MidTurnInput       bool     `json:"mid_turn_input"`
	SlashCommands      bool     `json:"slash_commands"`
	MCPServers         bool     `json:"mcp_servers"`
	ContextUsageDetail bool     `json:"context_usage_detail"`
	EffortLevels       []string `json:"effort_levels"`
	PermissionModes    []string `json:"permission_modes"`
	AttachmentTypes    []string `json:"attachment_types"`
	Models             []string `json:"models"`
}

SessionCapabilities is one session's capability list (#2646): what its agent and current model support, each list naming exactly the options the daemon's set_session_settings checks accept for that session. Support is not permission, and the list is not the enforcement: the daemon re-checks every request whatever a client shows.

No omitempty: a present object carries all nine keys, and each list is [] rather than null when it holds nothing.

  • MidTurnInput is true only if a message sent during a running turn reaches that turn; false means it is held until the turn ends.
  • SlashCommands, MCPServers and ContextUsageDetail (#2670) say whether the session answers request_slash_command_list, mcp_status_request and request_context_usage's breakdown at all: true for Claude, false for Codex.
  • EffortLevels are the levels accepted for the session's current model.
  • PermissionModes are the values the permission_mode field accepts. The bypass posture is not among them: it stays reachable only through yolo.
  • AttachmentTypes is ["*/*"]: attachments reach either agent as file paths, and the daemon keeps no type allowlist.
  • Models are the values of the session's own agent's entries, empty when that vocabulary is unavailable. "" (the agent's default) is accepted but never listed, as for EffortLevels.

type SessionErrorPayload added in v0.16.0

type SessionErrorPayload struct {
	ConversationID string `json:"conversation_id"` // routing key; plain string, no omitempty — mirrors the sibling interactive payloads
	Code           string `json:"code"`            // CodeSessionBlocked (terminal) or CodeSessionChildCrashing (not); plain string, not a named enum (leaf-data convention)
	Message        string `json:"message"`         // daemon-generated human-readable reason
}

SessionErrorPayload is the body of an Envelope whose Type == TypeSessionError (docs/protocol-mobile.md § Error codes). Binary → phone direction; the unsolicited, conversation-scoped frame the daemon emits for a session problem. Code says which: CodeSessionBlocked when its interactive message queue gives up delivering queued messages (the msgqueue OnGiveUp seam, #1000), which is terminal, or CodeSessionChildCrashing when the conversation's claude child keeps exiting at startup and the daemon is still restarting it (#2724), which is not. Wire vocabulary only — the producers live in cmd/pyry; the never-log discipline for Message is theirs.

ConversationID is the routing key — a plain string with no omitempty, mirroring the sibling interactive payloads (QueueStatePayload, SessionTransitionPayload) — so the phone attaches the error to the correct session. It is the daemon's own resolved id (set by #1008 from the OnGiveUp conversation_id), never attacker-derived — same posture as QueueStatePayload.ConversationID.

Code is the wire code, CodeSessionBlocked or CodeSessionChildCrashing; a plain string over a closed wire set, not a named enum (leaf-data convention, matching MessagePayload.Role / SessionTransitionPayload.Reason). Neither is the transient CodeServerBinaryBusy, so a client cannot read the frame as "retry shortly": session.blocked is a terminal give-up, and session.child_crashing reports that the daemon is already retrying on its own. The struct carries NO Retryable / RetryAfterS fields: their structural absence is what prevents a client reading the frame as a cue to resend. Message is daemon-written human-readable prose and never carries child output or queued text. No field carries omitempty — all three are always present so the golden fixture pins the full shape.

type SessionFactsPayload added in v0.16.0

type SessionFactsPayload struct {
	ConversationID    string   `json:"conversation_id"`
	ClaudeCodeVersion string   `json:"claude_code_version"`
	PermissionMode    string   `json:"permission_mode"`
	TruncatedFields   []string `json:"truncated_fields"`
}

SessionFactsPayload is the body of an Envelope whose Type == TypeSessionFacts (docs/protocol-mobile.md § session_facts, #2253). Binary → phone direction; the wire form of turnevent.SessionFacts, which reports what claude's own build IS and what posture claude says the child is running under, from the same system/init line ModelAnnouncedPayload's value comes from.

Declared here (#2253) ahead of its producer so a client can be written against the shape — the sequencing #1405 used ahead of #1410, #1616 ahead of #1638 and #1704 ahead of #1848. The producer has since landed: turnbridge.MapEvent's turnevent.SessionFacts arm constructs it (#2254) and cmd/pyry's interactive turn emitter pushes it (#2252), so live traffic carries the frame.

Like ModelAnnouncedPayload it is conversation-scoped rather than turn-scoped, so there is no turn_id, and receiving one neither opens nor closes a turn: a per-turn report is not a turn boundary (turnevent.SessionFacts' own doc). PER LINE, NOT PER SESSION — claude emits init once per TURN, so one session produces several of these and the producer does not dedup. The bridge supplies ConversationID because the internal event carries none.

The two values' semantics are NOT restated here: turnevent.SessionFacts' field comments are their single source of truth, in the manner ModelAnnouncedPayload delegates to ModelAnnounced.Model. Named and delegated: both are claude's text VERBATIM, neither is parsed, normalised or checked against any published list; EITHER may be empty, because the producer emits when either fact is present; and PermissionMode is an OPEN SET on purpose, since an allow-list would drop the first report of a posture nobody has heard of, which is the case an operator most needs to see. A consumer-facing statement of each is in docs/protocol-mobile.md § session_facts.

TruncatedFields is the siblings' []string rather than ModelAnnouncedPayload's Truncated bool, and that payload's doc states the rule both follow: a bool is right when the payload bounds a SINGLE string and a name list would be permanently either nil or one known name; a named list is right the moment the report has to say WHICH of several was cut. Two fields is where the rule flips. Entries are the DAEMON's wire names — "claude_code_version" and "permission_mode", the second NOT claude's own permissionMode, exactly as RateLimitedPayload's are "limit_type" and not claude's rateLimitType. nil when nothing was cut, never an empty non-nil slice, and nil serialises as null: UnrecognizedMessagePayload's form, and what every truncated_fields row in docs/protocol-mobile.md already describes. It is load-bearing either way — a payload that dropped it would present claude's cut text to a phone as complete.

FOUR KEYS OF THE CAPTURED INIT LINE ARE DELIBERATELY ABSENT, and the absence is the guarantee rather than a gap: cwd, memory_paths and messaging_socket_path are the operator's local filesystem, and session_id is claude's own session identity, which is not the daemon's conversation identity (BackgroundTaskStartedPayload's reason plus #1380's). None is declared on the producer's decode target (internal/streamsup's systemInitLine), so this payload cannot carry them even by accident — a field never decoded cannot leak whatever a later sweep forgets to check. There is NO effort field because claude publishes none, measured in #2251 and machine-enforced by effortInitPins; see TypeSessionFacts' block. MCP server status belongs to the frame #2373 declares and is deliberately not folded in here.

SECURITY: both strings are claude-authored values that crossed the subprocess trust boundary. They are safe to RENDER as inert text and must never be fed to an HTML sink, an attribute, or a URL; the daemon bounds them but does not sanitize them — no control-character or terminal-escape stripping happens on this path, beyond the invalid-UTF-8 scrub a mid-rune cut forces — so they stay untrusted, model-influenced text all the way to the client, and the render boundary owing the sanitization is the CLIENT's. Their bounds are the producer's, decided at construction (internal/streamsup's maxClaudeVersionField and maxPermissionModeField), so this struct re-decides no maximum: a second cap here would be a second place the limit is decided, and the two could disagree silently.

PermissionMode CARRIES ONE HAZARD THE SIBLING DOES NOT, and it is the field a client is likeliest to misuse. It is a CLAIM, NOT A GUARANTEE: a buggy or compromised claude can report `default` while running under any posture at all, and what the value proves is only what claude SAID. Nothing in the daemon gates on it and the value is never fed back into a spawn or a control request — in particular it must not become an input to internal/streamsup's permissionModeAllowed, which bounds what the DAEMON may ASK FOR and is a deliberately different rule. A client MUST NOT read it as an authorization decision: suppressing a warning, unlocking an action, or rendering a safety posture on the strength of this string is exactly the misuse it cannot support. Both fields follow ModelAnnouncedPayload's standing constraint — this is a REPORT, never a control input.

type SessionSettingsPayload added in v0.16.0

type SessionSettingsPayload struct {
	SessionID       string         `json:"session_id"`
	Model           string         `json:"model"`
	Effort          string         `json:"effort"`
	EffectiveEffort NullableString `json:"effective_effort,omitzero"`
	YOLO            bool           `json:"yolo"`
	PermissionMode  string         `json:"permission_mode"`
	UsedTokens      int            `json:"used_tokens"`
	WindowTokens    int            `json:"window_tokens"`
	// Capabilities is what the resolved session supports (#2646). Present only
	// for a conn that negotiated CapabilityMultiAgent and a reply that resolved a
	// session; nil omits the key, so every other reply is byte-identical to the
	// shape before it. A pointer so the payload stays comparable.
	Capabilities *SessionCapabilities `json:"capabilities,omitempty"`
	// MemorySearch is the selected session's search-access report. Nil means
	// the reply has no report, preserving the older wire shape.
	MemorySearch *MemorySearchReport `json:"memory_search,omitempty"`
}

SessionSettingsPayload is the body of an Envelope whose Type == TypeSessionSettings (docs/protocol-mobile.md § Session settings). Binary → phone direction; the daemon's answer to a request_session_settings.

It is the READ half the #844 cluster never had. A client needs two things to drive the run-configuration UI: the current values, and the SessionID to address a set_session_settings to. Before this payload the only source of the values was screen_snapshot's side-load, and the only source of the id was the unsolicited session_transition marker — which the daemon fires ONLY on a clear or an idle eviction, never on session creation, so a client that had done neither never learned an id at all and could not write. That is the defect this payload closes.

The original fields have no omitempty, matching ScreenSnapshotPayload (snapshot.go) and deliberately UNLIKE the sibling SetSessionSettingsPayload above. They form a full report of saved state, so every original field is always on the wire and a zero value is a real answer, not an absence. EffectiveEffort is the one additive exception: its zero value is omitted when no applied reading is available. Specifically:

  • SessionID "" means the daemon could not resolve a session to address. A client MUST treat the settings as read-only rather than sending a set_session_settings with an empty id, which would be rejected.
  • Model / Effort "" mean "inherited default, no per-session override" — the same meaning they carry on screen_snapshot.
  • EffectiveEffort is independent from Effort: a string is a confirmed applied level, null means claude reported no effort parameter, and an omitted key means the applied value is unavailable or unsupported.
  • YOLO false means the current child has not confirmed bypass. It is not, by itself, proof that permissions are enforced: PermissionMode "" means no current-child confirmation is available.
  • PermissionMode "" can therefore appear beside a non-empty SessionID when a live child has not confirmed a posture yet, or when the resolved session is dormant and has no child. Model and Effort still report stored intent in those cases.
  • WindowTokens 0 means the daemon has no trustworthy window reading, and covers two cases (#2100): the usage seam was not wired, and the used count came out ABOVE the window the daemon believed, which disproves the belief. Read it with UsedTokens to tell them apart — 0 is the unwired seam, a real figure is the disproved window and is still the true context size. Either way "X of Y" is unavailable. UsedTokens 0 against a NON-zero WindowTokens is a genuine fresh session.

PermissionMode and YOLO always agree because the producer derives both from the same current-child confirmation: confirmed bypass reports "bypassPermissions" AND yolo true, while an unavailable confirmation reports "" AND false. This half can report a posture the WRITE half refuses to accept on its permission_mode field — deliberate, and the whole point of the read half existing. A client labels its menu from this value and keeps sending yolo to change the bypass posture.

Scope: the values are those of the session bound to the conversation the request named (RequestSessionSettingsPayload above, #1586/#1610), and SessionID names that same session, so a client reads and writes the same place. The whole set is keyed by conversation and resolved as ONE value, so no field can describe a session another field does not — which is why a client can never read one session's values and write its change to another. A request that resolves to no session gets every original field at its zero value and omits EffectiveEffort, never reporting some other session's values.

type SessionSettingsUpdatedPayload added in v0.16.0

type SessionSettingsUpdatedPayload struct {
	SessionID string `json:"session_id"`
}

SessionSettingsUpdatedPayload is the body of an Envelope whose Type == TypeSessionSettingsUpdated (docs/protocol-mobile.md § Session settings). Binary → phone direction; the daemon's confirmation that a set_session_settings was applied.

It identifies only the session the change was applied to; the request↔reply correlation rides Envelope.InReplyTo at the handler layer (#845), and the client already knows what it sent, so the reply does not echo the settings. SessionID is a plain string, always present, no omitempty.

type SessionTransitionPayload added in v0.15.0

type SessionTransitionPayload struct {
	ConversationID    string    `json:"conversation_id"` // routing key; plain string (no literal-null semantics), no omitempty — mirrors the sibling interactive payloads
	PreviousSessionID string    `json:"previous_session_id"`
	NewSessionID      string    `json:"new_session_id"`
	Reason            string    `json:"reason"`
	OccurredAt        time.Time `json:"occurred_at"`
	WorkspaceCwd      *string   `json:"workspace_cwd"` // *string + no omitempty: literal `null` for non-workspace_change reasons; omitempty would drop the key.
}

SessionTransitionPayload is the body of an Envelope whose Type == TypeSessionTransition (docs/protocol-mobile.md § session_transition). Binary → phone direction; the wire form of a session boundary the phone renders as a ThreadItem.SessionBoundary marker (pyrycode-mobile#336).

The push is update-only: session creation (sessions.New, Pool.Mint/CreateIn, GetOrCreateIn) emits no transition, and it does not report every session ID change. The silent RotateBootstrapForSelfHeal primitive has no production caller today. Clients discover or re-read IDs with request_session_settings for the named conversation: supply conversation_id and read session_settings.session_id; an empty ID means no addressable session.

ConversationID is the routing key — a plain string with no omitempty, mirroring the sibling interactive payloads (SendMessagePayload, etc.) — so the phone folds the boundary marker into the correct conversation's thread. The producer binds it from the active conversation↔session mapping in #741; until that lands it emits "" (harmless: the mobile consumer is parked).

Reason is a plain string (not a named enum, matching MessagePayload.Role / TurnEndPayload.StopReason — internal/protocol is a stdlib-only leaf data package) over the closed wire set {clear, idle_evict, workspace_change}. OccurredAt is RFC3339Nano per the envelope timestamp rule.

WorkspaceCwd is *string with no omitempty: it carries the new workspace dir for reason "workspace_change" and renders literal JSON null for "clear" / "idle_evict". This encodes the workspaceCwd-non-null-iff-workspace_change invariant directly on the wire — omitempty would drop the key and lose that distinction.

type SetConversationMutedPayload added in v0.24.0

type SetConversationMutedPayload struct {
	ConversationID string `json:"conversation_id"`
	Muted          *bool  `json:"muted"`
}

SetConversationMutedPayload is the body of a set_conversation_muted frame (#2572). Phone → binary. It names a target conversation and the muted value to store for it: true mutes, false unmutes, through one verb.

Muted is a pointer because the key is required: an absent key (or JSON null) decodes to nil and the handler rejects it as protocol.malformed. A plain bool would read a missing key as false and silently unmute. No omitempty, for the round-trip reason given on CreateConversationPayload.

Deliberately NOT a reuse of ArchiveConversationPayload, per the semantic-coupling rationale the sibling payloads document. The reply reuses ConversationUpdatedPayload verbatim.

type SetConversationPinnedPayload added in v0.41.0

type SetConversationPinnedPayload struct {
	ConversationID string `json:"conversation_id"`
	Pinned         *bool  `json:"pinned"`
}

SetConversationPinnedPayload is the phone-to-host set_conversation_pinned request. Both keys are required: consumers must reject an empty conversation ID or nil Pinned as protocol.malformed. The pointer preserves missing/null separately from false. Pinning requires a promoted conversation; unpinning remains allowed. The response reuses ConversationUpdatedPayload. Production handling is pending #3537/#3538.

type SetHostSystemPromptPayload added in v0.32.0

type SetHostSystemPromptPayload struct {
	SystemPrompt *string `json:"system_prompt"`
}

SetHostSystemPromptPayload is the body of set_host_system_prompt, client → daemon. SystemPrompt is required: missing/null decode to nil and are invalid; other non-string JSON values fail decoding. A nonnil pointer preserves any string verbatim, including whitespace and "". Only "" clears durably; reset uses an ordinary set of the default returned in HostSystemPromptPayload. No omitempty: the wire key is required even though the zero DTO is invalid.

type SetSessionSettingsPayload added in v0.16.0

type SetSessionSettingsPayload struct {
	SessionID      string  `json:"session_id"`
	Model          *string `json:"model,omitempty"`
	Effort         *string `json:"effort,omitempty"`
	YOLO           *bool   `json:"yolo,omitempty"`
	PermissionMode *string `json:"permission_mode,omitempty"`
}

SetSessionSettingsPayload is the body of an Envelope whose Type == TypeSetSessionSettings (docs/protocol-mobile.md § Session settings). Phone → binary direction; an inbound v2 control envelope.

The three settings fields are pointers as the *presence contract*: nil means "leave unchanged"; a non-nil pointer means "set to this value" — including a non-nil *"" (Model/Effort) or *false (YOLO), which are thereby distinguishable from omitted. This mirrors sessions.SettingsUpdate{Model, Effort *string; YOLO *bool} (#840) that the #845 handler decodes this payload into 1:1, so a nil field flows straight through to "leave the stored value untouched".

The omitempty on the three pointer fields is load-bearing and deliberately UNLIKE the sibling *string-without-omitempty payload (SessionTransitionPayload) whose spec wire shows a literal null sentinel. Here an unset field is *absent* from the wire (the minimal shape a client changing one setting naturally produces), not null. Go's omitempty treats a non-nil pointer as non-empty regardless of the pointee, so a non-nil *false / *"" still marshals its key — an omitted YOLO can never masquerade as a sent false, and an omitted Model can never masquerade as an instruction to clear a stored value (AC #2). Do NOT "fix" this by copying the sibling payloads' no-omitempty style.

SessionID is the addressing key — it matches sessions.Pool.UpdateSettings(id sessions.SessionID, …). A client learns it from SessionSettingsPayload below, the request/response route it can drive at any time, or observes a change to it on the unsolicited session_transition marker. The marker ALONE is not a sufficient source and this comment used to imply it was: the daemon fires it only on a clear or an idle eviction, never on session creation, so a client that had done neither never learned an id and could not write. A plain string, always required, no omitempty. PermissionMode names one of claude's permission modes (#1687), and it JOINS YOLO rather than superseding it — the mobile client speaks yolo and the wire types are not drifted without a matching change on every client. Removing yolo is a later ticket, filed when every client has moved.

Two rules make this field unlike its three siblings, and both are enforced at the wire boundary (internal/relay's set_session_settings handler), not here — this package defines shape:

  • Present-at-"" is NOT a settable value. For Model and Effort "" means "run at claude's own default", a real value the presence contract can carry. The default posture is a NAMEABLE mode ("default"), so an explicit "" names nothing and is refused. The pointer's job here is purely absent-vs-present.
  • A frame carrying BOTH this field and YOLO is refused as malformed. They are two spellings of one posture — yolo:true is bypassPermissions, yolo:false is default — so a frame carrying both is redundant or contradictory. Refusal rather than precedence means there is no rule for a client author or a reviewer to get wrong, and no client sends both.

The accepted vocabulary is claude's five NON-ESCALATING modes (default, acceptEdits, plan, auto, dontAsk), measured live by #2041. bypassPermissions is refused on this field: the escalation stays reachable only through YOLO, so it keeps exactly one spelling on the wire. That refusal is a wire-vocabulary decision and not a statement about what the daemon can deliver — since #2066 it delivers the escalation in band too, spelled as the bit — so widening this field to six needs its own argument rather than following from the daemon's.

type SetSystemPromptPayload added in v0.16.0

type SetSystemPromptPayload struct {
	ConversationID string  `json:"conversation_id"`
	SystemPrompt   *string `json:"system_prompt"`
}

SetSystemPromptPayload is the body of a set_system_prompt frame (docs/protocol-mobile.md § set_system_prompt). Phone → binary. It names a target conversation and the durable per-conversation system prompt to store for it — the operator-authored text appended to every session that conversation spawns from then on.

SystemPrompt is a pointer because the verb has to express THREE states, and a plain string could only express two:

null (or the key absent) — clear: the conversation returns to spawning with
                          the daemon constant alone, exactly as it does today
""                       — explicitly empty (a distinct stored state)
"<text>"                 — stored verbatim, after validation

null and an absent key are indistinguishable after decode and both mean clear. The pointer maps 1:1 onto conversations.Registry.SetSystemPrompt's own *string argument, which is the single validating door for all three states — including clear, which is why the field is nullable rather than the clear path getting a verb of its own.

No omitempty, matching CreateConversationPayload's rationale: omitempty on a nil pointer would drop the key entirely and break byte-equivalent round-trip.

The byte bound (conversations.MaxSystemPromptBytes) and the UTF-8 check are enforced at the registry, not here — this type carries the value, it does not police it.

Deliberately NOT a reuse of ChangeWorkspacePayload or ArchiveConversationPayload, per the semantic-coupling rationale the sibling payloads document. The reply reuses ConversationUpdatedPayload verbatim — see the note there on why that record gains no prompt field.

type SlashCommand added in v0.16.0

type SlashCommand struct {
	Name            string   `json:"name"`
	ArgumentHint    string   `json:"argument_hint"`
	Description     string   `json:"description"`
	Aliases         []string `json:"aliases"`
	TruncatedFields []string `json:"truncated_fields"`
}

SlashCommand is one row of a SlashCommandListPayload (docs/protocol-mobile.md § slash_command_list, #1727). Its fields are exactly the four per-entry keys claude's initialize reply carries and nothing invented; the measurement behind "exactly" is in SlashCommandListPayload's doc.

All three strings cross, not just the name. The Actions-menu grey-out needs names to match against, but the type-ahead renders all three: at 51 entries the description is what makes the list usable rather than a wall of names, and the argument hint is what tells the operator that a command takes something after it.

Name is NOT an identifier. One name in the capture is __remote-workflow, so no charset assumption belongs in this struct or in a client.

ArgumentHint is EMPTY on 33 of the capture's 51 entries, and no entry omits the key — so an empty hint is the ordinary case rather than missing data. That is why no string key here is optional: eliding it would make the common row indistinguishable from a malformed one.

Description may contain NEWLINES — claude-api's does — and 0x0a is the ONLY sub-0x20 byte anywhere across the 51 entries' four string fields. Newlines are therefore the control characters on this path rather than one class among several, and a client rendering a single-line row must handle that specific case.

Aliases is what makes the grey-out correct, and a shape dropping it would break the first consumer. The desktop Actions menu's own reset entry is an ALIAS of clear, not a command name, so a client matching against Name alone greys out a command that works. It is also why the cheap source cannot answer the question: the same capture's system/init line carries slash_commands, the identical 51 names in the identical order as bare strings, and not one of the 11 aliases. The key is always present on the wire and never null — see MarshalJSON, and read its rationale, which is NOT SlashCommandListPayload.MarshalJSON's.

TruncatedFields names THIS row's cut fields — "name", "argument_hint", "description", "aliases", the wire names rather than the Go ones, as RateLimitedPayload.TruncatedFields uses its JSON tags — and is null when nothing was cut. All four are enumerated because all four are strings the SECURITY paragraph credits and a producer may cut; #1720 reads this line to pick the names its producer emits, so an under-enumeration here would under-cover a real field. Deliberately NOT normalised the way Aliases is — see MarshalJSON. It is load-bearing rather than decoration: a row that dropped it would present claude's cut text to a phone as complete.

SECURITY: Name, ArgumentHint, Description and every string in Aliases are WORKSPACE-authored strings that crossed the subprocess trust boundary. That strengthens ModelOption's claude-authored warning rather than restating it: a command defined in a repository was written by whoever wrote that repository, which is a lower-trust origin than claude. They are safe to RENDER as inert text and must never be fed to an HTML sink, an attribute, or a URL; the daemon bounds them but does not sanitize them — no control-character or terminal-escape stripping happens on this path — so they stay untrusted text all the way to the client, and the render boundary owing the sanitization is the CLIENT's. Their bound is the producer's (#1719/#1720), decided at construction, so this struct re-decides no maximum and declares no charset check: a second cap here would be a second place the limit is decided, and the two could disagree silently.

The family's convention sentence — it is a REPORT, never a control input — needs the amendment ModelOption.Value carries, for a different reason: a client is meant to send a Name BACK, as the text of an ordinary message, because sending the slash command IS the feature. Publishing a name does not make it trusted. It arrives inbound as ordinary message text, on a path that does not treat it as a command vocabulary and does not consult this list, and no field here reaches a child as an argv element. This frame declares no inbound verb — TypeSlashCommandList's own doc has that reasoning — and grants nothing.

func (SlashCommand) MarshalJSON added in v0.16.0

func (c SlashCommand) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Aliases to an empty array, so a row always serialises as "aliases":[] and never as "aliases":null. It deliberately leaves TruncatedFields alone, which stays null when nothing was cut.

The reason is NOT SlashCommandListPayload.MarshalJSON's, and the asymmetry between the two is not an accident. An empty alias list is not a positive statement here, it is a COLLAPSE — and that is measured rather than argued. claude never sends "aliases": []: zero of the capture's 51 entries carry an empty array, 42 omit the key entirely and 9 carry a non-empty one. An entry with no aliases and an entry with the key absent are the same statement, and a client must not have to branch on absent-vs-empty to match an alias, so the wire states ONE position for both and [] is the position that spares every row an optional-array branch. This is exactly ModelOption.MarshalJSON's EffortLevels collapse with the frequency INVERTED: the majority case here, the single exception (Haiku) there.

THE DAEMON-INTERNAL VALUE COLLAPSES TOO, and #1825 settled it — the question this comment used to hand forward. turnevent.SlashCommand.Aliases reads an absent key, a JSON null and a published empty array as ONE reading, spelled nil, and owns the argument for it. It reached that answer the way turnevent.ModelOption.EffortLevels reached its own (#1828), by WEIGHING that precedent rather than inheriting it: the two lists' frequencies are inverted, so what carried was not the levels' conclusion but the observation that the frequency changes how often a collapse fires and not what either shape MEANS. So the two sides of this boundary agree, which is what makes this method's normalisation a one-shape job rather than a two-shape reconciliation. The wire's position would have been stated here either way, because an undeclared position is one #1720 would have to invent.

TruncatedFields is exempt for BackgroundTaskRosterPayload.MarshalJSON's own carve-out reason, unchanged: nil and [] say the identical thing there ("nothing was cut") and no consumer branches on the difference.

This method cannot be folded into the payload's: a payload marshaller normalising entries in place would mutate the caller's backing array unless the slice were copied first, and it would not fire at all when a SlashCommand is marshalled on its own.

Value receiver and the type alias, for SlashCommandListPayload.MarshalJSON's reasons.

type SlashCommandListPayload added in v0.16.0

type SlashCommandListPayload struct {
	ConversationID  string         `json:"conversation_id"`
	Commands        []SlashCommand `json:"commands"`
	DroppedCommands int            `json:"dropped_commands"`
}

SlashCommandListPayload is the body of an Envelope whose Type == TypeSlashCommandList (docs/protocol-mobile.md § slash_command_list). Binary → phone direction; the wire form of the slash-command inventory claude returns from a control_request with subtype initialize, alongside the models array ModelListPayload carries: the set of commands this session in this working directory will accept. A SNAPSHOT of what claude will accept, not a delta, and conversation-scoped rather than turn-scoped — receiving one neither opens nor closes a turn.

Declared here (#1727) ahead of its producer so a client can be written against the shape — the sequencing #1405 used ahead of #1410, #1616 ahead of #1638 and #1704 ahead of #1848. THE PRODUCER HAS SINCE LANDED: turnbridge.MapEvent's turnevent.SlashCommandList arm constructs it (#2001), which is the sibling sequencing paid off — that arm is the one every later consumer maps through rather than forking. Two consumers are blocked on the shape today: pyrycode-desktop#681, the Actions-menu grey-out that matches its menu entries against this list, and pyrycode-desktop#694, a type-ahead that filters the whole list live and renders each row as a name, an argument hint and a description.

ConversationID is present and unfilled by this ticket — the producer supplies it at mapping time, the seam every v2 interactive payload uses. claude's own session_id is deliberately absent for BackgroundTaskStartedPayload's reason: claude's session identity is not the daemon's conversation identity.

Commands is in claude's own order. The key is always present on the wire and never null — see MarshalJSON.

The COUNT is workspace- and version-dependent, and no client may assume one: 51 entries against claude 2.1.239 in this repository, while an earlier hand count against 2.1.220 in a different working directory reported 74. That variation is the feature's whole point, and it is why the list is per session and per working directory rather than a one-off global — so a client must not cache one list across working directories.

The payload's cost lives in the descriptions: the capture's 51 entries serialise to 14,277 bytes of compact UTF-8 against the 65519-byte v2 application-envelope cap. Comfortable but not free, so a cut has to be REPORTABLE rather than silent, which is what DroppedCommands and SlashCommand.TruncatedFields are for.

DroppedCommands is how many entries the producer cut that this frame does NOT carry; 0 when nothing was dropped. AN ENTRY CAP NOW EXISTS AND SOMETHING NOW COUNTS IT: streamsup's maxSlashCommandListEntries bounds the decoded entry count and turnevent.SlashCommandList.DroppedCommands carries what it cut (#1826). What is still missing is a PATH TO A CLIENT, so read the state of this key precisely rather than by inference. SOMETHING NOW WRITES IT — turnbridge.MapEvent's arm takes turnevent.SlashCommandList.DroppedCommands as its BASE, never recomputing the count from len(Commands) (#2001), and ADDS whatever its own frame-size cut drops on top (#2002), so this field is the sum of two cuts where the event-side field is the producer's alone — but cmd/pyry's interactiveTurnEmitterV2.Handle still has no case, so no frame of this type is produced at all, which means every value a client could observe here today is STILL the zero one and there is still no frame on which len(Commands) + DroppedCommands is the menu's true size. It becomes that the moment #2003 lands the emission, and not before. It was declared ahead of all of this because a wire with nowhere to put a drop discards it silently, while a permanent 0 reads as "nothing was dropped", which is a lie rather than a gap. #1719 owned the decode and is CLOSED; #1826 owned the cap and the count and is closed too; #2001 is where the field and that counter met, and is also where the CAUSES were settled — the field says entries were cut without naming a cause, deliberately, so that a drop for a shape reason lands in the same count. The count reports here rather than as a name in a top-level truncated_fields — which is why this payload has none, BackgroundTaskRosterPayload's stated reason — because a name-only report loses HOW MANY were lost, and each dimension reports where it is decided: a text cut is a property of one entry and rides that entry as SlashCommand.TruncatedFields.

The per-entry key set is COMPLETE, and that is measured rather than assumed. Against the committed capture internal/e2e/realclaude/testdata/initialize_control_v2.1.239.json (claude 2.1.239), name, description, argumentHint and aliases are the entire per-entry vocabulary: 42 of the 51 entries carry the first three, the other 9 carry all four, and there is no third key set. This shape adopts ALL FOUR, so unlike ModelOption it drops nothing — which means a key a later claude adds arrives as a documented gap against a stated measurement rather than as a silent drop.

func (SlashCommandListPayload) MarshalJSON added in v0.16.0

func (p SlashCommandListPayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Commands to an empty array, so a slash-command list always serialises as "commands":[] and never as "commands":null.

This implements BackgroundTaskRosterPayload.MarshalJSON's reason unchanged, and that whole rationale transfers: omitempty is out because an empty list is a POSITIVE statement — it says claude offered nothing — rather than an absence, and between null and [], [] reads as an empty list where null reads as absent/unknown, so a client decoding into a non-optional array type never has to branch. SlashCommand.MarshalJSON normalises its own Aliases for a DIFFERENT reason — read it there, so the asymmetry is not taken for an accident — and deliberately leaves TruncatedFields alone.

This method cannot do the entry's job for it. Assigning a fresh slice to this copy's own Commands field is safe, but reaching THROUGH it into p.Commands[i] would mutate the caller's backing array, which for a payload shared between an emitter goroutine and a per-connection fan-out is a data race as well as a correctness bug; and a payload-level normalisation would not fire at all when a SlashCommand is marshalled on its own.

Value receiver, so it applies to the value form a round trip and a bridge both take, and so the substitution lands on a copy rather than on the caller's slice. The type alias is the standard indirection that keeps json.Marshal from recursing back into this method.

type StallPayload added in v0.15.0

type StallPayload struct {
	ConversationID string `json:"conversation_id"`
}

StallPayload is the body of an Envelope whose Type == TypeStall (docs/protocol-mobile.md § stall). Binary → phone direction; the wire form of the internal-only turnevent.Stall onset marker. It carries conversation identity only — like turn_state, a stall is a coarse conversation-level signal, not turn-scoped, so there is no turn_id; and it is onset-only, so there is no clearing field (the phone self-clears on the next turn activity). The bridge (#608) supplies ConversationID because the internal Stall marker carries none.

type StopBackgroundTaskPayload added in v0.33.0

type StopBackgroundTaskPayload struct {
	ConversationID string `json:"conversation_id"`
	TaskID         string `json:"task_id"`
}

StopBackgroundTaskPayload names exactly one conversation and background task. Both ids are untrusted lookup identifiers, never paths. An empty conversation is dropped without cursor fallback; an empty task in a named conversation is refused. Neither field is omitted when marshalled.

type SwitchAgentPayload added in v0.37.0

type SwitchAgentPayload struct {
	ConversationID string  `json:"conversation_id"`
	Agent          string  `json:"agent"`
	Model          string  `json:"model"`
	Effort         *string `json:"effort,omitempty"`
}

SwitchAgentPayload is the body of a v2 TypeSwitchAgent request. ConversationID, Agent, and Model are always present; an empty Model selects the target agent's template default. Effort omitted or null is unspecified and marshals omitted; a present empty string clears it, while a nonempty string selects that effort. Validation and handling are deferred to #2870, production wiring to #2871.

type SystemPromptPayload added in v0.16.0

type SystemPromptPayload struct {
	SystemPrompt        *string `json:"system_prompt,omitempty"`
	SessionPromptStatus string  `json:"session_prompt_status"`
}

SystemPromptPayload is the body of an Envelope whose Type == TypeSystemPrompt (docs/protocol-mobile.md § Reading a conversation's system prompt). Binary → phone direction; the daemon's answer to a request_system_prompt, correlated by InReplyTo.

It is the READ half the #2151 cluster shipped without, and it carries the two things a client needs to render a prompt editor honestly: what is stored, and whether the child the operator is typing at is running under it.

SystemPrompt IS A POINTER WITH omitempty, AND THAT PAIRING IS THE WHOLE CONTRACT. It mirrors conversations.Conversation.SystemPrompt's storage encoding field for field, and for that field's stated reason: omitempty on a pointer tests the POINTER, not the pointee, so nil omits the key while a non-nil pointer to "" still emits "system_prompt": "". The registry's three states therefore stay distinguishable on the wire —

absent key / null  no prompt is stored (the default)
""                 an explicitly empty prompt, a distinct stored state
any string         the stored text, verbatim, up to MaxSystemPromptBytes

— which is what lets a client read a value and write it back through SetSystemPromptPayload, whose own SystemPrompt field is the same tri-state, without silently collapsing "explicitly empty" into "no prompt". A plain string with omitempty cannot express the split: both no-bytes states would serialize away and both would decode to "". Do NOT "fix" this to a plain string for symmetry with the neighbouring read payloads; TestSystemPromptPayload_TriStateSurvivesARoundTrip pins all three.

SessionPromptStatus HAS NO omitempty and is ALWAYS one of the three constants above, never "". Unlike SessionSettingsPayload's permission_mode — whose "" is the no-session sentinel — this field spells that state out as "no_session", because this payload has no second all-zero field to read it beside.

THE TWO FIELDS ARE INDEPENDENT and a client must not derive one from the other. A conversation storing text while nothing runs reports the text with "no_session"; a conversation storing nothing while a session runs that was spawned with nothing reports an absent key with "matches" — because Pool.SystemPromptFor collapses both no-bytes states to "" by design, so the daemon compares the COLLAPSED stored value and an explicitly empty prompt matches a session spawned with no operator text.

THE SPAWNED-WITH TEXT IS DELIBERATELY NOT CARRIED. "differs" says the two disagree and stops there: echoing up to another 8192 bytes of operator text back over the wire to say so is what this shape rules out, and a client that wants to show a diff is a later ticket. Adding the field later is cheap and would need its own argument against the envelope cap.

NO conversation_id EITHER, matching SessionSettingsPayload and unlike ModelListPayload. Correlation rides InReplyTo, and carrying an id would force a choice this reply refuses to make: an unhosted conversation has no registry-canonical id to report, and echoing back the client's own string is the shape every other verb here declines. Its absence is what lets the unhosted answer be byte-identical to the answer for a hosted conversation holding no prompt and running nothing.

type ThinkingProgressPayload added in v0.16.0

type ThinkingProgressPayload struct {
	ConversationID       string `json:"conversation_id"`
	EstimatedTokens      int    `json:"estimated_tokens"`
	EstimatedTokensDelta int    `json:"estimated_tokens_delta"`
}

ThinkingProgressPayload is the body of an Envelope whose Type == TypeThinkingProgress (docs/protocol-mobile.md § thinking_progress, #1386). Binary → phone direction; the wire form of turnevent.ThinkingProgress, the daemon's translation of claude's system/thinking_tokens line. It reports that claude is actively reasoning and roughly how much — claude's only mid-turn proof of life on the stream-json surface.

Like turn_state it is a coarse conversation-level signal, NOT turn-scoped, so there is no turn_id, and receiving one neither opens nor closes a turn. The bridge supplies ConversationID because the internal event carries none; claude's own session_id is deliberately absent for BackgroundTaskStartedPayload's reason, and the parser drops it before the event exists (#1380/#1385).

Both fields are claude's own integer readings, carried verbatim. There is no TruncatedFields, and its absence is a decision rather than an omission: unlike every sibling above this payload carries no claude-authored TEXT at all, so nothing is ever cut, and a permanently-nil field would claim a bound that does not exist. For the same reason there is no producer byte cap to mirror here.

Two consumer hazards ride these numbers and are NOT restated here, because turnevent.ThinkingProgress's field comments are their single source of truth (with the measured numbers): EstimatedTokens is not monotonic across a turn, and the EstimatedTokensDelta values a client receives do not sum to the turn's total. A consumer-facing statement of both, plus the two reasons absence proves nothing, is in docs/protocol-mobile.md § thinking_progress.

type ThreadCatchUpPayload added in v0.39.0

type ThreadCatchUpPayload struct {
	ConversationID string `json:"conversation_id"`
	Epoch          string `json:"epoch"`
	Version        uint64 `json:"version"`
	Limit          int    `json:"limit,omitempty"`
	// Projection also selects this conversation's live view; omission is complete.
	Projection string `json:"projection,omitempty"`
}

ThreadCatchUpPayload requests full changed/active items and parent closure. Version zero selects the newest window; nonzero catch-up is never truncated. Normalize Limit even for nonzero catch-up, which rejects negative values.

type ThreadChildrenPayload added in v0.41.0

type ThreadChildrenPayload struct {
	ConversationID string                 `json:"conversation_id"`
	Epoch          string                 `json:"epoch"`
	Version        uint64                 `json:"version"`
	ItemID         uint64                 `json:"item_id"`
	Rev            uint64                 `json:"rev"`
	Children       []ThreadSummary        `json:"children"`
	Final          bool                   `json:"final"`
	More           *bool                  `json:"more,omitempty"`
	Cursor         *ThreadExpansionCursor `json:"cursor,omitempty"`
}

ThreadChildrenPayload carries direct summaries or a separate empty Final marker. Only the marker has More and (when true) Cursor. More is authoritative; only false finishes the parent's enumeration at this capture. Interrupted, cancelled or failed delivery certifies nothing. Neither expansion completion nor its Version advances full-thread checkpoints or live join watermarks.

type ThreadCompactUpdatePayload added in v0.41.0

type ThreadCompactUpdatePayload struct {
	Projection     string         `json:"projection"`
	ConversationID string         `json:"conversation_id"`
	Epoch          string         `json:"epoch"`
	FromVersion    uint64         `json:"from_version"`
	Version        uint64         `json:"version"`
	Item           *ThreadItem    `json:"item,omitempty"`
	Header         *ThreadSummary `json:"header,omitempty"`
	Progress       bool           `json:"progress"`
}

ThreadCompactUpdatePayload declares a full root replacement or hidden-only Progress for the exclusive source interval (FromVersion, Version]. Exactly one of Item, Header or Progress is supplied. Item retains complete non-tool/agent content; Header carries tool/agent metadata only. Rows must be public roots. Progress explicitly accounts for consumed entries producing no root change. These intervals never certify complete inventory or downloaded subtree detail. Consumers apply only in matching scope after initialization; gaps require catch-up. Repeated rows replace by source identity, without opening descendants. Intervals may overlap when one consumed entry changes several roots: equal versions for different identities must not be discarded. Only a successful query marker establishes a completed recovery checkpoint.

type ThreadContinuation added in v0.39.0

type ThreadContinuation struct {
	UpdateID   string `json:"update_id"`
	Index      uint64 `json:"index"`
	Offset     uint64 `json:"offset"`
	TotalBytes uint64 `json:"total_bytes"`
	Final      bool   `json:"final"`
}

ThreadContinuation describes assembly progress, never history progress. UpdateID is SHA-256(type + NUL + serialized logical payload), in lowercase hex. Index and Offset start at zero. TotalBytes counts decoded Data bytes. Consumers require consecutive indices/offsets and identical assembly metadata; Final commits only after length, digest, routing, request correlation and applicable base_rev validation. It never certifies query coverage. A failed assembly requires catch-up without advancing completed rev/version.

type ThreadExpansionCursor added in v0.41.0

type ThreadExpansionCursor struct {
	ConversationID string `json:"conversation_id"`
	Epoch          string `json:"epoch"`
	ItemID         uint64 `json:"item_id"`
	Rev            uint64 `json:"rev"`
	Version        uint64 `json:"version"`
	Order          uint64 `json:"order"`
	ID             uint64 `json:"id"`
}

ThreadExpansionCursor binds a child enumeration to one capture and its last emitted (Order, ID). Resume strictly after that tuple, including order-zero rows. Any binding mismatch requires a fresh first page, not an old snapshot. The cursor conveys no authority and must be checked against current Store facts.

func (ThreadExpansionCursor) Matches added in v0.41.0

Matches compares scope, expected parent revision, epoch and consumed version.

type ThreadExpansionRequest added in v0.41.0

type ThreadExpansionRequest struct {
	ConversationID string                 `json:"conversation_id"`
	Epoch          string                 `json:"epoch"`
	ItemID         uint64                 `json:"item_id"`
	ExpectedRev    uint64                 `json:"expected_rev"`
	Limit          int                    `json:"limit,omitempty"`
	Cursor         *ThreadExpansionCursor `json:"cursor,omitempty"`
}

ThreadExpansionRequest names a tool body or a direct-child page of ItemID. First reads require matching nonempty Epoch and ExpectedRev. Children use Limit and an optional exclusive Cursor. Handlers enforce required fields, public ownership and normal thread/interactive authorization, not DTO decoding.

type ThreadItem added in v0.39.0

type ThreadItem struct {
	ID   uint64 `json:"id"`
	Kind string `json:"kind"`
	// Order is absent for queued, dropped or lost sends until delivery supplies
	// its history entry order. Parent is absent for the main thread.
	Order      uint64 `json:"order,omitempty"`
	Rev        uint64 `json:"rev"`
	EndedOrder uint64 `json:"ended_order,omitempty"`
	// Session and Agent carry recorded attribution only, with no inferred default.
	// NoChild distinguishes positively no producing child from unknown provenance.
	Session string `json:"session,omitempty"`
	Agent   string `json:"agent,omitempty"`
	NoChild bool   `json:"no_child,omitempty"`
	Turn    string `json:"turn,omitempty"`
	Parent  uint64 `json:"parent,omitempty"`
	Status  string `json:"status"`
	Active  bool   `json:"active"`
	Shown   bool   `json:"shown"`
	Summary string `json:"summary"`
	Subtype string `json:"subtype,omitempty"`
	// Content retains kind-specific fields, including unknown fields, as inert
	// JSON. Clients must treat it as untrusted display data, never executable input.
	Content json.RawMessage `json:"content"`
}

ThreadItem is a full daemon-built row, shared by live updates and thread pages. ID and Kind never change. IDs, orders and revisions are history-entry numbers below 2^53; producers enforce that range. Unknown kinds and status words remain display data, with Summary supplying a plain fallback and Active stating whether the item can still change by itself.

type ThreadItemAddedPayload added in v0.39.0

type ThreadItemAddedPayload struct {
	ConversationID string     `json:"conversation_id"`
	Epoch          string     `json:"epoch"`
	Version        uint64     `json:"version"`
	Item           ThreadItem `json:"item"`
}

ThreadItemAddedPayload declares a new full item emitted by the daemon fold publisher. Version is the newest folded history entry; Epoch changes when item identities may no longer have the same meaning and clients must reload the conversation.

type ThreadItemChangedPayload added in v0.39.0

type ThreadItemChangedPayload struct {
	ConversationID string `json:"conversation_id"`
	Epoch          string `json:"epoch"`
	Version        uint64 `json:"version"`
	ItemID         uint64 `json:"item_id"`
	BaseRev        uint64 `json:"base_rev"`
	Rev            uint64 `json:"rev"`
	// Changes must be an object keyed by item field name, excluding id and kind.
	// Missing keys mean unchanged; supplied empty, false, zero or null values are
	// replacements. A content patch replaces the entire content value. Raw values
	// stay inert, including unknown fields; consumers own validation/application.
	Changes map[string]json.RawMessage `json:"changes"`
}

ThreadItemChangedPayload declares an in-place item update emitted by the daemon fold publisher. Clients apply it only when their item's revision equals BaseRev, otherwise requesting catch-up. Rev is the resulting revision; identity and kind stay fixed.

type ThreadItemsPayload added in v0.39.0

type ThreadItemsPayload struct {
	ConversationID string       `json:"conversation_id"`
	Epoch          string       `json:"epoch"`
	Version        uint64       `json:"version"`
	Items          []ThreadItem `json:"items"`
	Final          bool         `json:"final"`
	FromVersion    *uint64      `json:"from_version,omitempty"`
	LowerOrder     *uint64      `json:"lower_order,omitempty"`
	UpperOrder     *uint64      `json:"upper_order,omitempty"`
	Continuation   *uint64      `json:"continuation,omitempty"`
	OlderExists    *bool        `json:"older_exists,omitempty"`

	Projection string          `json:"projection,omitempty"`
	Headers    []ThreadSummary `json:"headers,omitempty"`
}

ThreadItemsPayload is a row batch or a separate empty success marker. Only Final certifies coverage. Nonzero catch-up markers carry FromVersion for (FromVersion, Version]; window/page markers carry all four page fields, even zero/false. The range is [LowerOrder, UpperOrder), Continuation equals LowerOrder, and OlderExists is authoritative. Extras never expand that range. Ordinary batches omit all coverage fields and explicitly emit Final false. An object continuation selects ThreadUpdatePart assembly instead of this DTO; its final flag completes assembly only, never request coverage. Compact projection puts full public non-tool/agent roots in Items and public tool/agent roots in Headers. Order/ID determine placement across both arrays. Compact coverage certifies only that projection's root window/source interval, never complete inventory or detail. All data, parts and markers repeat scope. Errors, disconnects and partial replies advance no completed checkpoint.

func (ThreadItemsPayload) MarshalJSON added in v0.39.0

func (p ThreadItemsPayload) MarshalJSON() ([]byte, error)

type ThreadPagePayload added in v0.39.0

type ThreadPagePayload struct {
	ConversationID string `json:"conversation_id"`
	BeforeOrder    uint64 `json:"before_order"`
	Limit          int    `json:"limit,omitempty"`
	Projection     string `json:"projection,omitempty"`
	Epoch          string `json:"epoch,omitempty"` // Required for compact pages.
}

ThreadPagePayload requests the ordered window below exclusive BeforeOrder. Limits count ordered rows; ties and parent extras may exceed them.

type ThreadResetPayload added in v0.39.0

type ThreadResetPayload struct {
	ConversationID string `json:"conversation_id"`
	Epoch          string `json:"epoch"`
	Version        uint64 `json:"version"`
	Projection     string `json:"projection,omitempty"`
}

ThreadResetPayload terminates a correlated query without certifying partial items or advancing a completed checkpoint. ErrorPayload is terminal failure.

type ThreadSummary added in v0.41.0

type ThreadSummary struct {
	ID            uint64 `json:"id"`
	Kind          string `json:"kind"`
	Order         uint64 `json:"order"`
	Rev           uint64 `json:"rev"`
	EndedOrder    uint64 `json:"ended_order,omitempty"`
	Session       string `json:"session,omitempty"`
	Agent         string `json:"agent,omitempty"`
	NoChild       bool   `json:"no_child,omitempty"`
	Turn          string `json:"turn,omitempty"`
	Parent        uint64 `json:"parent"`
	Status        string `json:"status"`
	Active        bool   `json:"active"`
	Shown         bool   `json:"shown"`
	Headline      string `json:"headline"`
	Subtype       string `json:"subtype,omitempty"`
	DetailOmitted bool   `json:"detail_omitted"`

	ErrorSummary      *string `json:"error_summary,omitempty"`
	PublicChildCount  *uint64 `json:"public_child_count,omitempty"`
	HasPublicChildren *bool   `json:"has_public_children,omitempty"`
	SubtreeVersion    *uint64 `json:"subtree_version,omitempty"`
}

ThreadSummary contains metadata only, with explicitly omitted detail and no descendant inventory. Headline is plain single-line display text, at most 200 Unicode code points including an ellipsis. Never interpret it as markup. Optional facts are unknown when absent, never evidence of no error/children or fresh cached detail. IDs, counts and versions are integers below 2^53, with zero allowed for known empty counts/freshness. PublicChildCount excludes private children and, when known, requires HasPublicChildren == (count > 0). HasPublicChildren alone may be known. NoChild describes attribution only. SubtreeVersion is epoch-scoped freshness, changing on nested public changes independently of source Rev, which is the revision accepted by expansion reads. Changed ancestor freshness invalidates cached subtree knowledge even while open: explicitly refresh demanded bodies/pages with bounded expansion reads. Unknown freshness proves nothing; conservative invalidation is allowed.

func NewThreadSummary added in v0.41.0

func NewThreadSummary(i ThreadItem) ThreadSummary

NewThreadSummary projects metadata without retaining Content.

func (ThreadSummary) MarshalJSON added in v0.41.0

func (s ThreadSummary) MarshalJSON() ([]byte, error)

MarshalJSON enforces bounded plain headline/error text without reading detail. An explicit empty ErrorSummary means known no error; omission means unknown.

type ThreadTextAppendPayload added in v0.39.0

type ThreadTextAppendPayload struct {
	ConversationID string `json:"conversation_id"`
	Epoch          string `json:"epoch"`
	Version        uint64 `json:"version"`
	ItemID         uint64 `json:"item_id"`
	BaseRev        uint64 `json:"base_rev"`
	Rev            uint64 `json:"rev"`
	Text           string `json:"text"`
}

ThreadTextAppendPayload declares a message text suffix emitted by the daemon fold publisher. Text is appended only when the item's revision equals BaseRev; Rev is the resulting revision. A mismatch requires catch-up rather than guessing.

type ThreadToolBodyPayload added in v0.41.0

type ThreadToolBodyPayload struct {
	ConversationID string          `json:"conversation_id"`
	Epoch          string          `json:"epoch"`
	Version        uint64          `json:"version"`
	ItemID         uint64          `json:"item_id"`
	Rev            uint64          `json:"rev"`
	Kind           string          `json:"kind"`
	Content        json.RawMessage `json:"content,omitempty"`
	Final          bool            `json:"final"`
}

ThreadToolBodyPayload carries existing rendered tool_call/agent Content, including unknown fields, without additional truncation or enlarged upstream limits. An available empty input/output object differs from absent detail. A separate Final marker omits Content. Fragment final completes assembly only; complete data plus the marker completes this request at this capture. Cached bodies are scoped by conversation/epoch/item/source Rev, independently of ancestor subtree freshness. Reads do not subscribe live descendants or change the selected view. Completion never certifies compact query coverage.

type ThreadUpdatePart added in v0.39.0

type ThreadUpdatePart struct {
	Projection     string              `json:"projection,omitempty"`
	ConversationID string              `json:"conversation_id"`
	Epoch          string              `json:"epoch"`
	Version        uint64              `json:"version"`
	ItemID         uint64              `json:"item_id"`
	BaseRev        *uint64             `json:"base_rev,omitempty"`
	Rev            uint64              `json:"rev"`
	Continuation   *ThreadContinuation `json:"continuation,omitempty"`
	Data           string              `json:"data"`
}

ThreadUpdatePart replaces an oversized update payload under its original type. Check Continuation before decoding an ordinary DTO. Concatenate Data, decode that JSON as the original DTO, then apply atomically. No fragment is a patch or message suffix by itself. Kind, placement, unknown values and explicit clears are preserved inside the assembled payload. Query fragments serialize the whole single-item batch. BaseRev is present only for changes and appends.

type ToolDeniedPayload added in v0.16.0

type ToolDeniedPayload struct {
	ConversationID string `json:"conversation_id"`
	TurnID         string `json:"turn_id"`
	// ToolUseID is the refused call, byte-identical to the tool_use and tool_result
	// frames for the same call. Empty and named in dropped_fields means the daemon
	// emptied an over-cap id rather than cutting it: a cut join key joins to nothing
	// while still looking like a real handle, which is strictly worse than an absence
	// a client can see.
	ToolUseID string `json:"tool_use_id"`
	// ToolName is claude's name for the tool it refused ("Bash" in every captured
	// denial). An OPEN SET carried verbatim; dropped rather than cut when over-cap,
	// since a consumer matches this token against claude's tool set.
	ToolName string `json:"tool_name"`
	// DecisionReasonType is claude's word for WHAT denied the call — "classifier",
	// "asyncAgent", "mode" and "rule" are the documented values. OBSERVED ABSENT IN
	// EVERY CAPTURED DENIAL at claude 2.1.239, so empty is the ordinary reading here
	// rather than the exceptional one; the slices above say which emptiness it is.
	DecisionReasonType string `json:"decision_reason_type"`
	// DecisionReason is claude's free-form explanation, absent in every captured
	// denial exactly as DecisionReasonType is. Cut rather than dropped and reported in
	// truncated_fields, on Message's reasoning: a cut sentence still reads as what it
	// is. Carries Message's SECURITY reading verbatim.
	DecisionReason string `json:"decision_reason"`
	// Message is claude's rejection text — the prose it also writes into the
	// tool_result. Cut rather than dropped, reported in truncated_fields.
	Message string `json:"message"`
	// TruncatedFields names the fields the daemon CUT to fit their caps, in this
	// struct's declaration order, under this frame's wire keys: "decision_reason",
	// "message". nil when nothing was cut, never an empty slice.
	TruncatedFields []string `json:"truncated_fields"`
	// DroppedFields names the fields the daemon EMPTIED for exceeding their caps, in
	// declaration order, under this frame's wire keys: "tool_use_id", "tool_name",
	// "decision_reason_type" — tool_use_id rather than the daemon-internal
	// tool_call_id, which is what the bridge's rename exists to guarantee. nil when
	// nothing was dropped.
	DroppedFields []string `json:"dropped_fields"`
}

ToolDeniedPayload is the body of an Envelope whose Type == TypeToolDenied (docs/protocol-mobile.md § tool_denied, #2233). Binary → phone direction; the wire form of turnevent.ToolCallDenied, which reports that claude REFUSED to run a tool call it had already announced. Turn-scoped like the two frames it joins, so unlike the conversation-scoped status peers below it carries a turn_id.

IT IS NOT A WIDER tool_result, AND IT COULD NOT HAVE BEEN. claude states the denial on a line that arrives BEFORE the tool result, so folding it in would need the parser to latch cross-line state keyed by tool_use_id; and #2234's result-line recovery reports denials for calls whose tool_result frame has already shipped, which a field on a sent frame cannot answer. A client joins this row to the tool_use and tool_result carrying the same ToolUseID — the identifier is byte-identical across all three, which is the whole point of publishing it.

ToolName IS SPELLED tool_name WHERE ToolUsePayload SPELLS THE SAME VALUE name, and the divergence is deliberate rather than drift. On that frame the tool IS the subject, so an unqualified name is unambiguous; here it is one named thing among several. The binding reason is the report slices below: they name fields by keys THIS frame carries, so the token and the wire key have to be the same string.

THE TWO REPORT SLICES ARE THE FRAME'S OWN VOCABULARY, NOT THE DAEMON'S INTERNAL ONE. turnevent.ToolCallDenied names the id tool_call_id — its own field name — and the bridge (internal/turnbridge's deniedReportKeys) rewrites exactly that one token to tool_use_id on the way here. A token naming a key the frame does not carry is one a client cannot look up, which would make the report unusable precisely where it matters most. Every other token already names a key declared below.

THE THREE-VALUED READING THE SLICES MAKE DECIDABLE is what they are for, and it is the reason a second slice exists at all. For any field named in either:

  • empty and named in NEITHER slice — claude sent nothing.
  • empty and named in dropped_fields — the daemon emptied an over-cap value.
  • present and named in truncated_fields — the daemon cut claude's text to fit.

Without dropped_fields an empty ToolName could not be told from a tool_name claude never sent. RateLimitedPayload.TruncatedFields carries only the first distinction because on that event nothing drops; CompactionBoundaryPayload.Trigger drops with no report because it is the only droppable value there, so an empty trigger is already unambiguous. Here three fields drop, and the ambiguity is real.

BOTH SLICES ARE nil WHEN NOTHING FIRED, AND nil REACHES THE WIRE AS null. This type therefore has NO MarshalJSON, and the absence is deliberate: RateLimitedPayload is the precedent, and BackgroundTaskRosterPayload.MarshalJSON's nil→[] means the OPPOSITE and does not generalise. An empty roster is a positive statement; nothing-was-cut is an absence. An allocated [] here would tell a phone that claude's cut text is complete. No omitempty either, per this file's rule, so both keys are always present.

SECURITY: Message and DecisionReason are claude-authored PROSE that crossed the subprocess trust boundary — bounded by the daemon (internal/streamsup's maxDenialProse) and NOT sanitized. A rule-based denial may quote THE COMMAND LINE THAT WAS REFUSED, which carries whatever an operator typed, and every captured denial names absolute host paths of the session's allowed working directories. They take UnrecognizedMessagePayload.Raw's rule: render as inert text ATTRIBUTED TO claude, never as the daemon's own finding, and never feed either to an HTML sink, an attribute, a URL, or anything that executes or re-shells it. ToolName and DecisionReasonType are short TOKENS from open sets and take the NARROWER TurnEndPayload.Outcome rule instead — switch on them against known values, treat an unrecognised one as unknown — the same prose-versus-token split CompactingPayload.ErrorText and CompactionBoundaryPayload.Trigger draw next door. Every bound is the producer's, decided at construction, so this struct re-decides no maximum: a second cap here would be a second place the limit is decided and the two could disagree silently. The frame is a REPORT, never a control input — NOTHING IN THE DAEMON KEYS A BEHAVIOUR ON ANY FIELD HERE, which is what keeps a fabricated denial a misleading label rather than an actuator.

type ToolProgressPayload added in v0.16.0

type ToolProgressPayload struct {
	ConversationID string `json:"conversation_id"`
	TurnID         string `json:"turn_id"`
	ToolUseID      string `json:"tool_use_id"`
	ElapsedSeconds int    `json:"elapsed_seconds"`
}

ToolProgressPayload is the body of an Envelope whose Type == TypeToolProgress. It updates the open ToolUsePayload row with the matching ToolUseID. The elapsed value is claude's signed reading, forwarded verbatim rather than computed, clamped, or accumulated by the daemon.

The join id was already bounded at construction by the turnevent producer. It remains an untrusted display handle rather than a capability: neither this package nor the outbound bridge acts on it. No field uses omitempty, so zero values remain explicit on the wire like every other interactive-event payload.

type ToolResultPayload added in v0.15.0

type ToolResultPayload struct {
	ConversationID  string `json:"conversation_id"`
	TurnID          string `json:"turn_id"`
	ToolUseID       string `json:"tool_use_id"`
	ParentToolUseID string `json:"parent_tool_use_id"`
	IsError         bool   `json:"is_error"`
	ResultSummary   string `json:"result_summary"`
	ResultDetail    string `json:"result_detail"`
}

ToolResultPayload is the body of an Envelope whose Type == TypeToolResult (docs/protocol-mobile.md § tool_result). Binary → phone direction; reports the outcome of the tool_use with the matching ToolUseID. ResultSummary is a human-readable précis of the result, not the raw output.

ResultDetail is a short précis of an edit or write's structured outcome — "+10 −3", "created · 54 lines" — composed by the daemon from the tool_use_result sidecar. Read, shell, search and unrecognised shapes send an empty detail (#2745). A client renders it beside the row and never parses it.

RENDER IT VERBATIM. The separators are U+2212 MINUS SIGN (not a hyphen) and U+00B7 MIDDLE DOT spaced on both sides; they are part of the contract, so a client that substitutes ASCII lookalikes is showing something this daemon did not send.

The two summary fields do NOT share a provenance, and a reader who assumes they do will reason wrongly about both. ResultSummary is claude's own text passed through under a rune cap (turnbridge's maxResultSummaryRunes). ResultDetail contains no claude-supplied byte: its producer formats decoded integers and its own literals, so its alphabet is digits, spaces, ASCII letters and the two glyphs named above, and its length is bounded at construction rather than by a cap here.

It carries no omitempty, per this file's rule: absence and "" mean the same thing (no count), and always emitting the key keeps the testdata fixture pinning the full shape. A client built before this landed ignores the unknown key; one built after it decodes a frame that lacks the key to "" without error, so the field is optional in the sense that binds. ParentToolUseID (#2191) is ToolUsePayload's field with ToolUsePayload's meaning and ToolUsePayload's grouping-hint-not-a-capability rule, carried here so a result row groups with the call row it completes. Read that docblock; it is the single source of truth for both.

The BOUND matters more on this frame than on that one, which is why the producer caps it at all. tool_result is never-droppable control class (§ Error codes, 4413): a frame over the application-envelope cap is LOST, not truncated, so an unbounded claude-authored string here would cost the whole row rather than shorten it. The value is bounded at construction at 256 bytes, which is why the worst case computed for ResultSummary above still holds.

type ToolUsePayload added in v0.15.0

type ToolUsePayload struct {
	ConversationID  string            `json:"conversation_id"`
	TurnID          string            `json:"turn_id"`
	ToolUseID       string            `json:"tool_use_id"`
	ParentToolUseID string            `json:"parent_tool_use_id"`
	Name            string            `json:"name"`
	InputSummary    string            `json:"input_summary"`
	Input           map[string]string `json:"input"`
}

ToolUsePayload is the body of an Envelope whose Type == TypeToolUse (docs/protocol-mobile.md § tool_use). Binary → phone direction; announces a tool invocation. InputSummary is a human-readable précis of the tool input, not the raw input.

Input is the tool input's own top-level fields (#1678), each value the input's value verbatim — a JSON string decoded, any other JSON type in its compact JSON form — so a client can show what a call ACTS ON instead of the first 200 runes of a compacted blob. It is what InputSummary could never be: per-field rather than one flattened line, so an Edit's file_path survives alongside the replaced text rather than being buried inside it.

The bounds are the bridge's, decided at construction (internal/turnbridge's maxInputValueRunes / maxInputKeyRunes / maxInputFields / maxInputTotalRunes), so this struct re-decides no maximum, for RateLimitedPayload's reason: a second cap here would be a second place the limit is decided and the two could disagree silently. A value the bridge shortened ends in "…" — this wire's value-level truncation convention, the one InputSummary already uses — and there is deliberately no truncated_fields list to name the cut or dropped fields (#1678 decided this explicitly). The known cost is that a value legitimately ending in "…" is indistinguishable from a cut one.

A field can be ABSENT because the total bound dropped it; InputSummary remains the whole-input fallback. Key order on the wire is alphabetical, a marshalling artefact of the map rather than the input's own order, so display order is the client's choice. The key is always present and never null — see MarshalJSON.

This map is what makes ToolUsePayload non-comparable with ==. Every existing comparison already goes through reflect.DeepEqual or byte equality; a future == against an any-typed copy would compile and panic at runtime.

SECURITY: the values are DISPLAY STRINGS, NOT CAPABILITIES. They are model-authored text that crossed the subprocess trust boundary and that the daemon neither resolved nor validated — a file_path is not canonicalised and may be relative or traversing, and a Bash command value is a literal shell command line. A client may render them as inert text; it must never open one as a path on its own filesystem, execute or re-shell one, or feed one to an HTML sink, an attribute, or a URL. ParentToolUseID (#2191) names the Agent/Task call that spawned the subagent making this call, and is EMPTY on the main conversation. A client joins a child to its parent on the ToolUseID these frames already carry — the two are byte-identical — so three parallel subagents render as three collapsible groups instead of thirty rows interleaved into the main thread. Nesting needs no extra field: the value is claude's own, read verbatim with no branch on depth, so a call made by a subagent that a subagent spawned names the INNER Agent call and following ids rebuilds the whole tree.

IT IS A GROUPING HINT, NOT A CAPABILITY, and it takes Input's rule above. It is model-authored text that crossed the subprocess trust boundary; the daemon neither resolved it nor checked that it names a call this client has seen. Render the row under a parent when the id matches one, render it at top level when it does not, and never dereference it as anything else. Nothing in the daemon branches on the value.

Empty has exactly ONE meaning, "main thread", which is what makes it safe to drop an unusable value into: the producer (streamsup's parentToolUseID) empties a value it cannot read or that exceeds its cap rather than cutting it, because a cut join key matches no ToolUseID while still looking like one. So an emptied id degrades to top-level rendering — the behaviour before this field existed — rather than to a wrong parent. There is deliberately no report naming which emptiness it is; unlike ToolDeniedPayload's fields, this one has no second meaning for a report to disambiguate.

It carries no omitempty, per this file's rule: absence and "" mean the same thing, and always emitting the key keeps the testdata fixture pinning the full shape. A client built before this landed ignores the unknown key.

func (ToolUsePayload) MarshalJSON added in v0.16.0

func (p ToolUsePayload) MarshalJSON() ([]byte, error)

MarshalJSON normalises a nil Input to an empty map, so a tool call with no sendable fields always serialises as "input":{} and never as "input":null.

This is BackgroundTaskRosterPayload.MarshalJSON's pattern applied to a map, and its doc comment is the single source of truth for why the deviation is worth the lines and why a doc comment alone would not have been enough. The same reasoning holds here: the bridge (#1678) returns a nil map for all three no-fields cases — an absent input, an empty object, and an input that is not a JSON object at all — so without this method those would ship null while the fixture went on asserting {}, and nothing in `make check` would notice.

Between null and {}, {} is the better client contract for the reason [] beats null there: it is iterable without a branch in every client language. The payload deliberately does not distinguish the three no-fields cases, so there is nothing for null to mean that {} does not.

type TurnEndPayload added in v0.15.0

type TurnEndPayload struct {
	ConversationID string `json:"conversation_id"`
	TurnID         string `json:"turn_id"`
	StopReason     string `json:"stop_reason"`
	// Outcome is claude's `result` subtype — an OPEN SET, carried verbatim. The
	// observed values are success, error_during_execution, error_max_turns,
	// error_max_budget_usd and error_max_structured_output_retries; a client must
	// treat an unrecognised token as unknown rather than as an error, because
	// claude may ship one at any time.
	//
	// SECURITY: claude-authored text. The daemon BOUNDS it (internal/streamsup's
	// maxTurnEndStopField) and does NOT sanitize it — no control-character or
	// terminal-escape stripping happens on this path — so the render boundary
	// owing that sanitization is the CLIENT's, exactly as ModelOption's SECURITY
	// paragraph states for the strings beside it. Empty means claude sent none or
	// the value was past its bound; a client answers both the same way.
	Outcome string `json:"outcome"`
	// IsError is claude's own is_error flag for the turn. NOT derivable from
	// Outcome: claude sends subtype `success` with is_error true when the turn
	// ended on an API error, a context overflow being the documented case, so a
	// client inferring this from the subtype reads exactly that turn as clean.
	IsError bool `json:"is_error"`
	// TerminalReason is claude's finer-grained cause beside the subtype — the most
	// open of the three sets, nineteen values documented and explicitly not closed
	// (max_turns, budget_exhausted, prompt_too_long, hook_stopped, completed, …).
	// It is what makes a context overflow legible at all, since that turn's subtype
	// is plain `success`. Carries Outcome's SECURITY paragraph unchanged.
	TerminalReason string `json:"terminal_reason"`
	// ErrorCategory is the API error an `assistant` line in the turn reported at the
	// wrapper level (#2224): rate_limit, overloaded, account_on_hold,
	// authentication_failed, billing_error, invalid_request, model_not_found,
	// server_error, oauth_org_not_allowed, max_output_tokens, unknown — an OPEN set
	// on the three fields above's rule, empty when claude sent none or the value was
	// past its bound. It answers a question the other three cannot: WHY the API
	// stopped serving the turn, rather than how the turn ended.
	//
	// A DIFFERENT KIND OF CLAIM FROM ITS NEIGHBOURS, and a client that renders it
	// like them gets it wrong. Outcome and TerminalReason describe the TURN; half of
	// these values describe the ACCOUNT, and the daemon verifies none of them — it
	// carried a string off claude's stdout. Show it as claude's report, never as the
	// daemon's own finding about the operator's billing or credentials.
	//
	// SECURITY: claude-authored text, bounded by the daemon and NOT sanitized —
	// Outcome's SECURITY paragraph verbatim, including that the render boundary
	// owing the sanitization is the CLIENT's. It is spelled `error_category` rather
	// than `error` because a key of that name beside is_error reads as its detail,
	// and this is neither that nor an error object.
	ErrorCategory string `json:"error_category"`
	// DurationMS is how long THIS TURN took in milliseconds (#2260). PER TURN: it is
	// non-monotonic across the committed captures, falling as often as it rises.
	DurationMS int `json:"duration_ms"`
	// DurationAPIMS is claude's duration_api_ms in milliseconds, and it is a RUNNING
	// TOTAL for the session — NOT the API time inside this turn, which is the reading
	// its name invites and the one a client is most likely to get wrong. It is larger
	// than DurationMS on 53 of the 57 observed result lines, so reading it per turn
	// renders eleven seconds of API work for a three-second turn.
	//
	// Differencing consecutive frames does not recover a per-turn figure either: the
	// value already exceeds its own turn's DurationMS on the FIRST result line of 19
	// of the 21 multi-turn captures, so whatever it sums is not bounded by the turn's
	// wall clock. The daemon publishes what claude sent and differences nothing.
	DurationAPIMS int `json:"duration_api_ms"`
	// NumTurns is how many model round-trips THIS TURN made — per turn, on DurationMS's
	// side of the split, not a count of turns in the session. It holds constant across
	// consecutive frames of one session where a cumulative counter would climb.
	NumTurns int `json:"num_turns"`
	// CostUSDTotal is what the SESSION has cost so far in US dollars — a RUNNING TOTAL
	// with DurationAPIMS, and undifferenced for the same reason.
	//
	// The wire spells it `cost_usd_total` where claude spells it total_cost_usd. That
	// is deliberate and is the only respelling in this group; the other three keep
	// claude's own key.
	//
	// IT IS CLAUDE'S ESTIMATE, NOT A BILLING STATEMENT, and on a subscription it is
	// informational. See the four fields' shared rules below.
	CostUSDTotal float64 `json:"cost_usd_total"`
	// The four token counts are claude's per-turn usage readings, carried without
	// summing or conversion. InputTokens is uncached input only; CacheReadTokens
	// and CacheCreationTokens are input-side too, while OutputTokens is output-side.
	// InputTokens + OutputTokens is therefore not the turn total.
	//
	// The cache keys are deliberately shorter than claude's
	// cache_read_input_tokens and cache_creation_input_tokens. Plain values without
	// omitempty keep every key present; old, absent, null and unreadable readings are
	// all zero. The numbers are unverified claude output and drive no daemon action.
	InputTokens         int `json:"input_tokens"`
	OutputTokens        int `json:"output_tokens"`
	CacheReadTokens     int `json:"cache_read_tokens"`
	CacheCreationTokens int `json:"cache_creation_tokens"`
}

TurnEndPayload is the body of an Envelope whose Type == TypeTurnEnd (docs/protocol-mobile.md § turn_end). Binary → phone direction; marks the end of an assistant turn. StopReason carries the internal/turnevent.TurnEndReason string values verbatim ("end_turn", "max_tokens", "max_turn_requests", "refusal", "cancelled"); it stays a plain string because internal/protocol is a stdlib-only leaf data package and does NOT import internal/turnevent — #608 produces the field via string(turnevent.TurnEnd.Reason). The wire-value/taxonomy alignment is documented, not enforced by a shared type.

THREE FIELDS CARRY THE STOP SHAPE claude itself reported (#2223), beside StopReason rather than instead of it. StopReason's values and its derivation are unchanged and byte-identical for every subtype; the three below are what let a client tell a turn that hit --max-turns, exhausted a budget or overflowed its context apart from a finished answer, all of which used to arrive as a clean "end_turn".

TWO FIELDS ARE SPELLED LIKE A stop_reason AND NEITHER IS THE OTHER. StopReason is the daemon's two-value classification; Outcome is claude's own subtype token. claude's `result` line ALSO carries a key literally named stop_reason, and this daemon does not forward it under any name — a value seen on this wire is always one of the two fields declared here.

A FOURTH FIELD, ErrorCategory (#2224), rides beside them without joining them: it is read off an `assistant` line rather than the `result` line, and it names why the API stopped serving the turn rather than how the turn ended. It takes every wire rule the three below state — open set, no omitempty, claude-authored, bounded and unsanitized — and adds one they do not need, at its own declaration.

FOUR NUMBERS RIDE BESIDE THEM (#2260) and they are a different CLASS from every field above: claude-authored like the four strings, but numeric, so none of the string rules transfers. They are declared individually below and share the rules in the four paragraphs after this one.

TWO OF THE FOUR ARE RUNNING TOTALS AND TWO ARE PER TURN, and the pair that looks most alike is the pair that disagrees — DurationAPIMS is a session total while DurationMS is this turn's. The daemon differences neither and holds no previous line's value to difference one against.

A ZERO IS A NUMBER CLAUDE SENT, not a field the daemon failed to read, and a client that treats one as a gap mislabels a real turn. claude reports duration_api_ms 0 and num_turns 0 on an observed line whose duration_ms is 15617 and whose cost is non-zero. Absent, null, an unreadable value and an explicit 0 are one reading, and no field distinguishes them because nothing a client does depends on which it is.

NOTHING IS CLAMPED, RANGE-CHECKED OR ORDERED — RateLimitedPayload's posture for its own two numbers. In particular the daemon applies NO duration_api_ms <= duration_ms consistency check, because it would reject the ordinary case, and a negative arrives as claude sent it.

SECURITY: claude-authored, and threat 1 lands OUTWARD — but NOT in the shape Outcome's SECURITY paragraph states, so a client must not carry that paragraph across. A JSON number holds no control character, terminal escape, markup or URL, so there is no sanitization owed and no length bound to look for; these grow no frame because the bound is over the type's range rather than over claude's input length. What DOES land is the misattribution half: the daemon verifies none of these numbers, so rendering cost_usd_total as the daemon's own accounting of the operator's spend presents model-authored data as trusted chrome — error_category's trap reached through a number instead of a token. Attribute all four to claude. Nothing in the daemon acts on any of them, spend enforcement included.

No omitempty on any of them, per this file's rule as stated at ToolResultPayload: absence and the zero value mean the same thing, always emitting the key keeps the testdata fixture pinning the full shape, a client built before this landed ignores the unknown keys, and one built after decodes a frame lacking them to the zero value without error — which is the sense in which they are optional. It holds for the four numbers as written: a pointer would offer an absent-versus-zero distinction, and there is none to offer, since claude sends zeros itself.

type TurnStatePayload added in v0.15.0

type TurnStatePayload struct {
	ConversationID string `json:"conversation_id"`
	State          string `json:"state"`
}

TurnStatePayload is the body of an Envelope whose Type == TypeTurnState (docs/protocol-mobile.md § turn_state). Binary → phone direction; signals a coarse change in the turn's lifecycle. State is one of "thinking", "responding", "idle"; it stays a plain string (not a named enum), matching the MessagePayload.Role precedent. The exact internal event → state mapping is #608's.

type UnrecognizedMessagePayload added in v0.16.0

type UnrecognizedMessagePayload struct {
	ConversationID string `json:"conversation_id"`
	Site           string `json:"site"`
	MessageType    string `json:"message_type"`
	Raw            string `json:"raw"`
	Truncated      bool   `json:"truncated"`
}

UnrecognizedMessagePayload is the body of an Envelope whose Type == TypeUnrecognizedMessage (docs/protocol-mobile.md § unrecognized_message). Binary → phone direction; the wire form of the internal-only turnevent.Unrecognized diagnostic marker. Like turn_state it is a coarse conversation-level signal, not turn-scoped, so there is no turn_id — an unrecognized message has no turn we can honestly attribute it to.

Site is where the parser dropped the payload: "line_type", "assistant_block", "user_block" and "undecodable" from claude's stream-json, and "codex_method" and "codex_item" from codexsup's Codex translator. MessageType is the offending message or block `type` (the Codex method or item type on the Codex sites), empty when Site is "undecodable" (nothing decoded, so no type was read). Raw is the offending JSON, truncated by the producer to a fixed byte cap; Truncated says whether that happened.

SECURITY: Raw is the ONLY interactive payload field carrying unbounded model-adjacent JSON, so two properties are load-bearing. The producer truncates at construction to 16 KiB, so an oversized payload never reaches this struct; that is roughly a quarter of the v2 application-envelope cap of 65519 bytes (NOT v1's 1 MiB, which v2 superseded), leaving room for the other fields plus JSON escaping. And Raw is a plain string, not json.RawMessage, because a truncated blob is no longer valid JSON — typing it as raw JSON would be a lie and would break marshalling. A consumer must render it as inert text and never feed it to an HTML sink, an attribute, or a URL.

type Version added in v0.25.0

type Version struct {
	Major, Minor, Patch uint64
}

Version is a parsed MAJOR.MINOR.PATCH. Versions are ordered numerically, MAJOR first, and are only ever compared within one app name.

func ParseClientVersion added in v0.25.0

func ParseClientVersion(s string) (app string, v Version, ok bool)

ParseClientVersion parses a hello's client_version as <app>/<MAJOR>.<MINOR>.<PATCH> (docs/protocol-mobile.md § hello, v2-specific note). ok is false for anything else, including every pre-#2576 free-text form such as "1.0".

The input is remote-authored: the length is checked before anything is scanned, and the scan is a single pass over bytes with no regular expression.

func ParseVersion added in v0.25.0

func ParseVersion(s string) (Version, bool)

ParseVersion parses exactly three '.'-separated decimal integers: digits only, no leading zero except "0" itself, no prefix or suffix. A component that overflows uint64 is unparsable, as is anything over the client_version length cap.

func (Version) Compare added in v0.25.0

func (v Version) Compare(o Version) int

Compare returns -1, 0 or +1 as v is below, equal to or above o. The first differing component decides.

func (Version) String added in v0.25.0

func (v Version) String() string

String renders v as the three-part wire form, e.g. "1.4.0" — the shape ErrorPayload.MinClientVersion carries.

type WorkspaceFolderCreatedPayload added in v0.16.0

type WorkspaceFolderCreatedPayload struct {
	Path string `json:"path"`
}

WorkspaceFolderCreatedPayload is the body of a workspace_folder_created frame (docs/protocol-mobile.md § workspace_folder_created). Binary → phone, sent in reply to a create_workspace_folder (in_reply_to). Path is the canonical (symlink-resolved) absolute path of the created folder, confined to $HOME.

type WorkspaceUpdatedPayload added in v0.16.0

type WorkspaceUpdatedPayload struct {
	Path  string  `json:"path"`
	Label *string `json:"label"`
}

WorkspaceUpdatedPayload is the body of a workspace_updated frame (docs/protocol-mobile.md § Renaming a workspace). Binary → phone, sent in reply to a rename_workspace (in_reply_to) and pushed to that requester's peers with no correlation at all (see below). Path is the workspace's stored cwd and Label is the label now stored for it — null when cleared, which is why the field carries no omitempty (see RenameWorkspacePayload).

A separate type from RenameWorkspacePayload rather than a reuse of it, the same call CreateWorkspaceFolderPayload / WorkspaceFolderCreatedPayload made: the two are structurally identical today, and each stays free to change without dragging the other across the wire boundary.

It has TWO KINDS OF PRODUCER since #2209, the way TypeConversationUpdated does: the requester's correlated reply above, and an unsolicited push carrying no in_reply_to at all, fanned to every OTHER interactive conn so a name chosen on one machine shows on all of them. The record is the same either way — the push carries the value the reply carried — so a client that matches this type on correlation alone drops the pushed frame and should key on Path instead.

Jump to

Keyboard shortcuts

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