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
- Variables
- func IsV1Compatible(env Envelope) error
- type AckPayload
- type AssistantDeltaPayload
- type BackfillDonePayload
- type BackfillSincePayload
- type ConversationCreatedPayload
- type ConversationSummary
- type ConversationUpdatedPayload
- type ConversationsPayload
- type CreateConversationPayload
- type DequeueMessagePayload
- type Envelope
- type ErrorPayload
- type HelloAckPayload
- type HelloClientPayload
- type HelloServerPayload
- type InnerFrameV2
- type ListConversationsPayload
- type MessageChunkPayload
- type MessagePayload
- type ModalAnswerPayload
- type ModalCancelPayload
- type ModalDismissedPayload
- type ModalOption
- type ModalShownPayload
- type PromoteConversationPayload
- type QueueStatePayload
- type QueuedItem
- type RegisterPushTokenPayload
- type RequestSnapshotPayload
- type RoutingEnvelope
- type ScreenSnapshotPayload
- type SendMessagePayload
- type SessionTransitionPayload
- type StallPayload
- type ToolResultPayload
- type ToolUsePayload
- type TurnEndPayload
- type TurnStatePayload
Constants ¶
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" // Message errors. CodeMessageTooLong = "message.too_long" // Relay errors. CodeRelayNoServer = "relay.no_server" CodeRelayServerIDConflict = "relay.server_id_conflict" )
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.
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" // Backfill. TypeBackfillSince = "backfill_since" TypeMessageChunk = "message_chunk" TypeBackfillDone = "backfill_done" // 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.
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 v1TypeSet 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 v1TypeSet and v2OnlyTypes; these six live in the latter.
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 v1TypeSet 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 v1TypeSet 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 v1TypeSet and v2OnlyTypes; these two live in the latter.
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 v1TypeSet 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 v1TypeSet 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).
const ( TypeQueueState = "queue_state" // binary → phone, outbound v2 queued-backlog snapshot TypeDequeueMessage = "dequeue_message" // 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 v1TypeSet 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 v1TypeSet 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.
const ( TypeNoiseInit = "noise_init" TypeNoiseResp = "noise_resp" TypeNoiseMsg = "noise_msg" )
Inner-frame discriminator values for InnerFrameV2.Type (docs/protocol-mobile.md § Wire shapes table).
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.
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. Unlike the modal frames it carries NO payload — no conversation_id, no modal_id nonce, no answer_token, no idempotency key: a bare control frame.
Trust posture: interrupt is gated on the negotiated `interactive` capability (a non-interactive conn's interrupt is inert) 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.
MUST NOT be added to v1TypeSet 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 v1TypeSet and v2OnlyTypes; this constant lives in the latter.
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 v1TypeSet 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 v1TypeSet 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 v1TypeSet (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.
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 v1TypeSet 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 v1TypeSet and v2OnlyTypes; this constant lives in the latter.
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 v1TypeSet 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 v1TypeSet 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.
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 ¶
var ( ErrUnknownType = errors.New("protocol: unknown envelope type") ErrUnsupported = errors.New("protocol: unsupported envelope feature") )
Sentinel errors returned by IsV1Compatible. 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 IsV1Compatible ¶
IsV1Compatible reports whether env is acceptable under wire-protocol v1. Returns nil when env.Type is in the v1 type set and env.PayloadEncrypted is false. Returns ErrUnsupported when env.PayloadEncrypted is true (reserved for v2; docs/protocol-mobile.md § Reserved for v2). Returns ErrUnknownType when env.Type is empty or not in the v1 set.
Check order: PayloadEncrypted first, Type second. A frame failing both checks reports as ErrUnsupported — the stricter rejection wins.
IsV1Compatible 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 AssistantDeltaPayload ¶ added in v0.15.0
type AssistantDeltaPayload struct {
ConversationID string `json:"conversation_id"`
TurnID string `json:"turn_id"`
Seq int `json:"seq"`
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).
type BackfillDonePayload ¶
type BackfillDonePayload struct {
Delivered int `json:"delivered"`
}
BackfillDonePayload is the body of an Envelope whose Type == TypeBackfillDone (docs/protocol-mobile.md § backfill_done). Binary → phone direction; sent after the last message_chunk to mark completion.
type BackfillSincePayload ¶
type BackfillSincePayload struct {
SinceTS time.Time `json:"since_ts"`
ConversationID *string `json:"conversation_id"` // *string + no omitempty: spec wire shows literal `null` (meaning "all conversations"); omitempty would drop the key.
MaxMessages int `json:"max_messages"`
}
BackfillSincePayload is the body of an Envelope whose Type == TypeBackfillSince (docs/protocol-mobile.md § backfill_since). Phone → binary direction. SinceTS is RFC3339Nano per the envelope timestamp rule; MaxMessages is the phone's advisory cap on returned-message count.
type ConversationCreatedPayload ¶
type ConversationCreatedPayload struct {
ID string `json:"id"`
IsPromoted bool `json:"is_promoted"`
Cwd string `json:"cwd"`
Name *string `json:"name"`
LastUsedAt time.Time `json:"last_used_at"`
}
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 ConversationSummary ¶
type ConversationSummary struct {
ID string `json:"id"`
Name *string `json:"name"`
IsPromoted bool `json:"is_promoted"`
Cwd string `json:"cwd"`
LastMessageTS time.Time `json:"last_message_ts"`
LastUsedAt time.Time `json:"last_used_at"`
}
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"`
Name *string `json:"name"`
Cwd string `json:"cwd"`
LastUsedAt time.Time `json:"last_used_at"`
}
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, 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.
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"`
}
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 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, per-conversation event id (eventring) 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"`
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"`
}
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.
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"`
}
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.
type HelloClientPayload ¶
type HelloClientPayload struct {
Role string `json:"role"`
DeviceName string `json:"device_name"`
ClientVersion string `json:"client_version"`
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; when present it triggers a backfill (docs/protocol-mobile.md § Backfill semantics).
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 per-conversation 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 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 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 MessageChunkPayload ¶
type MessageChunkPayload struct {
Messages []MessagePayload `json:"messages"`
}
MessageChunkPayload is the body of an Envelope whose Type == TypeMessageChunk (docs/protocol-mobile.md § message_chunk). Binary → phone direction; streamed during a backfill response. Messages reuses MessagePayload directly — the spec says "same shape as message.payload, multiple."
type MessagePayload ¶
type MessagePayload struct {
ConversationID string `json:"conversation_id"`
MessageID string `json:"message_id"`
Role string `json:"role"`
Text string `json:"text"`
}
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.
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"`
}
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
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 {
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"`
}
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).
ModalID is a one-time, opaque, unguessable nonce minted per surfaced modal (by #703). It is the sole correlation key: there is no conversation_id, so the daemon resolves ModalID against 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 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 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"`
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. Text is untrusted, phone-originated transit content (see the producer/handler #722/#723 for the never-log discipline).
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 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 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;
// AuthenticateFirstFrame is the only consumer.
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; the dispatcher ignores CloseCode on inbound
// (phone→binary) frames. 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"`
}
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.
type SendMessagePayload ¶
type SendMessagePayload struct {
ConversationID string `json:"conversation_id"`
MessageID string `json:"message_id"`
Text string `json:"text"`
}
SendMessagePayload is the body of an Envelope whose Type == TypeSendMessage (docs/protocol-mobile.md § send_message). Phone → binary direction.
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).
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 (mirroring BackfillSincePayload.ConversationID): 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 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 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"`
IsError bool `json:"is_error"`
ResultSummary string `json:"result_summary"`
}
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.
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"`
Name string `json:"name"`
InputSummary string `json:"input_summary"`
}
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.
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"`
}
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.
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.