protocol

package
v0.37.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 5 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 (
	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 (
	// 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"

	// 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 (#2724)

	// Attachment errors (#1751; docs/protocol-mobile.md § Attachments). The
	// reject vocabulary both attachment_chunk legs answer with, declared in one
	// place so #1741, #1743, #1897 and #2054 do not each invent a name (#1744 and
	// #1746, the two this list named when it was written, were each split and no
	// longer exist as work). The reasoning is published in that section rather
	// than duplicated here.
	//
	// attachment.not_found is DELIBERATELY MERGED: it 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. Two distinguishable codes
	// would make the asking verb a path-existence oracle, so the merge is a
	// disclosure decision, not an imprecision.
	//
	// IT SPANS BOTH VERBS as of #2036, no longer retrieval alone: a send_message
	// naming an attachment id that does not resolve under the message's own
	// conversation is answered with this same code. The predicate is identical —
	// an id did not resolve to a file inside that conversation's directory — and
	// so are the retryability, the static message and the client's repair, so a
	// second code would carry nothing a client could act on differently. The
	// merge argument applies with MORE force there, since send_message is the
	// cheaper probe of the two.
	//
	// The message stays STATIC and, where a request names several ids, MUST NOT
	// name WHICH of them failed — a per-id answer turns one message into a batch
	// existence-probe for up to MaxAttachmentIDsPerMessage ids and rebuilds the
	// oracle this merge exists to prevent.
	//
	// The three retryable members (too_many_uploads, storage_failed,
	// stream_aborted) are published as retry-AFTER-A-BACKOFF: an immediate
	// resend turns each into a hot loop, and too_many_uploads' bound clears
	// only when OTHER uploads finish.
	CodeAttachmentInvalidChunk    = "attachment.invalid_chunk"
	CodeAttachmentIntegrityFailed = "attachment.integrity_failed"
	CodeAttachmentTooManyUploads  = "attachment.too_many_uploads" // transient; the bound 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 (#2116; docs/protocol-mobile.md
	// § Conversation history). MINTED WITH THE HANDLER THAT SENDS THEM, which is
	// the rule that section states in as many words — it published the reject
	// CONDITIONS ahead of any code and named this ticket the owner of the codes,
	// the sequencing attachment_chunk established. None of these existed while
	// request_history had no answer.
	//
	// A CONDITION THE SECTION LISTS IS ANSWERED BY AN EXISTING CODE, not by a
	// fifth new one: a conversation_id that is not of canonical shape or names no
	// conversation the daemon hosts is CodeConversationNotFound. That is the
	// OPPOSITE of the attachment retrieval verb's choice above, deliberately —
	// there, merging an unknown conversation into attachment.not_found prevents a
	// path-existence oracle over a SECOND id. There is no second id here, and
	// request_snapshot already answers an unknown or foreign conversation
	// distinguishably, so a merge would buy nothing and cost a client the ability
	// to tell "wrong conversation" from "wrong cursor".
	//
	// history.invalid_cursor IS DELIBERATELY MERGED, and it is the one merge on
	// this path: a cursor that does not decode, one minted for another
	// conversation, and one naming a position not in this log are ONE answer.
	// Those distinctions are exactly what a probe would want, and internally they
	// arrive as the single history.ErrInvalidCursor sentinel, so the handler
	// CANNOT branch on what it must not distinguish. The refusal never echoes the
	// cursor back.
	//
	// RETRYABILITY SPLITS THE SET THREE-TO-ONE, and it is the field a client
	// actually branches on. The three client faults are permanent for the request
	// as sent — a different request repairs each — while history.unavailable is
	// the only one whose cause can clear without the client changing anything.
	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 (#2780; docs/protocol-mobile.md § Error codes), minted
	// with the mark_conversation_read handler that sends it. 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 (#2125; docs/protocol-mobile.md § Error codes).
	// MINTED WITH THE HANDLER THAT SENDS IT, the sequencing #2052 established and
	// the history group above followed: no reject vocabulary exists ahead of the
	// code that can emit it.
	//
	// ONE NEW CODE, NOT TWO. The other condition request_model_list can refuse —
	// the daemon does not host the named conversation — is answered by the EXISTING
	// CodeConversationNotFound, for the history group's stated reason: there is no
	// second id here to build a path-existence oracle over, and request_snapshot and
	// request_history already answer an unknown conversation distinguishably, so a
	// merge would buy nothing and cost a client the ability to tell "wrong
	// conversation" from "no menu yet". KnownConversation is what separates the two
	// arms.
	//
	// IT MERGES TWO CAUSES DELIBERATELY: nothing retained anywhere (no bootstrap in
	// the pool, a bootstrap constructed evicted, or its initialize reply not yet
	// arrived) and no daemon-side source wired at all. Both mean the same thing to a
	// client — the daemon hosts this conversation and has no menu to give you — and
	// the repair is identical. Distinguishing them would publish whether the host's
	// model-list source is configured, which is a fact about the machine rather than
	// about the request.
	//
	// RETRYABLE, and the retryability follows the dominant cause rather than the
	// merged one: a child that has not yet answered its initialize ask will, and the
	// caller changes nothing to make that happen.
	//
	// IT IS NOT AN EMPTY MENU. turnevent.ModelList.Models is documented never-empty,
	// so an empty models array must NEVER stand in for "unknown" — this code is the
	// only way to say "no list", alongside the absence of a frame on the
	// unsolicited paths.
	CodeModelListUnavailable = "model_list.unavailable" // the daemon hosts the conversation but has no vocabulary to answer with; retryable

	// MCP status error (#2381; docs/protocol-mobile.md § Error codes). A hosted
	// conversation can be temporarily unable to report a current status: its
	// resolver has no live result yet. The request handler emits this code only
	// after membership succeeds, and never substitutes an empty or retained status.
	CodeMCPStatusUnavailable = "mcp_status.unavailable" // hosted conversation has no current MCP status; retryable

	// MCP actuation error (#2419; docs/protocol-mobile.md § Error codes). THE ONE
	// ANSWER TO EVERY REFUSAL of an mcp_reconnect or an mcp_toggle: an unauthorized
	// device, an unknown server, no live child and a child that declined alike. The
	// merge is the contract rather than a simplification left to tidy up later —
	// separating "not permitted" from "no such server" would make the verb an oracle
	// for which MCP servers the host runs, and separating either from "actuation
	// failed" would tell a device whether it is privileged. Both are facts about the
	// daemon and about the asker that the request must not be able to learn; the
	// daemon-side audit record is where the reasons stay apart.
	//
	// NON-RETRYABLE ON EVERY ARM, and that is load-bearing rather than incidental: a
	// retryable refusal would read as "transient, so not the gate", re-splitting on
	// the flag exactly what the single code merged. Distinct from
	// CodeMCPStatusUnavailable above, which is the retryable read-path answer.
	//
	// It carries no server name and no claude-authored text; the message is a
	// compile-time constant in internal/relay.
	CodeMCPActuationRefused = "mcp_actuation.refused" // reconnect or toggle refused, reason deliberately merged; never retryable

	// Context-usage read error (#2431; docs/protocol-mobile.md § Error codes).
	// MINTED WITH THE HANDLER THAT SENDS IT, the sequencing #2052, the history
	// group and #2125 each followed: no reject vocabulary exists ahead of the code
	// that can emit it.
	//
	// ONE NEW CODE, NOT TWO, for the reason CodeModelListUnavailable's block above
	// gives in full: the other condition request_context_usage can refuse — the
	// daemon does not host the named conversation — is answered by the EXISTING
	// CodeConversationNotFound, and KnownConversation is what separates the two
	// arms. There is no second id here to build a path-existence oracle over.
	//
	// IT MERGES EVERY "HOSTED BUT NO READING" CAUSE, and the merge is inherited
	// rather than chosen: streamsup's QueryContextUsage collapses no bound session,
	// no live child, a rotation in flight, a child replaced before answering, a
	// failed write, an expired deadline and an unusable payload into ONE bool, so a
	// richer wire vocabulary here would have nothing to source itself from. An
	// unwired daemon-side seam merges in too, deliberately: distinguishing it would
	// publish whether the host's context-usage source is configured, which is a fact
	// about the machine rather than about the request.
	//
	// RETRYABLE, following the dominant cause rather than the merged one: a busy or
	// rotating child will answer later and the caller changes nothing to make that
	// happen. Note that the daemon-side resolver caches a refusal for its collapsing
	// window, so a retry inside that window is answered from the same refusal — the
	// window is short precisely so this stays a pacing detail rather than a lie.
	//
	// IT IS NOT A ZERO-VALUED READING. A ContextUsagePayload of all zeros is a
	// SHAPE a client cannot distinguish from a genuine empty context, so it must
	// NEVER stand in for "unknown" — this code is the only way to say "no reading",
	// alongside the absence of a frame on the unsolicited post-turn lane.
	CodeContextUsageUnavailable = "context_usage.unavailable" // the daemon hosts the conversation but has no reading to give; retryable

	// Workspace error (#2207; docs/protocol-mobile.md § Error codes). MINTED WITH
	// THE HANDLER THAT SENDS IT, the sequencing #2052, the history group and #2125
	// each followed: no reject vocabulary exists ahead of the code that can emit it.
	//
	// NOT CodeConversationNotFound, and the distinction is the point rather than a
	// naming preference. A rename_workspace names no conversation at all — its key
	// is a workspace path, and N conversations may share one. Answering with the
	// conversation code would send a client looking for a row it never asked about
	// and could not act on.
	//
	// IT IS THE MAP'S ONLY CEILING, which is why it is a containment property and
	// not merely a UX nicety. A workspace_labels key is creatable only at a path
	// that byte-equals a stored conversation's cwd, so the key count is bounded by
	// the number of distinct cwds the daemon actually hosts. Relaxing this refusal
	// would remove that bound.
	//
	// NON-RETRYABLE: the same path fails identically until a conversation exists
	// there, which is not something a retry accomplishes. The message is static and
	// never echoes the requested path.
	CodeWorkspaceNotFound = "workspace.not_found"

	// Pairing-mint errors (#2127; docs/protocol-mobile.md § Error codes). MINTED
	// WITH THE HANDLER THAT SENDS THEM, the sequencing #2052, the history group,
	// #2125 and #2207 each followed: no reject vocabulary exists ahead of the code
	// that can emit it.
	//
	// NEITHER IS CodeAuthInvalidToken, and that is the group's defining decision
	// rather than a naming preference. A mint_pairing reaching a handler at all has
	// already presented a token the handshake validated, so answering an auth code
	// would tell a legitimate client its credential was rejected and invite it to
	// re-pair — the one repair that cannot help. The device is authenticated; what
	// it lacks is privilege.
	//
	// NEITHER IS AN ORACLE, which is the property the wire contract asks this group
	// for. pairing.not_permitted reports only that the asking device lacks the
	// remote-permissions flag — a fact it can already establish by answering any
	// permission modal and being denied — and NOTHING about the host, the registry,
	// or any other device. It is not conditioned on the requested device_name, so it
	// cannot be used to probe which labels exist.
	//
	// pairing.unavailable MERGES EVERY HOST-SIDE FAILURE deliberately: a busy
	// devices.json lock, a registry read or write error, and an RNG failure arrive
	// as one answer. Each can clear without the client changing anything, the repair
	// is identical for all three, and distinguishing them would publish facts about
	// the machine rather than about the request. The errors behind them format an
	// absolute host path and never reach the wire at all.
	//
	// A MALFORMED REQUEST IS NOT IN THIS GROUP. An undecodable payload — including
	// a device_name over MaxDeviceNameBytes, which MintPairingPayload.UnmarshalJSON
	// refuses — is answered with the existing CodeProtocolMalformed, the answer that
	// type's own doc block assigns. A third code for it would be a second spelling
	// of a decision already made.
	//
	// RETRYABILITY SPLITS THE PAIR ONE-TO-ONE: the privilege refusal is permanent
	// for the device as paired (only a shell on the host can change it), and the
	// host-side failure is the transient one.
	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 (#2443; docs/protocol-mobile.md § Error codes).
	// MINTED WITH THE HANDLER THAT SENDS IT, the sequencing #2052, the history
	// group, #2125, #2207 and #2419 each followed: no reject vocabulary exists
	// ahead of the code that can emit it.
	//
	// IT REPORTS A ROTATION THAT SUCCEEDED, which is what makes it unlike every
	// other code in this file. new_session rotated the conversation and the
	// successor child came up; what did not happen is the MOVE into the
	// conversation's recorded workspace, because re-confining that stored path at
	// spawn time refused it — the folder was deleted, or re-pointed outside $HOME,
	// since change_workspace stored it (#1475 wired the move; this code reports its
	// one caveat). An error frame is the carrier because the client needs the
	// refusal CORRELATED to the frame it sent, and a conversation record carries no
	// in_reply_to.
	//
	// IT IS NOT AN ORACLE, and the derivation matters because this verb is silent in
	// every other outcome. The frame fires only after a rotation that actually
	// happened, whose session_transition the client already receives carrying the
	// rotated conversation's id; the conversation's recorded cwd is already
	// published in ConversationSummary; and change_workspace already answers "is
	// this path acceptable?" directly for any path a client names. A client could
	// already derive this refusal from frames it is entitled to send, so what this
	// adds is one round trip of convenience rather than a fact. Every INERT arm
	// stays silent — an unknown conversation, an unbound one, a non-canonical id, a
	// conversation with no live child, a non-interactive conn — so the verb still
	// cannot answer "does this conversation exist?".
	//
	// NON-RETRYABLE: the same stored workspace fails identically until the operator
	// repairs the folder or re-points it with change_workspace, which is not
	// something a retry accomplishes — CodeWorkspaceNotFound's reasoning, unchanged.
	//
	// IT CARRIES THE CONVERSATION ID and no fragment of the operator's filesystem
	// path. The id is needed because a bare new_session names no conversation and
	// rotates the daemon's cursor one, so in_reply_to alone cannot identify the
	// subject; it travels in ErrorPayload.ConversationID, whose own doc carries the
	// never-echo obligation. The message is a compile-time constant in
	// internal/relay and the confinement error's text reaches neither it nor a log.
	CodeNewSessionWorkspaceRefused = "new_session.workspace_refused" // the rotation completed; the recorded workspace was refused, so the successor stayed put

	// Client errors (#2576; docs/protocol-mobile.md § Compatibility). The
	// app-too-old rejection: the hello's client_version names an app build older
	// than the minimum this host holds for that app, or — once any minimum is
	// set — cannot be parsed at all. RESERVED AHEAD OF ITS SENDER, deliberately
	// unlike the MINTED-WITH-THE-HANDLER groups above: the compatibility policy
	// has to be published before the app releases that obey it, and nothing
	// enforces it until a later ticket adds the minimum.
	//
	// A NEW CATEGORY, not protocol.unsupported (which is about protocol
	// versions) and not auth (the device is authenticated): the fault is the
	// client build. It is sent sealed, after the Noise handshake and AFTER the
	// token check, so an unauthenticated peer learns nothing about the host's
	// version policy; the relay's StatusClientUpdateRequired close follows it.
	//
	// NON-RETRYABLE: the same build fails identically, and only an app update
	// repairs it. Terminal for THIS host only — a client keeps its other hosts.
	// 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-code constants — wire values for the "code" field of error payloads (docs/protocol-mobile.md § Error codes). The naming convention is Code<Category><Reason>, matching the dotted-string structure category.reason. Grouped by category in spec-table order.

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 dispatch.Route write verb
	// (like create_conversation / promote_conversation): it renames an
	// existing conversation and replies with the reused conversation_updated
	// record. It is a inboundAppTypeSet member, not a v2 control frame — see the
	// v1/v2 partition in envelope.go / compat_test.go.
	TypeRenameConversation = "rename_conversation"
	// TypeDeleteConversation is a phone → binary dispatch.Route write verb
	// (like rename_conversation / create_conversation): it PERMANENTLY removes
	// an existing conversation from the registry (hard delete — the reversible
	// path is archive/unarchive) and replies with a conversation_deleted
	// acknowledgement. It is a inboundAppTypeSet member, not a v2 control frame — see
	// the v1/v2 partition in envelope.go / compat_test.go.
	TypeDeleteConversation = "delete_conversation"
	// TypeConversationDeleted is the binary → phone acknowledgement replied to
	// a delete_conversation, correlated via in_reply_to. Unlike
	// conversation_updated it carries only the deleted conversation's id — the
	// record no longer exists, so no name/cwd/last_used_at can be projected.
	// Also a inboundAppTypeSet member.
	TypeConversationDeleted = "conversation_deleted"
	// TypeArchiveConversation is a phone → binary dispatch.Route write verb
	// (like rename_conversation / delete_conversation): it sets an existing
	// conversation's durable archived flag (IsArchived = true) and replies with
	// the reused conversation_updated record reflecting the new state. It is a
	// inboundAppTypeSet member, not a v2 control frame — see the v1/v2 partition in
	// envelope.go / compat_test.go. Its symmetric restore is
	// unarchive_conversation; both carry the shared ArchiveConversationPayload.
	TypeArchiveConversation = "archive_conversation"
	// TypeUnarchiveConversation is the symmetric restore of
	// archive_conversation: a phone → binary dispatch.Route write verb that
	// clears the durable archived flag (IsArchived = false) and replies with the
	// reused conversation_updated record reflecting the restored (active) state.
	// It is a inboundAppTypeSet member, not a v2 control frame — see the v1/v2 partition
	// in envelope.go / compat_test.go.
	TypeUnarchiveConversation = "unarchive_conversation"
	// TypeSetConversationMuted is a phone → binary dispatch.Route write verb
	// (#2572) that sets or clears an existing conversation's durable muted flag
	// (IsMuted) from the payload's required muted bool, and replies with the
	// reused conversation_updated record. Unlike archive, the same record is also
	// pushed to every interactive conn, so other clients stop alerting without
	// re-listing. It is a inboundAppTypeSet member, not a v2 control frame — see
	// the v1/v2 partition in envelope.go / compat_test.go.
	TypeSetConversationMuted = "set_conversation_muted"
	// TypeMarkConversationRead is a phone → binary dispatch.Route write verb
	// (#2780) that raises an existing 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 the
	// reused conversation_updated record; only an actual advance also pushes it
	// to every interactive conn. It is a inboundAppTypeSet member, not a v2
	// control frame — see the v1/v2 partition in envelope.go / compat_test.go.
	TypeMarkConversationRead = "mark_conversation_read"
	// TypeChangeWorkspace is a phone → binary dispatch.Route write verb (like
	// rename_conversation / delete_conversation): it moves an existing
	// conversation to a client-chosen workspace folder by updating its recorded
	// workspace (its Cwd) to a target filesystem path — confined to $HOME before
	// it is stored — and replies with the reused conversation_updated record
	// reflecting the new workspace. "Workspace" IS the conversation's Cwd (this
	// codebase has no separate workspace-id concept). It is a inboundAppTypeSet member,
	// not a v2 control frame — see the v1/v2 partition in envelope.go /
	// compat_test.go ("v2 wire message" in the ticket title names the encrypted
	// v2 transport, not the v1/v2 type partition). The reply reuses
	// conversation_updated / ConversationUpdatedPayload (only cwd changed), so
	// there is no new reply type.
	TypeChangeWorkspace = "change_workspace"
	// TypeSetSystemPrompt is a phone → binary dispatch.Route write verb (like
	// rename_conversation / change_workspace): it sets or clears a conversation's
	// durable per-conversation system prompt — the operator-authored text #2150
	// appends to every session that conversation spawns. Keyed by conversation,
	// NOT by session (contrast set_session_settings): the prompt must be settable
	// with no session live and must outlive every session the conversation has.
	// The payload's system_prompt is nullable so "clear" is expressible distinctly
	// from "set it to the empty string"; the byte bound and the UTF-8 check live at
	// the registry door (conversations.MaxSystemPromptBytes), not here. It is a
	// inboundAppTypeSet member, not a v2 control frame — see the v1/v2 partition in
	// envelope.go / compat_test.go. The reply reuses conversation_updated /
	// ConversationUpdatedPayload, so there is no new reply type — and that record
	// deliberately carries NO prompt field, so the ack confirms the write without
	// echoing up to 8192 bytes of operator text to a frame documented as broadcast
	// to every phone on this server-id. The new value takes effect at the
	// conversation's next session start, not on a running child.
	TypeSetSystemPrompt = "set_system_prompt"

	// Daemon-wide host prompt family. 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. The client → daemon read verb is
	// map-dispatched; the daemon → client reply is outbound only. See the
	// consumer contract in claude_account.go; the handler is pending #2839.
	TypeRequestClaudeAccount = "request_claude_account"
	TypeClaudeAccount        = "claude_account"

	// Workspace.
	// TypeCreateWorkspaceFolder is a phone → binary dispatch.Route write verb
	// (like create_conversation / change_workspace): it creates a new folder on
	// the daemon host under a client-supplied parent path, confined to $HOME, and
	// replies with the new workspace_folder_created record carrying the created
	// folder's canonical absolute path. It touches NO conversations registry — it
	// only creates a directory. It is a inboundAppTypeSet member, not a v2 control frame —
	// see the v1/v2 partition in envelope.go / compat_test.go ("v2 wire message"
	// in the ticket title names the encrypted v2 transport, not the v1/v2 type
	// partition). Unlike change_workspace (which reuses conversation_updated) the
	// reply is a NEW type, TypeWorkspaceFolderCreated.
	TypeCreateWorkspaceFolder = "create_workspace_folder"
	// TypeWorkspaceFolderCreated is the binary → phone reply to a
	// create_workspace_folder, correlated via in_reply_to. It carries the
	// canonical (symlink-resolved) absolute path of the created folder — no
	// conversation is involved, so no conversation record is projected. Also a
	// inboundAppTypeSet member.
	TypeWorkspaceFolderCreated = "workspace_folder_created"
	// TypeRecentWorkspaces is a phone → binary dispatch.Route read verb (like
	// list_conversations): it asks for the distinct set of recently-used
	// workspace folders and replies with a recent_workspaces_list record. The
	// list is derived entirely from Cwd values the daemon already owns in the
	// conversations registry — no untrusted input drives a filesystem operation,
	// so it is NOT security-sensitive (contrast create_workspace_folder, which
	// writes to disk from untrusted input). It is a inboundAppTypeSet member, not a v2
	// control frame — see the v1/v2 partition in envelope.go / compat_test.go
	// ("v2 wire message" in the ticket title names the encrypted v2 transport,
	// not the v1/v2 type partition). Its request payload is empty by spec.
	TypeRecentWorkspaces = "recent_workspaces"
	// TypeRecentWorkspacesList is the binary → phone reply to a
	// recent_workspaces, correlated via in_reply_to. It carries the distinct
	// workspace paths ordered most-recent-first, each with its most-recent
	// last_used_at. Also a inboundAppTypeSet member.
	TypeRecentWorkspacesList = "recent_workspaces_list"
	// TypeRenameWorkspace is a phone → binary dispatch.Route write verb (like
	// rename_conversation / set_system_prompt): it sets or clears the
	// operator-chosen display name of a workspace, so a folder whose name is
	// unhelpful reads the way the operator thinks of it. The payload's label is
	// nullable so "clear" is expressible distinctly from "set it to the empty
	// string"; the non-blank check and the MaxWorkspaceLabelBytes bound live in the
	// handler, because conversations.Registry.SetWorkspaceLabel is documented as
	// validating nothing. It is a inboundAppTypeSet member, not a v2 control frame —
	// see the v1/v2 partition in envelope.go / compat_test.go.
	//
	// KEYED BY WORKSPACE, NOT BY CONVERSATION, and that is why its reply is a new
	// type rather than the reused conversation_updated record change_workspace
	// answers with: N conversations share one cwd, a workspace has no row of its
	// own, and no conversation record could carry the change without naming one
	// arbitrary member of that set.
	TypeRenameWorkspace = "rename_workspace"
	// TypeWorkspaceUpdated is the binary → phone reply to a rename_workspace,
	// correlated via in_reply_to. It carries the workspace's path and its stored
	// label (null when cleared). Also a inboundAppTypeSet member.
	//
	// A NEW TYPE RATHER THAN A NEW ARM ON AN EXISTING ONE, deliberately, for
	// compatibility: an un-upgraded client drops an unknown frame type, whereas a
	// new field or a new meaning on a type it already handles would be rendered
	// wrongly rather than ignored.
	TypeWorkspaceUpdated = "workspace_updated"

	// Push.
	TypeRegisterPushToken = "register_push_token"
)

Envelope-type constants — wire values for Envelope.Type (docs/protocol-mobile.md § Message types). The set is closed in v1; new types require a v2 envelope per the protocol's versioning policy.

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

Mobile Protocol v2 interactive application-event types. These are additive, capability-gated events the binary pushes to a phone that has advertised the "interactive" capability (docs/protocol-mobile.md § Interactive events). Unlike TypeRekeyRequest (a v2 control envelope intercepted before dispatch.Route), these are outbound binary → phone application events that are never dispatched inbound — but for the v1/v2 partition's purpose they are equally "v2-only".

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: an old phone receives the coarse v1 "message" fan-out, not these. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these six live in the latter.

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

Mobile Protocol v2 PTY-derived status peers of TypeStall. Like stall, these are additive, capability-gated status frames the binary pushes to a phone that advertised the "interactive" capability — they surface claude's API-error retry and auto-compaction sub-states (docs/protocol-mobile.md § api_retry / § compacting). They are outbound binary → phone status events, never a turn-lifecycle event and never dispatched inbound.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: an old phone never receives them. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these two live in the latter.

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 types. These are the frames in the vocabulary whose subject is work that OUTLIVES the turn that started it — claude backgrounds a shell command and it keeps running after the assistant reports end_turn. That gap is #1240's symptom exactly: the daemon reported turn_end carrying end_turn and went idle while a command claude started was provably still alive, and nothing reaching a phone separated that from a genuine finish.

Grouped alone rather than with api_retry/compacting or with the turn-lifecycle six: those describe a live turn's sub-states and its lifecycle, and neither cluster's subject is turn-independent work.

AMENDED 2026-09-10 (#2246): the block admits a periodic READING beside three lifecycle frames, and the two sentences above are edited rather than annotated because both were counts of a set that grew. background_task_progress reports that a running task is still working and what it is doing, so it has no edges at all — but this block's criterion is the frame's SUBJECT, turn-independent work, not its shape, which is why it lands here and not beside thinking_progress. That constant is grouped alone for the reason its own doc gives: its subject is neither the turn's lifecycle nor turn-independent work.

The NAMES are the daemon's, not claude's. internal/streamsup/parser.go translates claude's system/task_started, system/task_updated, system/background_tasks_changed and system/task_progress subtypes into internal/turnevent variants — the authority on that set being streamsup.emitSystemSubtype's case arms rather than this list, which is a reading aid and fails no build when it goes stale — and the wire follows the VARIANTS. The daemon is the single place a claude rename lands; if every client read claude's vocabulary directly, one claude release could break all of them at once with nothing in between to absorb it. In particular background_task_roster is named for what the frame IS (a snapshot) rather than for claude's trigger (…_changed), which would invite a consumer to read it as a delta and infer a finish the daemon has never observed.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: these are outbound binary → phone events an old phone never receives. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these all live in the latter.

The declaring ticket (#1393) was wire vocabulary only; #1394 added internal/turnbridge's MapEvent cases for the first three variants and the docs/protocol-mobile.md section, so those frames reach an interactive v2 mobile client. #2246 added the fourth end to end in one change.

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 — #2381)
	TypeMCPReconnect     = "mcp_reconnect"      // phone → binary, inbound v2 control (switch-intercepted — #2419)
	TypeMCPToggle        = "mcp_toggle"         // phone → binary, inbound v2 control (switch-intercepted — #2419)
)

Mobile Protocol v2 MCP server-status report, its request, and the two actuation verbs. TypeMCPStatus is the single binary → phone envelope carrying the conversation-scoped MCP inventory for live publication and for every correlated reply. TypeMCPStatusRequest is the phone → binary read request, and TypeMCPReconnect / TypeMCPToggle are the phone → binary write verbs (#2419). All three inbound types are intercepted by the v2 session manager before dispatch.Route.

THE TWO ACTUATORS TAKE BARE VERB NAMES while the read verb carries a suffix, and the asymmetry is deliberate. mcp_status_request is spelled that way only because its answer reuses the mcp_status type name and the two would otherwise collide; the actuators have no such collision, so they take the names the claude child's own control protocol already uses (see WriteMCPReconnect / WriteMCPToggle in internal/streamsup). Neither actuator has an ack type: an accepted actuation is answered with a fresh TypeMCPStatus correlated by the request envelope's id.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go. All four are v2-only, and an old v1 client must reject every one of them. The v2OnlyTypes partition classifies all four; the relay guard records the three inbound types as switch-intercepted and TypeMCPStatus as output used by pushes and replies.

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 types. The always-available, parser-independent screen snapshot is the floor of ADR 025's safe-degradation strategy (docs/protocol-mobile.md § Screen snapshot): the phone asks for a one-shot text picture of the current screen, the binary renders it and pushes it back. The pair groups here so a reader greps "snapshot" and finds both adjacent with their rationale.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go. Like TypeRekeyRequest, TypeRequestSnapshot is an inbound v2 control envelope the v2 session manager intercepts before dispatch.Route; a leak into inboundAppTypeSet would route it to the handler chain. TypeScreenSnapshot is an outbound binary → phone event an old phone must never receive. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these two live in the latter.

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 vocabulary (epic #597 Phase 3, docs/protocol-mobile.md § Modal). When the supervised claude surfaces a modal (a permission prompt, a plan-approval, a tool-confirmation), the daemon describes it to the phone, the phone answers, and the daemon drives that answer back into claude. modal_shown rides the existing "interactive" capability (#607) negotiated in hello/hello_ack — viewing a modal is ungated; answering is gated separately, per-device, default OFF, in the security model (#702), which is NOT a wire capability.

Two natures in one cluster. modal_shown / modal_dismissed are outbound binary → phone events an old phone must never receive. modal_answer / modal_cancel are inbound phone → binary *control* envelopes the v2 session manager intercepts at internal/relay/v2session.go's dispatchAppFrame before internal/dispatch.Route (like TypeRekeyRequest / TypeRequestSnapshot); there is NO dispatch.Route handler for them.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a leak would either route an inbound control envelope to the handler chain or offer an outbound modal event to an old phone, violating the v1/v2 boundary. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these four live in the latter.

This ticket (#701) is wire vocabulary only — the producer that mints modal_id nonces, dedups answers by answer_token, validates inbound answers, and gates the fan-out is sibling #703 (with #706 building two-heads ownership and #702 the per-device answer gate).

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 vocabulary (epic #597 Phase 3, docs/protocol-mobile.md § Queue). A phone that types while claude is busy has its turn buffered in internal/msgqueue; queue_state (daemon → phone) is the wire form of msgqueue.Snapshot(convID) so the phone can see the backlog, and dequeue_message (phone → daemon) drives msgqueue.Remove(convID, id) so the phone can cancel an entry it no longer wants.

Two natures in one cluster. queue_state is an outbound binary → phone event an old phone must never receive. dequeue_message is an inbound phone → binary *control* envelope the v2 session manager intercepts at internal/relay/v2session.go's dispatchAppFrame before internal/dispatch.Route (like TypeModalAnswer / TypeRequestSnapshot); there is NO dispatch.Route handler for it.

Trust contrast with the modal cluster: unlike modal_answer, dequeuing is ungated for any paired phone (ADR 025 § Security model) — viewing and dequeuing are an ordinary capability, with no nonce and no per-device gate. queued_msg_id is a plain per-conversation counter from internal/msgqueue, not a security primitive.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a leak would either route the inbound control envelope to the handler chain or offer the outbound queue_state event to an old phone, violating the v1/v2 boundary. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these two live in the latter.

This ticket (#720) is wire vocabulary only — the producer that emits queue_state is sibling #722 and the handler that applies dequeue_message is sibling #723.

send_queued_now (#2729) is dequeue_message's sibling with the opposite effect: it drives msgqueue.SendNow(convID, id), writing the named entry into the running claude turn instead of dropping it. Same nature, same trust posture, same fields.

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 streaming vocabulary (#812, split from #803; docs/protocol-mobile.md § Debug bundle). A content-bearing debug bundle (assembled by #811) routinely exceeds one AEAD frame, so the daemon streams it to a paired phone as ordered, cap-respecting chunks ending in a completion marker. debug_bundle_chunk carries one base64 slice of the bundle with a 0-based contiguous seq; debug_bundle_done carries the exact chunk count so the phone detects a truncated stream. Both ride the manager's asynchronous push path (StreamBundle → Push → drainOnce), never the synchronous handler-reply channel.

Both are outbound binary → phone v2 events an old phone must never receive. MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a leak would offer the outbound event to an old phone, violating the v1/v2 boundary. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these two live in the latter.

This ticket (#812) delivers the streaming primitive unwired; the request verb that drives it for the debug bundle is sibling #813.

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 set-session-settings vocabulary (#844, split from #841; docs/protocol-mobile.md § Session settings). A paired client sends set_session_settings to change one session's per-session model / reasoning effort / YOLO (bypass-permissions); the daemon confirms with session_settings_updated. The request payload (SetSessionSettingsPayload, settings.go) uses per-field pointers so an omitted setting decodes distinctly from one explicitly set to its zero value — nil means "leave unchanged".

This ticket (#844) is wire vocabulary ONLY — these two Type* constants, the two payload structs, and CodeSessionNotFound. The handler that intercepts the request, gates on the interactive capability, validates, persists via sessions.Pool.UpdateSettings (#840), and emits the reply is sibling #845. Splitting vocabulary from handler follows the established v2 precedent (#701→#703, #720→#723, #812→#813, #656→#657).

Two natures in one cluster. set_session_settings is an inbound phone → binary *control* envelope the v2 session manager intercepts at internal/relay/v2session.go's dispatchAppFrame before internal/dispatch.Route (like TypeModalAnswer / TypeNewSession); there is NO dispatch.Route handler for it. session_settings_updated is an outbound binary → phone reply an old phone must never receive.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a leak would either route the inbound control envelope to the handler chain or offer the outbound reply to an old phone, violating the v1/v2 boundary. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these two live in the latter.

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 read-session-settings vocabulary (#491/#1214; docs/protocol-mobile.md § Session settings). The READ half of the #844 cluster above, which shipped write-only: set_session_settings changes the values and session_settings_updated only echoes the id back, so a client had no way to ASK what the current values are, nor to learn the session id it must address a change to.

Until now a client got both by reading screen_snapshot, which carries them as a side-load (#848, #857). That coupling is the bug: screen_snapshot is a photograph of the terminal, and on the stream-json runner there is no terminal to photograph, so handleRequestSnapshot answers CodeServerBinaryOffline (#1101) and the settings — which have nothing to do with a terminal — are refused with it. This pair carries them on their own route, gated on their own seams, so it answers on BOTH runners. screen_snapshot is deliberately left untouched: its side-loaded copies stay for the shipped mobile client.

The request frame carries a RequestSessionSettingsPayload naming the conversation the client is asking about (#1586). It WAS bare until then — like TypeRequestDebugBundle, which stays bare because its bundle is daemon-global and has no per-session key to name — but this reply is what hands a client the session_id every subsequent set_session_settings must address, so a client needed a way to say which conversation it meant. conversation_id is untrusted network input used for exactly one thing: an in-memory resolution through handleRequestSessionSettings' conversation-keyed run-configuration seam. It reaches no log line, no error string, no filesystem path, and not the reply.

Since #1610 it SELECTS which session the reply describes, and the reported id and the reported values move in one step because they are resolved as one value. Every unresolvable case — a conversation the daemon does not host, one bound to no live session, and an absent or empty id — is answered with a zero-valued session_settings rather than an error, and never with the shared bootstrap session's id or values.

Two natures in one cluster, mirroring #844. request_session_settings is an inbound phone → binary *control* envelope the v2 session manager intercepts at internal/relay/v2session.go's dispatchAppFrame before internal/dispatch.Route (like TypeSetSessionSettings / TypeRequestSnapshot); there is NO dispatch.Route handler for it. session_settings is an outbound binary → phone reply an old phone must never receive.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a leak would either route the inbound control envelope to the handler chain or offer the outbound reply to an old phone, violating the v1/v2 boundary. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these two live in the latter.

View Source
const (
	TypeRequestSystemPrompt = "request_system_prompt" // phone → binary, inbound v2 control (switch-intercepted — #2152)
	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 PAIR (#2152, split from #2094; docs/protocol-mobile.md § Reading a conversation's system prompt publishes both). The frame a client sends to ask what system prompt one conversation holds, and the frame it is answered with. Their payloads are RequestSystemPromptPayload and SystemPromptPayload (system_prompt.go).

THE DEFECT IT CLOSES is the read half TypeSetSystemPrompt (#2151) shipped without. That verb's ack is the reused TypeConversationUpdated record, which deliberately does NOT carry the value — it is broadcast to every phone on the server-id, so carrying it there would widen the audience for a value only the requester asked about — so a client that did not itself perform the write has no way to learn what is stored. And because a stored prompt takes effect at the conversation's NEXT session start, a client showing the stored value alone tells an operator their edit is live when it is not.

SO THE REPLY REPORTS A DIFFERENCE, NOT A SECOND COPY OF THE TEXT. The daemon knows what the live session was spawned with (#2150's session-keyed Pool.SystemPromptFor); the client's need is to be told the two disagree, so SystemPromptPayload carries a three-value verdict rather than echoing up to another 8192 bytes of operator text back over the wire. A client that wants to show a diff is a later ticket.

A READ ROUTE, NOT A FIELD ON AN EXISTING REPLY, and both alternatives were rejected for a stated reason. It does not go on the TypeConversations record: a prompt is capped at conversations.MaxSystemPromptBytes (8192) and that reply carries EVERY row, so a handful of prompted conversations would blow the 65519-byte application-envelope cap. It does not go on SessionSettingsPayload either: that payload's contract is that every field sits at its zero when no session resolves, which is exactly when an operator most needs to see what is stored.

THE NAME follows the six inbound "ask the daemon for X" verbs already here — TypeRequestSnapshot, TypeRequestDebugBundle, TypeRequestSessionSettings, TypeRequestAttachment, TypeRequestHistory, TypeRequestModelList — rather than inventing a seventh idiom for the same act. #2052's rule applies: a wire type string IS the contract, and a name chosen twice is a name chosen wrong once.

UNLIKE ITS NEAREST FILE-SPREAD PRECEDENT IT MINTS NO ERROR CODE AND HAS NO ERROR FRAME. TypeRequestModelList needs two codes because turnevent.ModelList's Models is documented never-empty, so an empty menu cannot stand in for "unknown". Here every unresolvable case has a truthful constant answer — the reply whose system_prompt key is absent and whose verdict is "no_session" — so this verb takes TypeRequestSessionSettings' always-answer posture instead. A conversation this daemon does not host is answered with exactly that reply, which makes the verb useless as a membership oracle.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: these are v2 CONTROL envelopes intercepted before internal/dispatch.Route, exactly as TypeRequestSessionSettings and TypeRequestModelList are. IsKnownAppType rejecting them with ErrUnknownType is also the structural bar against a v1 client pushing one into the v1 handler chain. The partition in internal/protocol/compat_test.go files both in v2OnlyTypes, and inboundAppTypeSet's asserted count does not move.

NEITHER EVER SITS IN excludedTypes AS "pending handler". Like TypeRequestModelList and unlike TypeRequestHistory (#2113→#2116) or TypeRequestAttachment (#2052→#2054), the declaration and the handler land in ONE ticket — the declaration's only daemon-side consumer is that handler, so cutting them apart would produce a slice consumed by exactly one sibling. The request is therefore filed in cmd/pyry/relay_guard_test.go's inboundTypes as "switch-intercepted" from the moment it exists, and the reply in excludedTypes as an outbound reply, exactly as TypeHistoryPage is for TypeRequestHistory.

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 (#1962, split from #1926). The questions claude asks mid-turn when it needs the operator to choose between approaches, carried to a client as one frame per batch. The call rides the same approval bridge a permission prompt does: it blocks on pyry mcp-approve, handleApprove parks it in internal/permbridge keyed by tool_use_id, and streamApprovalBridge.Surface raises it to clients. That surfacer hard-codes tuidriver.ModalClassPermission and uses the tool name as the prompt body, which is the defect this vocabulary exists to close — a clarifying question reaches a remote client today as a modal titled "Permission required" whose body reads as AskUserQuestion.

Grouped alone rather than merged into the modal block above, and the deciding argument is SECURITY rather than taste. denyByClass in internal/modalbridge/modal.go makes ModalShownPayload.DefaultOptionID the DENY option, so a careless confirm on a remote surface denies rather than allows, and docs/protocol-mobile.md § Modal states as a hard invariant that default_option_id MUST equal one of options[].id. That invariant is TOTAL on the permission surface: every modal_shown frame satisfies it, so any client or test may assert it unconditionally. A clarifying question has no deny option and no safe default, so a question riding modal_shown would demote a total invariant to a class-conditional one — every asserting site would have to learn a class exemption, on precisely the field whose whole purpose is fail-safe. Two supporting reasons, both re-checked against the tree: ModalAnswerPayload carries exactly one OptionID, so a batch with per-question multi-select forks the inbound leg either way and the claimed reuse is false at the joint that carries the security contract; and ModalOption is flat {id, label} while the committed capture internal/e2e/realclaude/testdata/ask_user_question_v2.1.239.json nests options under each question and gives each a description, so growing the modal shape would add a field that is always empty for permission and trust and would rewrite every committed modal_shown golden on both sides of the wire. Sharing an approval bridge is not sharing a subject.

The NAME is the daemon's, not claude's, for the reason the blocks above give: the wire type names what the frame IS to a client, so a claude rename lands in one place instead of breaking every client at once. question_shown mirrors modal_shown because the frame is the same KIND of thing — a prompt surfaced to a client, answered or dismissed on a terminal path — while being a different family.

claude's words on this path are the tool name AskUserQuestion and the tool_input keys questions, question, header, options and multiSelect. The sibling blocks' subject-noun trap cuts here too: the SINGULAR question is a substring of the correct name, so a strings.Contains check on it would be RED against it — the same trap TypeSlashCommandList's block records three words wide for command, slash_command and slash, and TypeModelAnnounced's block records for the singular model. The discriminating words are therefore the PLURAL array key questions, which question_shown does not contain (it carries question_, not questions), and the tool name itself, whose snake-cased derivations all carry ask. That containment is why the name is not questions_shown, which would make the plural check red by construction. header, options and multiSelect are per-entry keys and belong to the payload-bytes half that arrives with the shape. See TestQuestionShownType_IsNotClaudesVocabulary.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone report an old phone never receives, and a leak into that set would let a phone send a question_shown frame into dispatch.Route. Two drift detectors classify it, both mandatory from the moment the constant exists rather than from the moment something emits it: the partition in internal/protocol/compat_test.go splits Type* constants between inboundAppTypeSet and v2OnlyTypes (this lives in the latter), and cmd/pyry/relay_guard_test.go's excludedTypes records it as a push.

No inbound request verb is declared here, and that is not an omission. Both constants in this block are outbound-only. The inbound pair — TypeQuestionAnswer / TypeQuestionRefused, declared by #1983 in the block below — sits in cmd/pyry/relay_guard_test.go's inboundTypes as "switch-intercepted" since #1984 gave internal/relay/v2session.go's dispatchAppFrame a case for each. Between those two slices it was filed in excludedTypes under its own pending-handler label, because TestEveryInboundV2TypeHasHandler's Assertion #1 requires an inbound type to be wired into cmd/pyry/relay.go's Handlers map or that switch — a verb declared without its handler is red by construction — and filing it AS A PUSH to dodge that would have been a lie to the guard. TypeAttachmentChunk is the same shape one step earlier, still excluded until #1744 dispatches it. See that block for the reasoning in full.

THE DISMISSAL IS ITS OWN TYPE (#1974), settling what TypeQuestionShown's own slice deferred. ModalDismissedPayload identifies what it clears by modal_id, and a client decoding modal_dismissed routes it to the modal panel — so a question_batch_id arriving in that field clears the wrong panel, or none. Reusing the modal frame would have made the routing depend on a value's shape instead of on the frame's name. Its payload is QuestionDismissedPayload (questions.go): question_batch_id, outcome and source, field for field with the modal frame's, including the absent conversation_id.

The source values do NOT carry over intact from modal_dismissed, and that is published in docs/protocol-mobile.md § Question rather than left to be assumed. Of the modal frame's closed set {remote, local, timeout}, only timeout is emitted by a slice in flight; remote and local are answered outcomes belonging to the answer half. Two of the producer's terminal paths — the caller disconnecting and the daemon shutting down — have NO member in that set at all, so source is declared a plain string whose vocabulary the producer owns, the Outcome/Class posture rather than the modal source's.

The declaring tickets are wire vocabulary only: #1963 declares the batch payload and its nested per-question and per-option types, #1974 the dismissal payload, #1965 the parse that fills the batch from claude's tool input, #1975 the nonce mint, and #1973 the producer that emits both frames. pyrycode-desktop#849 decodes what this family lands. Same declare-then-emit sequencing as #1405→#1410, #1616→#1638, #1704→#1848 and #1726.

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

Mobile Protocol v2 clarifying-question ANSWER vocabulary (#1983, split from #1907). The frames a client sends back to resolve a batch the block above surfaced: question_answer carries the operator's selections, question_refused says the operator declined to choose. These are the question family's FIRST INBOUND types — everything above is binary → phone.

TWO TYPES, NOT ONE NULLABLE FLAG. A refusal carries no answers, and the family's own precedent is that a distinct meaning gets its own type rather than a nullable field on a shared one: TypeQuestionDismissed above is its own type rather than a reused modal_dismissed (#1974) for exactly that reason. The pair mirrors TypeModalAnswer / TypeModalCancel.

SELECTIONS ARE POSITIONAL; ONLY THE VALUES ARE CLIENT-AUTHORED. An answer entry names its question by its INDEX into the batch's questions array — the canonical order the client already renders — rather than echoing the question text back, and the daemon reads the text from its own parked copy. QuestionOption carries no id and claude's protocol selects an option by its LABEL, so the alternative would carry a claude-authored string back across the trust boundary in both directions for no gain. QuestionShownPayload's warning stands unchanged: publishing such a string outbound does not make it trusted when it returns. The values an entry carries ARE genuinely client-authored — claude's contract permits free text anywhere and requires no value to be one of the offered labels — so they are opaque strings, checked against nothing.

THE VENDOR response FIELD IS DELIBERATELY NOT CARRIED. claude's contract (https://code.claude.com/docs/en/agent-sdk/user-input) offers an optional top-level freeform reply that replaces answers entirely; both this repo and pyrycode-desktop decided on 2026-08-31 not to use it. It stays available later with no wire change, so nothing here forecloses it.

THE GUARD CLASSIFIES THESE WITH THEIR INBOUND NEIGHBOURS, and getting it wrong is a red build rather than a style question. Both sit in cmd/pyry/relay_guard_test.go's inboundTypes as "switch-intercepted", beside TypeModalAnswer / TypeModalCancel, because internal/relay/v2session.go's dispatchAppFrame now has cases for them (#1984). Between #1983 and #1984 they were filed in excludedTypes as "pending handler (#1984)" — inboundTypes would have failed Assertion #1 with no dispatch, and "push", the reason the eight outbound neighbours give, is false for a genuinely inbound frame. That entry had to move the moment the cases landed, which Assertion #2 makes mandatory rather than tidy-up. TypeAttachmentChunk is the same shape one step earlier, still excluded until #1744 dispatches it. Filing is required from the moment the constant exists: Assertion #3 reports an unclassified constant, not an unemitted one.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: these are v2 CONTROL envelopes intercepted before internal/dispatch.Route, exactly as TypeModalAnswer and TypeInterrupt are, and there is no dispatch.Route handler for either. A leak into that set would route an inbound control envelope into the v1 handler chain. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; these two live in the latter, and IsKnownAppType rejects both with ErrUnknownType.

The NAMES are the daemon's, not claude's, for the reason TypeQuestionShown's block gives: the wire type names what the frame IS to a client, so a claude rename lands in one place. The subject-noun trap cuts here too — the SINGULAR question is a substring of the tool name AskUserQuestion, so neither name may be probed with a strings.Contains on it.

BOTH FRAMES ARE NOW INTERCEPTED (#1984) — dispatchAppFrame has a case for each, so neither reaches dispatch.Route and neither draws the unknown-type reply it drew while #1983's declaration stood alone. Declaring the constants had changed no runtime path, which is what made that vocabulary-only slice safe on an inbound surface; adding the cases is what changed it, since a Go constant is not a registry. THE INTERCEPTION STILL GRANTS NO INBOUND CAPABILITY: the handler applies no authorization at all, and what makes that fail-safe is that its resolver seam is nil at every construction site, so no frame reaches an actuator. The interactive capability gate and the per-device answer gate (#702) remain the resolver's to apply, default deny, and #1986 installs the latter before anything is wired.

The payloads are QuestionAnswerPayload (with its nested QuestionAnswerEntry) and QuestionRefusedPayload in questions.go. #1985 resolves an answer against the daemon's parked batch; pyrycode-desktop#853 is the client that sends these. Same declare-then-serve sequencing as #1752→#1744.

View Source
const (
	TypeMintPairing   = "mint_pairing"   // phone → binary, inbound v2 control (pending handler — #2127)
	TypePairingMinted = "pairing_minted" // binary → phone, one minted pairing as the pair.Encode string, correlated via in_reply_to
)

Mobile Protocol v2 PAIRING-MINT PAIR (#2126; docs/protocol-mobile.md § Minting a pairing from a paired client publishes both). The frame an already-paired client sends to ask the daemon to mint a pairing for ANOTHER device, and the frame it is answered with. Their payloads are MintPairingPayload and PairingMintedPayload (pairing.go).

THE GAP IT CLOSES: pairing has exactly one minter, the `pyry pair` CLI, and it needs a shell on the daemon's host. runPairDefault reads 32 random bytes, hashes them into a devices.Device and hands the tuple to pair.Encode. Two clients want a second device paired without a shell — a browser build of the desktop client, and a second person's client — and the shape is the one WhatsApp Web and Signal Desktop use: a device that is already paired links the next one.

THE NAMES ARE THE WRITE-VERB FAMILY'S, NOT THE request_* FAMILY'S, and the departure is the point rather than an oversight. All seven inbound request_* verbs — TypeRequestSnapshot, TypeRequestDebugBundle, TypeRequestSessionSettings, TypeRequestAttachment, TypeRequestHistory, TypeRequestModelList, TypeRequestSystemPrompt — are READS: each asks for something that already exists and is answered with a projection of daemon state. This one CREATES. It mints a credential and writes a durable devices.json record, so it takes the shape the vocabulary already has for that — TypeCreateConversation→TypeConversationCreated, TypeCreateWorkspaceFolder→TypeWorkspaceFolderCreated, imperative verb in and past participle out. Filing a state-mutating verb under the read family's prefix would hide the one thing a client most needs to read off the type string: this frame has a side effect on the host. #2052's rule cuts the same way it does for the reads — the wire type string IS the contract, and a name chosen twice is a name chosen wrong once.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: these are v2 CONTROL envelopes intercepted before internal/dispatch.Route, exactly as TypeRequestHistory, TypeRequestModelList and TypeRequestSystemPrompt are. The partition in internal/protocol/compat_test.go files both in v2OnlyTypes, and inboundAppTypeSet's asserted count does not move.

THAT LANE BINDS HARDER HERE THAN ON ANY OF THOSE THREE, because this verb's reply is a bearer credential: IsKnownAppType returning ErrUnknownType is the structural bar that stops a v1 client pushing a credential-minting verb into the v1 handler chain at all. TypeRecentWorkspaces is the OTHER family and is not the precedent to copy — its own block files it as a dispatch.Route read verb and justifies that with "no untrusted input drives a filesystem operation, so it is NOT security-sensitive". The inverse of that sentence is this pair.

THE HANDLER MUST ANSWER ONLY AN AUTHENTICATED PAIRED DEVICE, and this declaration carries that obligation rather than leaving it to the ticket that serves the frame. A one-key request yields a reply carrying a live credential, so the whole risk of the pair concentrates in the gate, and a declare-ahead slice is structurally bad at remembering one. AN INTERACTIVE-CAPABILITY GATE IS NOT A SUBSTITUTE: capability negotiation is a feature advertisement, not an authorization, and the check that matters is that the conn is itself an AEAD-authenticated device the registry holds. Rate-limiting the mint — an already-paired hostile client can otherwise grow devices.json without bound and hold many live credentials — is docs/protocol-mobile.md § Security model threat 7's deferred posture, and #2127 must weigh it rather than inherit silence.

IT WIDENS THREAT 4 (token leak via phone) ON PURPOSE. Minting authority moves from "someone with a shell on the host" to "any paired device", so one compromised client can mint further devices. The mitigation named there — per-device revocation via `pyry pair rm` — still applies and the blast radius is unchanged in kind. THREAT 1 DOES NOT LAND: device_name reaches no claude prompt on any path; it is a registry label, and the hazards it does carry are named at the field.

THE REPLY IS DECLARED AHEAD OF ITS HANDLER. #2127 serves this pair, blocked on the redemption window (#1528, #1529) and the devices.json lock (#1531); until then TypeMintPairing sits in cmd/pyry/relay_guard_test.go's excludedTypes as "pending handler (#2127)" — TypeRequestHistory's precedent (#2113→#2116), the entry moving up to inboundTypes as "switch-intercepted" when dispatchAppFrame gains its case — and TypePairingMinted as an outbound "reply", exactly as TypeHistoryPage is. Declaring ahead of serving is what lets the two client slices start against a published contract instead of waiting on three blockers, and it is this repo's established sequencing: #2052→#2054, #1983→#1984, #2113→#2116.

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 (
	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 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 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 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 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 (
	TypeAttachmentChunk = "attachment_chunk" // phone ↔ binary, one chunk of an attachment's bytes (both directions)
)

Mobile Protocol v2 attachment chunk (#1752, split from #1750; the docs/protocol-mobile.md § Attachments section is #1751). One slice of one attachment's bytes, carrying the whole transfer's metadata on every chunk (AttachmentChunkPayload, attachments.go). A file crossing the encrypted mobile channel routinely exceeds one AEAD frame, so the client splits it and the receiver reassembles; the relay stays transport-only, with no blob endpoint — that option was considered and rejected upstream.

BOTH DIRECTIONS RIDE THIS ONE FRAME, which is why the trailing comment below carries the file's only bidirectional arrow rather than a typo. Upload (client → daemon) and retrieval (daemon → client) are built months apart, and declaring exactly one type is what makes them impossible to drift apart: there is no second shape to update. The trust asymmetry that creates — inbound every field is a client claim, outbound the same fields are daemon-authored — cannot be expressed in a struct, so it lives in AttachmentChunkPayload's SECURITY block.

There is NO completion frame, and that is not an omission. TotalChunks rides every chunk, so a receiver learns the expected count from the FIRST frame it sees and detects a truncated stream earlier than debug_bundle_done detects one for the bundle stream — whose chunks carry only seq and therefore need a terminal frame to learn the count at all. A terminal *error* (a retrieval the daemon abandons mid-stream) is TypeError correlated via in_reply_to, which is #1751's reject vocabulary, not a second attachment frame.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: an old (v1) phone must never receive this frame, and rejection is also what keeps the type off the v1 inbound path — the upload leg really is inbound, so IsKnownAppType refusing it is the structural bar against a v1 client sending one into dispatch.Route. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this constant lives in the latter.

cmd/pyry/relay_guard_test.go's excludedTypes records it too, and NOT as a "push": the reason its seven newest neighbours give — this slice declares no inbound request verb — is false for a frame whose upload leg is inbound, so copying one would put a lie in the guard. Filing it in inboundTypes instead would fail Assertion #1, which requires an inbound type to be wired into cmd/pyry/relay.go's Handlers map or internal/relay/v2session.go's dispatchAppFrame switch, and this slice ships no dispatch. So the entry is excluded under its own label with the reason that is actually true — the inbound leg has no handler YET. #1744 adds the dispatchAppFrame case, at which point the entry moves to inboundTypes as "switch-intercepted". TypeHello, a borderline phone → binary type deliberately not filed inbound, is the precedent followed there rather than the pushes.

The declaring ticket (#1752) is wire vocabulary only: #1753 adds the per-chunk size cap and the both-direction encoding fixtures, #1751 publishes the client-facing contract and the attachment.* reject codes, #1741 reassembles and checks the claims, #1743 stores, and #1897 dispatches the inbound leg. Retrieval landed as three slices rather than the one #1746 this block first named: #2052 declares the request verb (TypeRequestAttachment below), #2053 builds the outbound stream, and #2054 answers the verb with one or the other. Same declare-then-emit sequencing as #1616→#1638 and #1704→#1848.

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

Mobile Protocol v2 ATTACHMENT ANNOUNCEMENT (#2082; docs/protocol-mobile.md § Attachments publishes it). The frame that tells a client a file exists on the host for a conversation. Its payload is AttachmentOfferedPayload (attachments.go).

THE DEFECT IT CLOSES: a client could only ever name a file IT MINTED ITSELF. Upload lands and is answered (TypeAttachmentStored), a message declares which attachments it carries (SendMessagePayload.AttachmentIDs), and retrieval works end to end (TypeRequestAttachment) — but every one of those needs an attachment_id the client already holds, so nothing on the wire ever handed a client an id it did not mint. A file claude produced reached a client as nothing at all (pyrycode-desktop#1028).

WIDENING TypeMessage WOULD NOT HAVE WORKED, and it is the obvious move. That frame is pushed only for the OPERATOR's own turn: its one producer builds a role "user" MessagePayload on confirmed delivery for the durable conversation-history log (#2115) and pushes the same envelope to interactive clients (#2699). The live assistant reply on the v2 interactive lane is a stream of TypeAssistantDelta closed by TypeTurnEnd, and a client learns any other stored message only by asking with TypeRequestHistory. So widening it would announce nothing at the moment a file appears, and would also change a record shape history-page decoders already read.

THE NAME follows the past-participle form of TypeAttachmentStored rather than inventing an idiom, and is fixed here rather than left to the producer for TypeRequestAttachment's reason: a wire type string IS the contract, the desktop client writes its decoder against the published name, and a name chosen twice is a name chosen wrong once. "OFFERED" RATHER THAN "SENT" IS LOAD-BEARING — no bytes ride this frame. A client that wants them asks with TypeRequestAttachment and gets TypeAttachmentChunk back.

IT IS A PUSH AND NOT A REPLY, which is ONE decision expressed in three places that must agree: this block, the docs/protocol-mobile.md § Application message types row, and cmd/pyry/relay_guard_test.go's excludedTypes entry. Nothing solicits it, so there is no request envelope for the envelope's InReplyTo to name — the whole difference from TypeAttachmentStored, which is outbound-only too but correlates to the chunk whose arrival completed the transfer. TypeModalShown is the nearest analogue on this count and on correlation: it has the same origin (an MCP tool call from claude, arriving over the control socket and broadcast to attached clients from the control-server handler goroutine) and its payload likewise carries a conversation id and no turn id.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: an old (v1) phone never receives this frame, and IsKnownAppType rejecting it with ErrUnknownType is also the structural bar against a v1 client SENDING one into dispatch.Route and asserting that a file exists on the host that does not. Filing it in inboundTypes is impossible anyway — Assertion #1 requires an inbound type to be wired into cmd/pyry/relay.go's Handlers map or internal/relay/v2session.go's dispatchAppFrame, and this slice ships no dispatch. Two drift detectors classify it, both mandatory from the moment the constant exists rather than from the moment something emits it: the partition in internal/protocol/compat_test.go (this lives in v2OnlyTypes), and excludedTypes as a push. Unlike TypeRequestAttachment's entry, which had to move to inboundTypes the moment #2054 landed its case, this frame has NO INBOUND LEG AT ALL, so its entry is permanent and never moves.

The declaring ticket (#2082) is wire vocabulary and publication only — no producer, no consumer, no validator. #2083 emits it, and is also where the file itself comes from; whether it records the offer into the conversation-history log is that slice's call. Same declare-then-emit sequencing as #1752→#1897, #1895→#1897 and #2052→#2054.

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

Mobile Protocol v2 attachment upload success reply (#1895, split from #1744; docs/protocol-mobile.md § Attachments publishes it). The one POSITIVE terminal signal the upload leg had: the transfer completed, its claims were checked, and the bytes are on the host addressable by the id the client chose. Its payload is AttachmentStoredPayload (attachments.go). Before this constant a client that uploaded was told what went wrong on every failure path and got silence on the one that worked, and that section said so — "No success frame is declared here, and a client must not invent one."

THE NAME is the positive of CodeAttachmentStorageFailed, so the family's terminal outcomes read as one set rather than a positive invented in a different idiom from its negatives. It is not read as narrow: six other attachment.* codes also terminate an upload, and this is the single positive terminal for the WHOLE transfer, not a report that only the storage step succeeded. "attachment_uploaded" was rejected because the wire type names what the frame IS to a client — TypeQuestionShown's block records that rule — and what this frame is, is the daemon's assertion, not the client's action. "attachment_ack" was rejected outright: TypeAck already exists and AckPayload is a struct{}, so the name would promise the existing empty frame while carrying a payload. That emptiness is also why the generic ack cannot serve here — it can name no attachment.

IT IS A REPLY, correlated via the envelope's InReplyTo, and that is ONE decision expressed in three places that must agree: this block, the docs/protocol-mobile.md § Application message types row, and cmd/pyry/relay_guard_test.go's excludedTypes entry, which defines "reply" as exactly this. TypeSessionSettingsUpdated is the nearest analogue on both counts — an outbound v2 confirmation of an inbound control frame, filed "reply", published as correlated by in_reply_to, and carrying only the id it confirms because the client already knows what it sent. The reject half of this same leg already went that way: CodeAttachmentStreamAborted is a TypeError correlated via in_reply_to, and a success correlating differently from the failure it is the alternative to would split one leg across two mechanisms.

WHAT InReplyTo POINTS AT is the envelope of the chunk WHOSE ARRIVAL COMPLETED THE TRANSFER — not the one with the highest Index. Chunks may arrive in any order and the transfer is complete when every index in [0, TotalChunks) has arrived exactly once, so the completing chunk is whichever one closed the set, and a client cannot predict which of its envelope ids that will be. That is why the payload ALSO carries the attachment id: the envelope field says which frame this answers, the payload says which transfer it concludes, and only the second is a value the client chose and can look up. The two are not redundant.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: an old (v1) phone never receives this frame, and IsKnownAppType rejecting it is the structural bar against a v1 client sending one into dispatch.Route. Filing it in inboundTypes is impossible anyway — Assertion #1 requires an inbound type to be wired into cmd/pyry/relay.go's Handlers map or internal/relay/v2session.go's dispatchAppFrame, and this slice ships no dispatch. Two drift detectors classify it, both mandatory from the moment the constant exists rather than from the moment something emits it: the partition in internal/protocol/compat_test.go (this lives in v2OnlyTypes), and excludedTypes as a reply.

The declaring ticket (#1895) is wire vocabulary and publication only — no producer, no consumer, no validator. #1897 dispatches the inbound leg and emits this frame, and #1898 observes it end to end. Same declare-then-emit sequencing as #1752→#1753 and #1616→#1638.

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

Mobile Protocol v2 operator-facing banner. claude printed text ABOUT the session rather than as part of an answer — a hook's block reason, a local command's output, a loop notification — and this frame is the one typed place it arrives (docs/protocol-mobile.md § banner, #2256).

THE FRAME EXISTS BECAUSE NOTHING ELSE ON THE WIRE COULD CARRY IT, and the gap was total rather than awkward. TypeUnrecognizedMessage is a parser-gap diagnostic, TypeCompacting and TypeRateLimited each report one specific machine state, and the assistant stream carries only what the model said. Text claude prints about the session had nowhere to go and was dropped.

Grouped alone rather than with api_retry/compacting. Those are show/clear sub-states of a live turn with two edges each; this is a single report with none, and its producer set spans two unrelated claude subtypes rather than one line pair.

The NAME is the daemon's, not claude's, for the reason the blocks above give: the wire follows internal/turnevent's VARIANT, so a claude rename lands in one place instead of breaking every client at once. claude's words on this path are the subtypes informational and notification and the payload keys content, level and prevent_continuation; `banner` derives from none of them and names what the thing IS to a client. TestBannerType_IsNotClaudesVocabulary pins that, and pins which of claude's words the check list may NOT contain.

IT HAS ONE PRODUCER SINCE #2319, which maps claude's informational subtype onto this frame against a committed capture, and NO SECOND ONE. #2258, which owned local_command_output and notification, is CLOSED AS ANSWERED (2026-09-10): the capture recorded both unobserved with zero frames, so neither had a field set to map. The frame shipped ahead of that first producer deliberately, and declaring a contract ahead of its producers is this file's established sequencing — #2052→#2054, #1983→#1984 — and it lets the client slices start against a published shape. Unlike TypeMintPairing above, nothing is pending on the INBOUND side: this is an outbound push and cmd/pyry/relay_guard_test.go's excludedTypes carries it as one.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone event an old phone never receives. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter, which is also the structural guarantee that nothing in this daemon accepts a banner FROM a phone.

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

Mobile Protocol v2 compaction boundary. claude finished compacting a conversation's context; this frame says what triggered it and how far the context shrank, so the mark a compaction leaves in a thread can say WHY claude no longer remembers something from before that point (docs/protocol-mobile.md § compaction_boundary).

Grouped alone rather than with api_retry/compacting, and the reason is an ORDERING rather than a taxonomy preference. Those two are show/clear sub-states with two edges; this is a single mark with none. More to the point, it CANNOT be a wider compacting payload: claude states the counts on a separate system/compact_boundary line that arrives AFTER the closing system/status line the falling edge is read off, so by the time the numbers exist the frame that would have carried them has shipped. See internal/turnevent's CompactionBoundary for the captured line order.

The NAME is the daemon's, not claude's, for the reason the blocks above give: the wire follows internal/turnevent's VARIANT, so a claude rename lands in one place instead of breaking every client at once. claude's subtype is compact_boundary; the daemon's word for the process is "compaction" throughout this package and internal/streamsup, and the discriminating word is "boundary" — what this frame MARKS — where `compacting` beside it names a state with two edges. The two frames stay separate and neither absorbs the other.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone event an old phone never receives. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter.

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

Mobile Protocol v2 context-window reading. TypeContextUsage is the single binary → phone envelope carrying 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.

ONE OUTBOUND SHAPE SERVES BOTH LATER PRODUCERS, which is why no request verb is declared alongside it. #2371 maps turnevent.ContextUsage and publishes this frame after a turn; #2293 answers an on-demand request with the SAME frame, correlated by the request envelope's id on Envelope.InReplyTo. That is TypeMCPStatus's arrangement, minus the separate read verb: #2293 owns the verb it needs together with the handler that answers it, because an inbound type with no entry in cmd/pyry/relay.go's Handlers map or internal/relay/v2session.go's dispatchAppFrame switch is red by construction under TestEveryInboundV2TypeHasHandler's Assertion #1.

Declared ahead of both producers, which is this file's established sequencing — #2052→#2054, #1983→#1984, #2373→#2374/#2375 — and it lets the waiting client slices (pyrycode-desktop#1254 and #2293) start against a published shape.

The READING IS INFORMATIONAL. It is claude's own arithmetic, not the daemon-owned contextwindow.Read value that control decisions key on, and nothing in this daemon gates on what a client does with it.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone event an old v1 phone must never receive, and its absence from that set is what makes IsKnownAppType reject it with ErrUnknownType. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter, which is also the structural guarantee that nothing in this daemon accepts a context reading FROM a phone. cmd/pyry/relay_guard_test.go's excludedTypes carries it as an outbound push+reply.

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

Mobile Protocol v2 CONVERSATION-HISTORY PAGE REPLY (#2113, split from #2091; docs/protocol-mobile.md § Conversation history publishes it). One backward step of a history walk: the entries, the cursor to ask again with, and whether the start of the log was reached. Its payload is HistoryPagePayload (history.go), mirroring history.Page.

THE NAME names what the frame IS to a client — a page of history — which is TypeQuestionShown's rule. "history" alone was rejected as describing the whole log rather than the one step this frame carries, and a client that read it that way would have no reason to walk.

IT IS A REPLY, correlated via the envelope's InReplyTo, and that is ONE decision expressed in three places that must agree: this block, the § Application message types row, and cmd/pyry/relay_guard_test.go's excludedTypes entry, which defines "reply" as exactly this. TypeSessionSettings is the nearest analogue on every count — an outbound v2 answer to an inbound request verb that named a conversation, filed "reply", published as correlated by in_reply_to, and carrying NO conversation id of its own because the client already knows what it asked. That last point is why the payload has no such key.

ONE ENTRY IS ONE WIRE ENVELOPE'S WORTH: a wire type, its payload, a timestamp and a durable entry id. That is what makes a page renderable without a second mapping — a client re-reduces it oldest-first through the timeline reducer it already has for the live stream. The id is the log's DURABLE per-conversation one, deliberately not Envelope.EventID, whose ring ids are per-process and do not survive a restart.

A WALK TERMINATES ON at_start, NEVER ON AN EMPTY entries list, and the entry clamp bounds a count rather than bytes — so a page may be short of what was asked for and shortness means nothing. HistoryPagePayload's block carries both rules with their reasoning, and all three page shapes are pinned by committed fixtures rather than left to inference.

UNLIKE ITS REQUEST HALF THIS FRAME CARRIES CONTENT, and the trust consequence is stated on HistoryEntry rather than borrowed from a neighbour: each entry's type and payload are REPLAYED content, claude-authored for a stored assistant frame, so § Security model's threat 1 lands here. TypeRequestAttachment's family publishes the opposite for itself and that sentence must not be carried over.

MUST NOT be added to inboundAppTypeSet: an old (v1) phone never receives this frame, and IsKnownAppType rejecting it is the structural bar against a v1 client sending one into dispatch.Route. Filing it in inboundTypes is impossible anyway — Assertion #1 requires a dispatch case and this frame has no inbound leg at all, so its excludedTypes entry never moves. Two drift detectors classify it, both mandatory from the moment the constant exists: v2OnlyTypes in internal/protocol/compat_test.go, and excludedTypes as a reply.

The declaring ticket (#2113) is wire vocabulary and publication only. #2116 emits it. Same declare-then-emit sequencing as #1895→#1897 and #1616→#1638.

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

Mobile Protocol v2 interrupt control (epic #597 Phase 3, docs/protocol-mobile.md § Interrupt). A paired phone sends interrupt to stop the running turn — the remote equivalent of pressing Esc at the local terminal. The daemon maps it to the neutral turnevent.Cancel command and routes it to the supervised claude as a single Esc keystroke (claude's own interrupt). #600 maps ACP session/cancel onto the same neutral shape.

It is an inbound phone → binary *control* envelope the v2 session manager intercepts at internal/relay/v2session.go's dispatchAppFrame before internal/dispatch.Route (like TypeModalCancel / TypeDequeueMessage); there is NO dispatch.Route handler for it. Since #2103 it carries an OPTIONAL InterruptPayload naming the conversation whose turn to stop — still no modal_id nonce, no answer_token and no idempotency key, and a replayed interrupt simply stops the turn again (a no-op when none is running), so no dedup is needed. An absent payload, an absent conversation_id, an empty one, and a body that does not decode at all are ONE meaning: the conversation the daemon's own cursor points at, the pre-#2103 behaviour an un-upgraded client still gets.

Trust posture: interrupt is gated on the negotiated `interactive` capability (a non-interactive conn's interrupt is inert, whether it names a conversation or not) and is exempt from the per-device permission gate (#702) — interrupting one's own paired session is a normal paired-phone action (ADR 025 § Security model), not a privileged tool-permission decision. Naming a conversation is a validated lookup key and not a widening: a paired device could already reach any conversation by routing a send_message to move the shared cursor and then sending the bare frame.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a leak would route this inbound control envelope to the handler chain. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this constant lives in the latter.

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

Mobile Protocol v2 announced-model report. claude names the model it resolved for the turn on its system/init line, and that value used to stop at the daemon boundary: internal/streamsup's parser has translated the line into turnevent.ModelAnnounced since #1600, but turnbridge.MapEvent's default dropped the variant, so no client could see what claude actually ran. #1638 added the case, so a client sees it now (docs/protocol-mobile.md § model_announced).

Grouped alone rather than with any block above: it is not a turn sub-state with two edges, not turn-independent work, not a periodic reading, and not a condition report about a window. It is an IDENTITY report — what claude says it is, for the turn it says it about.

The NAME is the daemon's, not claude's, for the reason the three blocks above give: the wire follows internal/turnevent's VARIANT (turnevent.ModelAnnounced), so a claude rename lands in one place instead of breaking every client at once. claude's subtype is init; the discriminating word is "init" — claude's, naming its LINE — where ours names what the daemon reports. The sibling blocks' form does not transfer to a test on "model": claude's KEY for the value is model, and so is turnevent.ModelAnnounced's field name, so that word is the subject noun rather than a vocabulary import.

The wire field keeps the name model even though three v2 payloads already carry one (ScreenSnapshotPayload, SessionSettingsPayload, SetSessionSettingsPayload). Those three mean the per-session OVERRIDE, where "" is "inherited default"; this means what claude ANNOUNCED, and in the ordinary case the two disagree loudly. The field name is turnevent's in snake_case per the house convention, every field on this wire is scoped by its envelope type, and a rename would not reach a client author reading only screen_snapshot's row — the doc cross-references do (docs/protocol-mobile.md § model_announced, § Screen snapshot, § Session settings).

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone event an old phone never receives, and a leak into that set would let a phone send a model_announced frame into dispatch.Route. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter.

The declaring ticket (#1616) was wire vocabulary only; #1638 added internal/turnbridge's MapEvent case for turnevent.ModelAnnounced and cmd/pyry's handler case, so this frame now reaches an interactive v2 mobile client. Same declare-then-emit sequencing as #1405→#1410 and #1393→#1394.

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

Mobile Protocol v2 model-list report. The daemon can ask claude which models it will accept — a control_request with subtype initialize, written on the child's held-open stdin, returns a models array — and that inventory used to stop at the daemon boundary, so no client could build a model menu, know which reasoning-effort levels a model supports, or know which models accept auto permission mode. #1848 added the turnbridge arm and #1849 the emitting case, so a client can read the inventory now (docs/protocol-mobile.md § model_list); the menus built on it are client-side work still outstanding (pyrycode-desktop#561, blocked since 2026-08-19; #682 is the same defect for the permission-mode menu).

Grouped alone rather than with any block above: it is not a turn sub-state with two edges, not turn-independent work, not a periodic reading, not a condition report about a window, and not an identity report about one turn. It is a CAPABILITY report — what claude says it CAN be, where model_announced reports what it IS for the turn it says it about. An inventory rather than an event: it does not open or close a turn and is not turn-scoped.

The NAME is the daemon's, not claude's, for the reason the blocks above give: the wire type names what the frame IS to a client, so a claude rename lands in one place instead of breaking every client at once. claude's words on this path are initialize (the control_request subtype) and models (the array key), so the discriminating words are "init" and "models" — model_list contains neither. The sibling blocks' form does not transfer to a test on "model": that is this frame's subject noun and the daemon's own word, so a strings.Contains check on it would be RED against the correct name, the same trap TypeModelAnnounced's block records for its own name.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone report an old phone never receives, and a leak into that set would let a phone send a model_list frame into dispatch.Route. Two drift detectors classify it, both mandatory from the moment the constant exists rather than from the moment something emits it: the partition in internal/protocol/compat_test.go splits Type* constants between inboundAppTypeSet and v2OnlyTypes (this lives in the latter), and cmd/pyry/relay_guard_test.go's excludedTypes records it as a push.

No inbound request verb is declared here, and that is not an omission. TestEveryInboundV2TypeHasHandler's Assertion #1 requires an inbound type to be wired into cmd/pyry/relay.go's Handlers map or internal/relay/v2session.go's dispatchAppFrame switch, and this ticket ships no handler — so a verb declared here would be red by construction, and filing it under excludedTypes to dodge that would be a lie to the guard. It shipped as a PUSH rather than a reply: #1849 emits it from interactiveTurnEmitterV2.Handle on the interactive turn lane, so this constant's excludedTypes classification stays push. A later ticket picking request/reply would still have to declare the verb together with its handler; a client's decode path is the same frame whatever it picks, which is what declaring the shape ahead of the producer bought.

The declaring ticket (#1704) was wire vocabulary only; #1848 added internal/turnbridge's MapEvent arm for turnevent.ModelList and #1849 added cmd/pyry's emitting Handle case, so this frame now reaches an interactive v2 mobile client, and #1705 added the encoding fixtures and the docs/protocol-mobile.md § model_list section. Same declare-then-emit sequencing as #1405→#1410 and #1616→#1638.

View Source
const (
	TypeModelRefusalFallback = "model_refusal_fallback"
)

Mobile Protocol v2 refusal-fallback report. 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. 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)
)

Mobile Protocol v2 start-new-session control (#831, split from #824; docs/protocol-mobile.md § New session). A paired phone sends new_session to start a fresh session in one conversation. On the stream path that is a kill and respawn under a freshly minted session id, NOT a `/clear` keystroke — the terminal-era framing this block used to carry described a supervisor that no longer runs the interactive path. The client observes the break through the EXISTING session_transition marker (reason: "clear", #656/#657) — there is NO synchronous ack (fire-and-forget, like interrupt). Unlike interrupt (→turnevent.Cancel) it maps to no neutral turnevent command; it drives the SessionStarter seam directly.

It is an inbound phone → binary *control* envelope the v2 session manager intercepts at internal/relay/v2session.go's dispatchAppFrame before internal/dispatch.Route (like TypeInterrupt / TypeRequestDebugBundle); there is NO dispatch.Route handler for it. It carries an OPTIONAL NewSessionPayload naming the conversation to restart (#2099) — one field, no modal_id nonce, no answer_token, no idempotency key. The payload is optional in full: the frame was bare until #2099, and an absent payload, an absent conversation_id and an undecodable body all mean "the conversation the daemon's cursor points at", which is what keeps an un-upgraded client working.

Trust posture: new_session is gated on the negotiated `interactive` capability (a non-interactive conn's new_session is inert) and is exempt from the per-device permission gate (#702) — starting a fresh session in one's own paired session is a normal paired-phone action (ADR 025 § Security model), not a privileged tool-permission decision.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a leak would route this inbound control envelope to the handler chain. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this constant lives in the latter.

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

Mobile Protocol v2 usage-limit report. claude's usage-limit window is in a state other than the one measured-benign one, so a turn that stops making progress because of a limit has something on the wire that says why. Before #1404 the daemon dropped claude's rate_limit_event line whole and the information existed nowhere in pyrycode, let alone on a phone (docs/protocol-mobile.md § rate_limited).

Grouped alone rather than with any block above: it is not a turn sub-state with two edges, not turn-independent work, and not a periodic reading. It is a CONDITION report about a usage-limit window that is orthogonal to any turn — whichever turn happened to observe it neither owns it nor bounds it.

The NAME is the daemon's, not claude's, for the reason the two blocks above give: the wire follows internal/turnevent's VARIANT (turnevent.RateLimited), so a claude rename lands in one place instead of breaking every client at once. claude's line type is rate_limit_event; the discriminating word is "event" — claude's, describing its line — where ours names the condition. It is also not a third vocabulary word: rate_limited is already the daemon's own name for this variant on its logging surface (cmd/pyry/interactive_turn_v2.go's eventKind returns exactly this string), so the wire agrees with the daemon. That agreement is prose here rather than a test because internal/protocol cannot import cmd/pyry.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone event an old phone never receives, and a leak into that set would let a phone send one into dispatch.Route. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter.

The declaring ticket (#1405) was wire vocabulary only; #1410 added internal/turnbridge's MapEvent case for turnevent.RateLimited and cmd/pyry's handler case, so this frame now reaches an interactive v2 mobile client. Unlike #1393 the docs/protocol-mobile.md section landed with the shape rather than with the producer, because #1410 disclaimed the file.

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

Mobile Protocol v2 LIVE WORKSPACE READ (#2598). The frame a client sends to read one regular file as it is on the host NOW, from the recorded workspace or admitted read folders of the conversation it names. Its payload is ReadWorkspaceFilePayload (attachments.go), and it is answered exactly as TypeRequestAttachment is: an attachment_chunk stream correlated by in_reply_to, or one CodeAttachmentNotFound / CodeAttachmentStreamAborted TypeError.

Declared and served in one slice, unlike #2052→#2054: the handler is the declaration's only consumer, so there is no pending-handler interval to file in excludedTypes.

View Source
const (
	// TypeRekeyRequest is the Mobile Protocol v2 control envelope either
	// side may emit to nudge the peer toward initiating a re-key
	// handshake (docs/protocol-mobile.md § Re-key). It is informational
	// from the binary's perspective: the binary is the IK responder per
	// ADR 024, so an inbound rekey_request takes no transport action.
	//
	// MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a
	// leak into that set would route the envelope to dispatch.Route's
	// handler chain, violating the v2 control / v1 application boundary
	// enforced by internal/relay's v2 session manager. The drift detector
	// in internal/protocol/compat_test.go partitions Type* constants
	// between inboundAppTypeSet and v2OnlyTypes; this constant lives in the
	// latter.
	TypeRekeyRequest = "rekey_request"
)

Mobile Protocol v2 control-envelope types. These are NOT v1 application types; they MUST NOT appear in inboundAppTypeSet (internal/protocol/envelope.go). The v2 session manager intercepts them at the dispatch boundary (internal/relay/v2session.go's dispatchAppFrame) before internal/dispatch.Route is called, so handler-table lookup never sees them.

View Source
const TypeReplySuggestion = "reply_suggestion"

TypeReplySuggestion declares outbound v2 suggestion state, gated by the negotiated "interactive" capability. ReplySuggestionPayload defines its set and explicit-null clear contract. Not yet emitted; never dispatched inbound or added to the v1 inboundAppTypeSet.

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

Mobile Protocol v2 attachment RETRIEVAL REQUEST verb (#2052, split from #1746; docs/protocol-mobile.md § Attachments publishes it). The frame a client sends to ask the daemon for a stored attachment — the one thing that section had deliberately left unpublished, in its own words: "the retrieval request verb ... (no such type exists in the daemon today)". Its payload is RequestAttachmentPayload (attachments.go). It is the FIRST inbound type in the attachment family that is inbound and nothing else — TypeAttachmentChunk's upload leg is inbound, but that frame rides both directions.

THE NAME follows the three inbound "ask the daemon for X" verbs already on this wire — TypeRequestSnapshot, TypeRequestDebugBundle, TypeRequestSessionSettings — rather than inventing a fourth idiom for the same act. It is fixed here rather than left to the handler because a wire type string IS the contract: the desktop client that consumes it writes its sender against the published name, and a name chosen twice is a name chosen wrong once.

IT NAMES A CONVERSATION AND AN ATTACHMENT, AND NOTHING ELSE. It was the one place this family let a client name a scope until #2142 gave AttachmentChunkPayload a conversation_id as well, and the argument that had kept it the only one — that an upload could only steer bytes elsewhere by naming a conversation — is reversed there rather than qualified here. Publishing that field changed no trust level, for the reason the rest of this paragraph gives, and it left the two ids doing different work: this one selects which conversation's file to read, the chunk's decides which conversation an upload is filed under (#2143). The safety was never in the id's shape or its randomness in either case — it is CONFINEMENT: the id is a lookup key validated against the daemon's own registry before it reaches a path join, never a value trusted as sent, and naming a conversation is not authorization. RequestAttachmentPayload's block carries that rule in full, because the block is what the handler's author reads.

CORRELATION RIDES THE ENVELOPE'S InReplyTo, so the payload carries NO REQUEST-ID KEY — TypeAttachmentStored's block has that decision and the reasoning transfers unchanged, since both terminals of this leg already correlate that way: the answering chunks and the CodeAttachmentStreamAborted TypeError alike. The committed testdata/attachment_chunk_retrieval.json settled it in bytes before this constant existed, riding in_reply_to 91, and testdata/request_attachment.json is the envelope 91 it answers. Inventing a request-id key here would leave that landed fixture describing a different scheme.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is a v2 CONTROL envelope intercepted before internal/dispatch.Route, exactly as TypeRequestSessionSettings and TypeModalAnswer are. IsKnownAppType rejecting it with ErrUnknownType is also the structural bar against a v1 client pushing one into the v1 handler chain. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this one lives in the latter, and inboundAppTypeSet's asserted count does not move.

THE GUARD FILES IT WITH ITS INBOUND NEIGHBOURS, and getting that wrong is a red build rather than a style question. cmd/pyry/relay_guard_test.go's inboundTypes carries it as "switch-intercepted", beside TypeAttachmentChunk, because internal/relay/v2session.go's dispatchAppFrame now has a case for it (#2054). Between #2052 and #2054 it sat in excludedTypes as "pending handler (#2054)": inboundTypes would have failed Assertion #1, which requires an inbound type to be wired into cmd/pyry/relay.go's Handlers map or dispatchAppFrame, and that slice shipped no dispatch; "push", the reason the outbound neighbours give, is false for a genuinely inbound frame, and filing it that way to dodge Assertion #1 would have been a lie to the guard. TypeQuestionAnswer / TypeQuestionRefused sat under exactly that label between #1983 and #1984, and TypeAttachmentChunk before #1897; each had to move the moment its case landed, which Assertion #2 makes mandatory rather than tidy-up — a wired type left in excludedTypes fails. Filing is required from the moment the constant exists: Assertion #3 reports an unclassified constant, not an unemitted one.

The declaring ticket (#2052) was wire vocabulary and publication only — no producer, no consumer, no validator, and NO ADMISSION-TIME CHECK. #2053 built the outbound chunk stream and #2054 answers this verb, owning the shape check, the registry validation and the CodeAttachmentNotFound reject path. Same declare-then-serve sequencing as #1752→#1897, #1895→#1897 and #1983→#1984.

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

Mobile Protocol v2 ON-DEMAND CONTEXT-USAGE REQUEST (#2431, split from #2293; docs/protocol-mobile.md § context_usage publishes it). The frame a client sends to ask for one conversation's context breakdown NOW, rather than waiting for the next turn to end. Its payload is RequestContextUsagePayload (interactive.go).

THE DEFECT IT CLOSES is that the automatic reading is both late and cheap. #2371 publishes one after every TurnEnd at detail:"summary" — claude answers that from the last response's usage plus local estimates, with no token-count API calls. An operator watching a long turn has no way to ask what it is consuming, and no way to get the expensive detail:"full" reading, which counts each category through that API and is worth asking for only when someone is looking at the screen.

IT MINTS NO SECOND OUTBOUND SHAPE. The answer is TypeContextUsage and ContextUsagePayload UNCHANGED, correlated by the envelope's InReplyTo and carrying NO EventID — so the reply never enters the #647 replay ring and advances no client cursor. That is what TypeContextUsage's own block above anticipated when it declared one shape for both producers, and it is why that type stays in cmd/pyry/relay_guard_test.go's excludedTypes as "push+reply" rather than moving.

THE DETAIL IS THE DAEMON'S CHOICE AND IS NOT ON THE WIRE. The payload carries a conversation id and nothing else: the daemon always asks at "full". A detail key would let one client downgrade what another is shown for the same conversation, because closely-spaced asks COLLAPSE to one round trip below the relay seam and are all answered from its result — so the cheap reading would win a race it should not be in. It would also be the second place that vocabulary is decided, after streamsup's own allow-list.

ITS REJECT VOCABULARY IS TWO CODES, ONLY ONE OF THEM NEW: the existing CodeConversationNotFound for a conversation this daemon does not host, and CodeContextUsageUnavailable (above) for one it hosts with no reading to give. A MALFORMED PAYLOAD MINTS NO THIRD CODE — it is TOLERATED, TypeRequestModelList's decision and for that block's stated reason: the id reaches a registry membership check and nothing else, never a path component, so a failed decode leaves an empty id that membership refuses. Do not copy that tolerance to a verb that joins the id into a path.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is a v2 CONTROL envelope intercepted before internal/dispatch.Route, exactly as TypeRequestModelList and TypeMCPStatusRequest are. IsKnownAppType rejecting it with ErrUnknownType is also the structural bar against a v1 client pushing one into the v1 handler chain. The partition in internal/protocol/compat_test.go files it in v2OnlyTypes, and inboundAppTypeSet's asserted count does not move.

IT NEVER SITS IN excludedTypes AS "pending handler". Like TypeRequestModelList and TypeRequestSystemPrompt, the declaration and the handler land in ONE ticket — the declaration's only daemon-side consumer is that handler — so it is filed in inboundTypes as "switch-intercepted" from the moment it exists.

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

Mobile Protocol v2 debug-bundle request verb (#813, split from #803; docs/protocol-mobile.md § Debug bundle). A paired phone sends request_debug_bundle to ask for the current session's debug bundle — the recent daemon log ring plus the newest terminal recording when debug capture was on. The bundle is daemon-global by construction (the log ring has no per-session key, per #811), so this is a BARE control frame — no payload, no conversation_id, no field an attacker could use to select another session's data — mirroring TypeInterrupt.

It is an inbound phone → binary *control* envelope the v2 session manager intercepts at internal/relay/v2session.go's dispatchAppFrame before internal/dispatch.Route (like TypeInterrupt / TypeDequeueMessage); there is NO dispatch.Route handler for it. The daemon replies by STREAMING the assembled bundle back as debug_bundle_chunk* + debug_bundle_done (#812), never through the synchronous 8-frame handler-reply path.

Authorization is pairing, enforced structurally at the Noise IK handshake: an unpaired device is refused with 4401 and never reaches dispatchAppFrame, so no new authorization gate lives on this verb.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: a leak would route this inbound control envelope to the handler chain. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this constant lives in the latter.

View Source
const (
	TypeRequestHistory = "request_history" // phone → binary, inbound v2 control (pending handler — #2116)
)

Mobile Protocol v2 CONVERSATION-HISTORY REQUEST VERB (#2113, split from #2091; docs/protocol-mobile.md § Conversation history publishes it). The frame a client sends to ask for entries older than the ones it already has. Its payload is RequestHistoryPayload (history.go).

THE DEFECT IT CLOSES: a client opening an existing conversation sees nothing that happened before it connected, because there was no verb to ask with. internal/relay's replayMissed is catch-up across a dropped connection over the bounded in-memory ring in internal/eventring — empty after a daemon restart — and § Reconnect / Backfill semantics said in as many words that a client wanting more "has no verb to ask for them and receives none". The log it reads landed in #2112 (internal/history); this constant puts that log's shapes on the wire.

THE NAME follows the four inbound "ask the daemon for X" verbs already here — TypeRequestSnapshot, TypeRequestDebugBundle, TypeRequestSessionSettings, TypeRequestAttachment — rather than inventing a fifth idiom for the same act. It is fixed by this declaring ticket rather than by the handler because a wire type string IS the contract: pyrycode-desktop#1088 and pyrycode-mobile#623 are both parked on the published section, not on the handler, and a name chosen twice is a name chosen wrong once.

PAGED, NEWEST-FIRST, WALKING BACKWARDS, ADDRESSED BY AN OPAQUE CURSOR rather than by an offset or a page number, both of which a concurrent append invalidates. RequestHistoryPayload's block carries the rules a handler's author needs: the cursor is not a secret and not a capability, Limit's zero means "the daemon chooses" and must never be allocated from, and the conversation id is a lookup key validated against the registry before any path join rather than a value trusted as sent.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is a v2 CONTROL envelope intercepted before internal/dispatch.Route, exactly as TypeRequestAttachment and TypeRequestSessionSettings are. IsKnownAppType rejecting it with ErrUnknownType is also the structural bar against a v1 client pushing one into the v1 handler chain, and that rejection's load-bearing half is the inbound one because this leg really is inbound. The partition in internal/protocol/compat_test.go files it in v2OnlyTypes, and inboundAppTypeSet's asserted count does not move.

IT SITS IN excludedTypes AS "pending handler (#2116)" UNTIL THAT SIBLING LANDS, and moves to inboundTypes the moment internal/relay/v2session.go's dispatchAppFrame gains its case — mandatory rather than tidy-up, since Assertion #2 fails a wired type left behind. inboundTypes today would fail Assertion #1, which requires a dispatch that this ticket does not ship, and "push" would be a lie to the guard about a genuinely inbound frame. TypeRequestAttachment sat under exactly that label between #2052 and #2054, and TypeQuestionAnswer / TypeQuestionRefused between #1983 and #1984. Filing is required from the moment the constant exists: Assertion #3 reports an unclassified constant, not an unemitted one.

The declaring ticket (#2113) is wire vocabulary and publication only — no producer, no consumer, no validator and no admission-time check. #2116 answers the verb, owning the shape check, the registry validation, the page's byte budgeting and every reject code; the reject CONDITIONS are published here, their codes are not, because minting a parallel reject vocabulary ahead of the handler is what #2052's precedent declines to do. Same declare-then-serve sequencing as #2052→#2054 and #1983→#1984.

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

Mobile Protocol v2 ON-DEMAND MODEL-LIST REQUEST VERB (#2125, split from #2084; docs/protocol-mobile.md § model_list publishes it). The frame a client sends to ask for a conversation's model menu at any time. Its payload is RequestModelListPayload (interactive.go).

THE DEFECT IT CLOSES: TypeModelList reaches a client two ways and a conversation created AFTER the client connected gets neither. The live interactive turn lane drops every event whose producing session is not the active conversation's, and the connect-time reconcile runs only inside the handshake, so a conversation that did not exist then is not in it. Without a request verb there is no third option, and a client's model and effort menus stay blank on a fresh chat (pyrycode-desktop#1054). #2085 makes the case universal by deferring the spawn to the first message.

THE NAME follows the five inbound "ask the daemon for X" verbs already here — TypeRequestSnapshot, TypeRequestDebugBundle, TypeRequestSessionSettings, TypeRequestAttachment, TypeRequestHistory — rather than inventing a sixth idiom for the same act. #2052's rule applies: a wire type string IS the contract, and a name chosen twice is a name chosen wrong once.

IT MINTS NO SECOND OUTBOUND SHAPE. The answer is TypeModelList and ModelListPayload UNCHANGED, correlated by the envelope's InReplyTo and carrying NO EventID — so the reply never enters the #647 replay ring and advances no client cursor, exactly as the connect-time reconcile's frame does not. The payload is what the daemon-side resolver already returns, so "the same payload the reconcile would send" means the SAME SOURCE rather than the same fields copied; the turnbridge mapping is not forked. That is why TypeModelList stays in cmd/pyry/relay_guard_test.go's excludedTypes as an outbound push, exactly as TypeHistoryPage does for TypeRequestHistory.

UNLIKE ITS NEAREST SHAPE PRECEDENT IT CAN REFUSE. TypeRequestSessionSettings answers every unresolvable case with an all-zero payload and never an error frame; this verb cannot borrow that, because turnevent.ModelList.Models is documented never-empty and an empty models array must never stand in for "unknown". The reject shape is TypeRequestHistory's — a TypeError envelope correlated by InReplyTo — with two codes: the existing CodeConversationNotFound and CodeModelListUnavailable (above), minted by this same ticket because it is the one that sends them.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is a v2 CONTROL envelope intercepted before internal/dispatch.Route, exactly as TypeRequestHistory and TypeRequestSessionSettings are. IsKnownAppType rejecting it with ErrUnknownType is also the structural bar against a v1 client pushing one into the v1 handler chain. The partition in internal/protocol/compat_test.go files it in v2OnlyTypes, and inboundAppTypeSet's asserted count does not move.

IT NEVER SITS IN excludedTypes AS "pending handler". Unlike TypeRequestHistory (#2113→#2116) and TypeRequestAttachment (#2052→#2054), the declaration and the handler land in ONE ticket — the declaration's only daemon-side consumer is that handler, so cutting them apart would produce a slice consumed by exactly one sibling. It is therefore filed in inboundTypes as "switch-intercepted" from the moment it exists; filing it as pending would fail Assertion #2 the moment dispatchAppFrame's case exists in the same commit.

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

Mobile Protocol v2 conversation-reset status. A reset runs in two daemon-side phases — a wrap-up turn that writes a handoff note for the successor, then a kill and respawn of claude under a new session id — and without this frame a client sees neither: the screen simply pauses for however long both take (docs/protocol-mobile.md § resetting, #2453).

Grouped alone rather than with api_retry/compacting, and the reason is PROVENANCE rather than shape. It has that pair's show/clear shape exactly, but their block comment reads "PTY-derived status peers" and counts its own two members: both are the wire form of a stream-json detector reading claude's own output. THIS FRAME'S SOURCE IS THE DAEMON'S OWN RESET ROUTINE. Every value on it is the daemon's — an id it assigned, a bool it computed, and two tokens it selected from the closed sets declared beside ResettingPayload — so nothing claude authored crosses on it. TypeUnrecognizedMessage below is the package's precedent for being grouped alone on exactly this ground: not a claude sub-state.

It is therefore NOT a turnevent variant and not one of the turn-stream events the § Interactive events intro counts, the distinction slash_command_list already draws in that file. Like every status peer it never opens or closes a turn.

ONE RESET EMITS TWO active:true FRAMES before a single active:false — see ResettingPayload, where that property and the closed sets are stated in full.

NO PRODUCER YET: #2455 owns the reset routine that emits this, and #2456 routes a client's /clear into it. Declaring a contract ahead of its producers is this file's established sequencing (#2052→#2054, #1983→#1984), and it lets the client slices start against a published shape.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: an old phone never receives it, and no phone may send it. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter, which is what makes IsKnownAppType reject an inbound "resetting" rather than letting one reach a handler — cmd/pyry/relay_guard_test.go's excludedTypes carries it as a push for the same reason.

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

Mobile Protocol v2 mid-turn-reconnect resync marker. When a reconnecting phone advertises a hello.last_event_id that has aged out of the bounded per-conversation event ring, the daemon emits this marker (instead of a partial, gap-ful replay) to tell the phone to do a full reload of the named conversation (#647; ADR 025 § Backpressure / replay). It carries only a conversation_id in an inline anonymous payload — no named payload struct, mirroring TypeRekeyRequest's payload-less control precedent.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: it is an outbound binary → phone v2 event an old phone must never receive. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this constant lives in the latter.

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

Mobile Protocol v2 session-error marker (#1007, split from #1001; docs/protocol-mobile.md § Error codes). It reports a conversation-scoped session problem to a paired phone as an unsolicited frame, and its code says whether the problem is terminal:

  • CodeSessionBlocked is terminal. The daemon's interactive message queue (internal/msgqueue) bounded a persistent-failure drain and gave up (the OnGiveUp seam, #1000); the client must never mistake it for a transient retry.
  • CodeSessionChildCrashing is not terminal (#2724). The conversation's claude child 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.

Unlike TypeError it is NOT in_reply_to-correlated to a client request (there is no request to reply to), so the payload (SessionErrorPayload, messaging.go) carries the conversation identity itself, plus the code and a human-readable message.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: it is an outbound binary → phone v2 event an old phone must never receive. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this constant lives in the latter.

This ticket (#1007) is wire vocabulary only — the producer that emits the frame on msgqueue give-up is sibling #1008.

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

Mobile Protocol v2 session-facts report. What claude's own build IS and what posture claude says the child is running under, taken from the SAME system/init line TypeModelAnnounced's value comes from. internal/streamsup has translated those two keys into turnevent.SessionFacts since #2252, and turnbridge.MapEvent has mapped the variant onto this type since #2254, so a client sees both facts. The defect it closes is the one TypeModelAnnounced's block states, applied to two more facts of the same shape: the daemon knows what it ASKED FOR and only claude knows what it GOT, so an unexpected posture or an unexpected build was being discarded with the rest of the line. The waiting consumer is pyrycode-desktop#1241.

Grouped alone rather than with any block above: it is not a turn sub-state with two edges, not turn-independent work, not a periodic reading, not a condition report about a window, and not a capability inventory. It is an IDENTITY report like TypeModelAnnounced, and it is a separate block from that one because the two report identities of DIFFERENT SUBJECTS — model_announced reports what claude will run AS for one turn, this reports what the child RUN itself is and how it is postured. A client renders the model on every turn; a version and a posture are what an operator checks when something looks wrong.

THE NAME CARRIES A TENSION WORTH MEETING HEAD-ON rather than leaving a reader to notice. This frame declares no session identity at all: claude's session_id is claude's session and NOT the daemon's conversation, and it is not even declared on the producer's decode target. "Session" here names the CHILD RUN the two facts describe, not an identifier the frame carries.

The NAME is otherwise the daemon's, not claude's, for the reason the blocks above give: the wire follows internal/turnevent's VARIANT (turnevent.SessionFacts), so a claude rename lands in one place instead of breaking every client at once.

THE DISCRIMINATING WORDS INVERT THE OBVIOUS CHOICE, and the trap the sibling blocks record cuts closer here than on any of them. `session` is a substring of this very name, so a strings.Contains check on it is RED against the correct name — TypeModelAnnounced's block records the same trap for the singular `model` and TypeSlashCommandList's records it three words wide for command, slash_command and slash. `session` is also claude's own word, via the session_id key on the same init line, so the collision is not merely a coincidence of spelling. The checkable words are claude's SUBTYPE (init) and claude's two KEYS for the values (claude_code_version and permissionMode); this name contains none of the three, which is what makes the negative pins satisfiable at all. Separating it from the three shipped session_-prefixed constants — TypeSessionTransition, TypeSessionSettings and TypeSessionError — has to be an EQUALITY rather than a containment for that same reason, the shape TypeQuestionDismissed's pin needed against TypeModalDismissed (see TestSessionFactsType_IsNotClaudesVocabulary).

NO effort FIELD ON THE PAYLOAD, and the absence is MEASURED rather than forgotten. #2251 captured the init line under the production spawn shape with an effort actually set, on the launch argv and acknowledged in band, and no init line carries an effort key. That measurement is machine-enforced by effortInitPins in internal/streamsup. Declaring the field anyway would put a permanently empty field on a shipped wire type, which is far harder to withdraw than to add later; should a later claude start publishing one, that pin reddens and that is the ticket to write then.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone report an old phone never receives, and a leak into that set would let a phone send a session_facts frame into dispatch.Route. Two drift detectors classify it, both mandatory from the moment the constant exists rather than from the moment something emits it: the partition in internal/protocol/compat_test.go splits Type* constants between inboundAppTypeSet and v2OnlyTypes (this lives in the latter), and cmd/pyry/relay_guard_test.go's excludedTypes records it as a push. Only the second of the two actually reddens on a BRAND-NEW constant — compat_test.go's lists are hand-maintained, so a constant left off both of them moves its size assertion nowhere, while the relay guard walks codes.go's AST.

No inbound request verb is declared here, and that is not an omission. TestEveryInboundV2TypeHasHandler's Assertion #1 requires an inbound type to be wired into cmd/pyry/relay.go's Handlers map or internal/relay/v2session.go's dispatchAppFrame switch, and this ticket ships no handler — so a verb declared here would be red by construction, and filing it under excludedTypes to dodge that would be a lie to the guard.

The declaring ticket (#2253) was wire vocabulary and documentation only; #2252 added cmd/pyry's emitting Handle case and #2254 internal/turnbridge's MapEvent arm for turnevent.SessionFacts, so this frame now reaches an interactive v2 mobile client. Same declare-then-emit sequencing as #1405→#1410, #1616→#1638, #1704→#1848 and #1726→#2003, with the two halves landing in the opposite order: the Handle case came first here and pushed nothing until the mapping arrived beneath it.

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

Mobile Protocol v2 session-boundary marker. When the daemon's session rotates (a /clear, an idle eviction, or a workspace change), it emits this outbound binary → phone event so the phone can construct a ThreadItem.SessionBoundary marker (pyrycode-mobile#336) instead of inferring boundaries from message fields that do not exist. The multi-field payload lives in SessionTransitionPayload (messaging.go): previous/new session id, the transition reason, when it occurred, and the workspace cwd.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: it is an outbound binary → phone v2 event an old phone must never receive. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this constant lives in the latter.

This ticket (#656) is wire vocabulary only — the producer that emits the marker on session transitions is sibling #657.

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

Mobile Protocol v2 slash-command-list report. The set of slash commands the running child accepts for this conversation, sourced from the same initialize control reply the block above uses — that reply carries a commands array alongside its models array, so one round trip answers both. The defect it closes: the desktop's Actions menu offers reset, compact and knowledge capture, and knowledge capture is workspace-specific — it exists in the operator's vault and in almost no repository — so a menu that always offers it is wrong in most repositories, and sending it there produces an "Unknown command" reply in the thread. Two consumers wait on the frame (pyrycode-desktop#681, the Actions-menu grey-out; pyrycode-desktop#694, a slash-command type-ahead in the message box).

Grouped alone rather than with any block above: it is not a turn sub-state with two edges, not turn-independent work, not a periodic reading, not a condition report about a window, and not an identity report about one turn. It is a capability inventory of VERBS — what the operator may ask the session to do — where model_list is a capability inventory of identities and model_announced reports the one identity in force. It is not merged into the TypeModelList block despite sharing the initialize round trip: sharing a source is not sharing a subject, the two naming paragraphs have to say different things (two claude words there, four here), and every block in this run groups alone.

The NAME is the daemon's, not claude's, for the reason the blocks above give: the wire type names what the frame IS to a client, so a claude rename lands in one place instead of breaking every client at once.

claude has FOUR words on this path where model_list had two: initialize (the control_request subtype), commands (the array key in the control reply, 51 entries in the committed capture initialize_control_v2.1.239.json), slash_commands (a key on the system/init stdout line carrying the identical 51 names as bare strings) and terminal_slash_commands (a different array on that same line, 2 entries: doctor and color). The names-only twin is not the source because it carries none of the 11 alias strings the control reply publishes across 9 of its 51 entries — a daemon forwarding it would ship the grey-out consumer a list in which reset does not appear, and reset is the desktop Actions menu's own entry (an alias of clear, not a command name).

The discriminating checks are therefore the PLURALS, and the sibling blocks' subject-noun trap cuts three words wide here rather than one: command, slash_command and slash are each a substring of the correct name, so a strings.Contains check on any of the three would be RED against it — the same trap TypeModelAnnounced's block records for model and TypeModelList's for models. slash_command_list contains none of claude's four words and no init, which is what makes the negative pins satisfiable at all. One plural check covers all three: commands is a substring of slash_commands, which is a substring of terminal_slash_commands, so a name derived from either longer key necessarily contains the shorter one (see TestSlashCommandListType_IsNotClaudesVocabulary).

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone report an old phone never receives, and a leak into that set would let a phone send a slash_command_list frame into dispatch.Route. Two drift detectors classify it, both mandatory from the moment the constant exists rather than from the moment something emits it: the partition in internal/protocol/compat_test.go splits Type* constants between inboundAppTypeSet and v2OnlyTypes (this lives in the latter), and cmd/pyry/relay_guard_test.go's excludedTypes records it as a push.

No inbound request verb is declared here, and that is not an omission. TestEveryInboundV2TypeHasHandler's Assertion #1 requires an inbound type to be wired into cmd/pyry/relay.go's Handlers map or internal/relay/v2session.go's dispatchAppFrame switch, and this ticket ships no handler — so a verb declared here would be red by construction, and filing it under excludedTypes to dodge that would be a lie to the guard. If #1720 picks request/reply it declares the verb together with its handler and moves this constant from push to reply; a client's decode path is the same frame either way, which is what declaring the type now exists to freeze.

The declaring ticket (#1726) is wire vocabulary only: #1727 declares the payload and its entry type, #1720 produces and emits the frame, and #1718 adds the encoding fixtures and the docs/protocol-mobile.md § slash_command_list section. Same declare-then-emit sequencing as #1405→#1410, #1616→#1638 and #1704→#1848.

View Source
const TypeStopBackgroundTask = "stop_background_task"

TypeStopBackgroundTask is a phone → binary v2 control verb, intercepted before v1 dispatch. It requires negotiated interactive; production remains inert until the stop seam is wired. It introduces no capability of its own.

View Source
const TypeSwitchAgent = "switch_agent"

TypeSwitchAgent names a phone → binary v2 agent-switch request. It remains outside the v1 inboundAppTypeSet; handling is pending #2870/#2871.

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

Mobile Protocol v2 thinking-progress reading. claude's mid-turn proof of life: during a long assistant turn nothing else crosses the stream-json surface, so a client showing "thinking" cannot separate a slow answer from a wedged one. This frame carries the daemon's translation of claude's system/thinking_tokens line (docs/protocol-mobile.md § thinking_progress).

Grouped alone rather than with api_retry/compacting or with the background-task three: it is not a show/clear sub-state with two edges, and its subject is neither the turn's lifecycle nor turn-independent work — it is a periodic READING of work in progress, with no edges at all.

The NAME is the daemon's, not claude's, for the reason the background-task block above gives: the wire follows internal/turnevent's VARIANT (turnevent.ThinkingProgress), so a claude rename lands in one place instead of breaking every client at once. The discriminating word is "progress" — what the daemon reports — not "tokens", which is claude's subtype. It also disambiguates against ThoughtChunk, which carries the CONTENT of claude's reasoning and is never forwarded (ADR 025): this frame carries none, so a client that renders it as text has nothing to render.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone event an old phone never receives. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter.

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

Mobile Protocol v2 tool-denial marker. claude refused to run a tool call it had already announced; this frame says WHICH call, so a blocked tool row can look blocked rather than broken (docs/protocol-mobile.md § tool_denied, #2233).

A FRAME OF ITS OWN RATHER THAN TWO FIELDS ON tool_result, and the choice is forced twice over rather than preferred. claude states the denial on a separate system/permission_denied line that arrives BEFORE the tool result (assistant/tool_use → system/permission_denied → user/tool_result, measured across the three denial-bearing arms of the committed bypass_reescalation capture), 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 whose tool_result frame has already shipped, which a field on a sent frame cannot answer at all. A standalone frame needs neither. See internal/turnevent's ToolCallDenied for the captured line order.

The NAME is the daemon's, not claude's, for the reason the blocks above give: the wire follows internal/turnevent's VARIANT, so a claude rename lands in one place instead of breaking every client at once. claude's subtype is permission_denied; the daemon's word names what the frame is ABOUT — a tool call — where "permission" names the mechanism that refused it and would read as a sibling of the MCP approval flow this has nothing to do with.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: this is an outbound binary → phone event an old phone never receives. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter. Keeping it there is also the structural guarantee that no inbound re-authorize path exists — nothing in this daemon accepts a tool_denied FROM a phone.

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

Mobile Protocol v2 tool-progress reading. 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 in internal/protocol/envelope.go. The drift detectors in internal/protocol/compat_test.go and cmd/pyry's relay guard classify it as an outbound v2 push.

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

Mobile Protocol v2 unrecognized-message diagnostic. The stream-json parser recognises three top-level message types from claude and a fixed set of content blocks; everything outside the measured known-ignored list used to be dropped into a debug log the production daemon does not print, so a claude version that moved something meaningful into a new type would show nothing anywhere. This frame carries that drop to the client instead (docs/protocol-mobile.md § unrecognized_message).

Grouped alone rather than with api_retry/compacting because it is not a claude sub-state: it reports a gap in OUR mapping, and its payload is the only interactive frame that carries raw model-adjacent JSON.

MUST NOT be added to inboundAppTypeSet in internal/protocol/envelope.go: an old phone never receives it. The drift detector in internal/protocol/compat_test.go partitions Type* constants between inboundAppTypeSet and v2OnlyTypes; this lives in the latter.

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

Functions

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.

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 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 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"`

	// ReadUpTo is the stored durable history read mark, including zero.
	ReadUpTo uint64 `json:"read_up_to"`
	// LatestEntryID is the newest durable history entry, or zero for no entries.
	LatestEntryID uint64 `json:"latest_entry_id"`
	// 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"`

	// 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"`
}

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.
	// The three history-backed direct live producers stamp a successful append's
	// ID; reconnect replay currently omits it. This conveys no authorization.
	HistoryEntryID *uint64 `json:"history_entry_id,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 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 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 in claude's own order, truncated from the tail by the producer. 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, and it is NOT a dated identifier: an alias (sonnet), a bracketed variant (opus[1m]), or default. A client cannot derive a family by splitting it on "-".

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 a Claude entry's own Value. 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 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"`
}

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