Documentation
¶
Overview ¶
Package relay drives the binary's outbound long-lived connection to the relay: opens the WSS via internal/transport and exposes inbound frames as protocol.RoutingEnvelope values via Frames(). The binary↔relay leg is content-blind — the relay registers the binary's server-id from the x-pyrycode-server request header and claims the slot on WS upgrade, so the conn is treated as established the moment the upgrade completes; there is no relay-originated hello/hello_ack handshake on this leg. It does NOT dispatch on envelope types, validate device tokens, or interpret application-level error payloads — those concerns layer above this package in a future ticket (supervisor wiring + per-message handlers).
The single source of truth for the headers and close codes is docs/protocol-mobile.md (§ Authentication, § Connection lifecycle, § Worked example). When that document changes, this package changes.
Index ¶
- Constants
- Variables
- func ReassembleAttachment(frames []protocol.Envelope, attachmentID string, inReplyTo uint64) ([]byte, error)
- func ReassembleBundle(frames []protocol.Envelope) ([]byte, error)
- func ShippedMinClientVersions() map[string]string
- func ValidEffort(e string) bool
- func ValidModel(m string) bool
- func WorkspaceRoot() string
- type ActiveConn
- type AgentCapabilities
- type AgentSwitchFailure
- type AgentSwitchOutcome
- type AgentSwitchState
- type AgentSwitcher
- type AttachmentIntake
- type BackgroundTaskStopOutcome
- type BackgroundTaskStopper
- type Config
- type Connection
- func (c *Connection) Close() error
- func (c *Connection) CloseConn(connID string, code uint16) error
- func (c *Connection) Connected() bool
- func (c *Connection) Frames() <-chan protocol.RoutingEnvelope
- func (c *Connection) Reconnected() <-chan struct{}
- func (c *Connection) Send(env protocol.RoutingEnvelope) error
- func (c *Connection) SendContext(ctx context.Context, env protocol.RoutingEnvelope) error
- func (c *Connection) SendPushWake(platform, token string) error
- func (c *Connection) SendPushWakeFeedback(ctx context.Context, platform, token, requestContext string) (<-chan string, error)
- func (c *Connection) Wait() error
- type DiagnosticQuestionResolver
- type HistoryPageOutcome
- type HistoryPageResult
- type HistoryPager
- type HostedAppsAPI
- type HostedAppsAssets
- type HostedAppsDiscovery
- type InnerFrameV2Decoded
- type Interrupter
- type LateSessionStarter
- type LiveState
- type MCPActuator
- type ModalDismissal
- type ModalResolver
- type PairingMintOutcome
- type PairingMintResult
- type PairingMinter
- type QuestionResolver
- type QueueRemover
- type QueueSender
- type RotatedWithoutWorkspaceError
- type RunConfig
- type SessionStarter
- type SettingsUpdate
- type SettingsUpdater
- type ThreadView
- type V2Session
- type V2SessionConfig
- type V2SessionManager
- func (m *V2SessionManager) ActiveConns(ctx context.Context) []ActiveConn
- func (m *V2SessionManager) ActiveThreadConns(ctx context.Context, conversation string) []ActiveConn
- func (m *V2SessionManager) DeliverThread(ctx context.Context, connID string, env protocol.Envelope) error
- func (m *V2SessionManager) FlushPushes(ctx context.Context) error
- func (m *V2SessionManager) HostedAppsChanged(change apps.Change)
- func (m *V2SessionManager) Push(ctx context.Context, connID string, env protocol.Envelope) error
- func (m *V2SessionManager) PushLiveState(ctx context.Context, connID string, r LiveState) error
- func (m *V2SessionManager) Rekey(ctx context.Context, connID string) error
- func (m *V2SessionManager) RetireLiveState(ctx context.Context, connID string) error
- func (m *V2SessionManager) Run(ctx context.Context) error
- func (m *V2SessionManager) SetReplaySource(ring *eventring.Ring, currentConv func() string)
- func (m *V2SessionManager) StreamAttachment(ctx context.Context, connID, attachmentID, path string, inReplyTo uint64) error
- func (m *V2SessionManager) StreamBundle(ctx context.Context, connID string, blob []byte) error
- type V2SessionState
- type WorkspaceFile
Constants ¶
const ( // StatusIdleTimeout is the WS close code the binary asks the relay to // apply when a v2 session receives no inbound frame within idleTimeout // and the manager tears it down through the in-repo idle sweep (#774). // Echoes HTTP 408 (Request Timeout), consistent with the 44xx←HTTP // close-code convention (4401←401, 4404←404, 4409←409, 4429←429). Wire // spec: docs/protocol-mobile.md § Error codes, close-code row 4408. // Sending it to an already-dropped conn is a harmless relay no-op. StatusIdleTimeout websocket.StatusCode = 4408 // StatusProtocolMismatch is the WS close code the binary asks the // relay to apply when a phone sends an inner frame that violates the // v2 inner-frame shape, the state machine, or the discriminator // table. Wire spec: docs/protocol-mobile.md § Error codes, close-code // row 4421. StatusProtocolMismatch websocket.StatusCode = 4421 // StatusHandshakeFailure is the WS close code the binary asks the // relay to apply when the Noise_IK handshake fails before // CipherStates exist (e.g. MAC failure on IK message 1, wrong static // pubkey). No AEAD-sealed error envelope can be sent — the close // code is the only signal. Wire spec: docs/protocol-mobile.md // § Error codes, close-code row 4426. StatusHandshakeFailure websocket.StatusCode = 4426 // StatusQueueOverflow is the WS close code the binary asks the relay to // apply when a v2 session's push queue exceeds pushQueueByteCeiling and // handlePushOverflow tears it down (#1505). Echoes HTTP 413 (Content Too // Large), consistent with the 44xx←HTTP convention. Deliberately NOT // StatusIdleTimeout: reusing 4408 would mislabel an overflow as an idle // session, the same class of mistake #912 documented when a transport // outage surfaced as noise.rekey_failed. Wire spec: // docs/protocol-mobile.md § Error codes, close-code row 4413. // // closeWith is called with a NIL frame on this path — nothing is sealed. // The trip condition is a parked drain, which in the #874 case means the // transport is down, so sealing an error envelope would burn a Noise // send-nonce for a frame that cannot arrive and gap the phone's recv nonce // (the #912 hazard). The idle sweep already sets this precedent, and the // close code alone suffices because the phone's recovery is a fresh // handshake, not a message. A future change that adds a sealed error frame // here reintroduces the nonce hazard. StatusQueueOverflow websocket.StatusCode = 4413 // StatusSessionGone is the WS close code the binary asks the relay to // apply when a noise_msg arrives on a conn the manager holds no session // for (#2488). handleFrame creates a bare V2StateAwaitingInit session for // any unheld conn id, so the frame reaches handleNoiseMsg with no // CipherStates: it can be neither decrypted nor answered with a sealed // error, and the close code is the only signal. Echoes HTTP 410 (Gone), // consistent with the 44xx←HTTP convention. Wire spec: // docs/protocol-mobile.md § Error codes, close-code row 4410. // // Deliberately NOT StatusProtocolMismatch, which this arm used before: // clients treat 4421 as a permanent mismatch and stop re-dialling, yet a // legitimate client lands here whenever it still holds cipher state for a // session the daemon dropped. Because closeWith deletes the conn from the // session map, all three causes — a daemon restart, an idle sweep (4408) // and the push-queue ceiling (4413) — reduce to a conn id the manager no // longer holds, and the documented recovery for each is a fresh Noise // handshake, which only a retryable close lets the client reach. // // Deliberately NOT StatusIdleTimeout either: 4408 means "your session // idled out", and a restart or an overflow is not that — the same mislabel // StatusQueueOverflow's comment already records rejecting. StatusSessionGone websocket.StatusCode = 4410 // StatusClientUpdateRequired is the WS close code the binary asks the // relay to apply when it refuses an app build older than the host's // minimum for that app (#2576). It follows the sealed // protocol.CodeClientUpdateRequired error in the same routing envelope, // after the Noise handshake and the token check, so the client reads the // error before the close — the token-failure arm's shape. Echoes HTTP 412 // (Precondition Failed), consistent with the 44xx←HTTP convention: the // minimum app version is a precondition the hello failed. 426 would be // the literal match but 4426 is StatusHandshakeFailure. Wire spec: // docs/protocol-mobile.md § Error codes, close-code row 4412. // // Terminal for THIS host only: a client stops re-dialling this daemon and // keeps its other hosts. Sent only while a minimum is set (#2578); see // MinMobileClientVersion. StatusClientUpdateRequired websocket.StatusCode = 4412 )
Mobile Protocol v2 close codes (docs/protocol-mobile.md § Error codes). 4401 (StatusUnauthorized) lives in auth.go and is reused unchanged.
const ( MinMobileClientVersion = "" MinDesktopClientVersion = "" )
The minimum app version this daemon release accepts, per app, as MAJOR.MINOR.PATCH (#2578). Build constants, not operator configuration: each daemon release carries its own, so during a staged rollout different hosts may enforce different minimums. Empty means no minimum for that app, and while both are empty no hello is ever refused for its version.
Set the first one only after that app has shipped a release sending client_version as <app>/<MAJOR>.<MINOR>.<PATCH>: once any minimum is set, every build sending the older free text is refused (docs/protocol-mobile.md § Compatibility). A value that does not parse fails NewV2SessionManager and TestNewV2SessionManager_MinClientVersions, never reading as "no minimum".
const MsgClientUpdateRequired = "this app version is no longer supported by this host; update the app"
MsgClientUpdateRequired is the static message of the protocol.CodeClientUpdateRequired error. The minimum travels in ErrorPayload.MinClientVersion, never in the message.
const MsgInvalidToken = "device token not recognised; re-pair via pyry pair on the binary"
MsgInvalidToken is the fixed user-facing message emitted in the auth.invalid_token error payload (docs/protocol-mobile.md § Error codes). Defined as an exported const so future integration tests can pin it without re-typing the spec sentence.
const ( // answers an unprovable model with the same reply set_session_settings does. MsgModelListUnavailable = "model list is unavailable" )
Static reply messages, one per wire code this path can answer with. Both are fixed constants and NEITHER is derived from an error value, an id, or a model string — the payload this handler forwards is claude-authored and untrusted, and nothing derived from it may reach a message a client reads.
const (
MsgSettingsModelNotOffered = "requested model is not offered"
)
Static reply messages for set_session_settings failures (#845). Each is a FIXED constant — never attacker-influenced bytes. encoding/json quotes attacker bytes into its decode-error string, so no decode error, payload byte, or model/effort value ever reaches these messages, the wire, or a log.
MsgSettingsModelNotOffered is exported for create_conversation (#2665), which refuses a model the same way.
StatusUnauthorized is the WS close code the relay sends when the binary rejects a phone's device token (docs/protocol-mobile.md § Error codes, close-code row 4401). Typed locally so callers don't import the websocket package for the value; parallel to statusServerIDConflict in connection.go.
Variables ¶
var ( // ErrServerIDConflict is the terminal error returned by Wait when // the relay refused our claim with WS close 4409 persistently // (serverIDConflictThreshold consecutive closes across the transport's // backoff ladder — a transient self-reconnect race clears well inside // that window, see #1072). Another binary is holding the same // server-id. Operator escalation: another pyry is already running for // this server-id. ErrServerIDConflict = errors.New("relay: server-id conflict (close 4409)") // ErrAdmissionFailed is returned by Wait on the first HTTP 401 upgrade // rejection. Automatic attempts stop until the caller creates a new connection. ErrAdmissionFailed = errors.New("relay: daemon admission failed (HTTP 401)") // ErrInvalidConfig is returned by Connect on invalid or missing fields. ErrInvalidConfig = errors.New("relay: invalid config") )
Sentinel errors. Callers distinguish fatal vs. retryable via errors.Is.
var ( // ErrThreadWithheld means current recipient eligibility forbids the envelope. ErrThreadWithheld = errors.New("relay: thread delivery withheld") // ErrThreadDeliveryFailed means encoding, sealing or transport failed. ErrThreadDeliveryFailed = errors.New("relay: thread delivery failed") )
var ErrConnNotFound = fmt.Errorf("relay: conn not found: %w", control.ErrConnNotFound)
ErrConnNotFound is returned by (*V2SessionManager).Rekey when connID is not currently registered in the manager's sessions map. Wraps control.ErrConnNotFound so the control dispatcher's errors.Is(err, control.ErrConnNotFound) check in handleRekey continues to map to ErrCodeConnNotFound on the wire without further plumbing.
var ErrEffortNotOffered = errors.New("relay: effort not offered")
ErrEffortNotOffered means a well-formed non-empty effort is not offered by the model the session will run: absent from that model's advertised levels, or, when the model has no entry for its agent, outside the fallback set. The settings handler replies as it does to an effort validEffort refuses, with the fixed, non-retryable protocol.malformed, and the error carries no value.
var ErrModelNotOffered = errors.New("relay: model not offered")
ErrModelNotOffered means a complete retained model vocabulary proves that a requested non-empty model is absent. The settings handler maps it to a fixed, non-retryable protocol.malformed response. It deliberately carries no model value because callers may log the outcome.
ErrModelVocabularyUnavailable means retained state cannot prove whether a requested non-empty model is offered. Missing state, dropped rows, and a row whose Value was truncated all map here. The settings handler returns the same retryable model_list.unavailable used by the model-list request path.
var ErrSessionNotOpen = errors.New("relay: session not open")
ErrSessionNotOpen is returned by (*V2SessionManager).Rekey when the named session exists but is not eligible for a manual rekey — either not in V2StateOpen (still handshaking, or already torn down), or already awaiting a rekey reply from a prior emit. The control dispatcher surfaces this verbatim through Response.Error with no ErrorCode (slice A defines no wire code for this state yet).
var ErrSessionUnknown = errors.New("relay: session unknown")
ErrSessionUnknown is the relay-local sentinel the SettingsUpdater adapter returns when set_session_settings names a session the daemon does not host. The cmd/pyry adapter maps sessions.ErrSessionNotFound onto it; handleSetSessionSettings maps it to a deterministic session.not_found reply.
var ErrTransportDown = errors.New("relay: transport down, rekey deferred - retry")
ErrTransportDown is returned by (*V2SessionManager).Rekey when the named session is open and eligible but the relay transport is currently down, so a manual rekey would seal a rekey_request that cannot reach the phone (burning a Noise send-nonce and arming a doomed reply window). Distinct from ErrSessionNotOpen so the operator sees "transport down, retry" rather than "not open". Surfaced verbatim by the control dispatcher through Response.Error with no ErrorCode, the same posture as ErrSessionNotOpen (#912).
Functions ¶
func ReassembleAttachment ¶ added in v0.16.0
func ReassembleAttachment(frames []protocol.Envelope, attachmentID string, inReplyTo uint64) ([]byte, error)
ReassembleAttachment is the receiver-contract reference and test oracle: it walks frames in arrival order, reconstructs one transfer's file, or fails cleanly. It is pure and exported — run in production only phone-side (out of repo); the daemon has no inbound caller. It is what makes "reassembling them in index order recovers the file byte for byte" testable at all, since that is a statement about a reassembler, and it is ReassembleBundle's counterpart without that function's contract.
IT SELECTS ONE TRANSFER BY BOTH CORRELATORS, which is the division § attachment_stored records: in_reply_to says WHICH FRAME THIS ANSWERS and the payload id says WHICH TRANSFER IT BELONGS TO. A frame answering another request is skipped, exactly as ReassembleBundle skips a non-bundle frame, so concurrent retrievals over one connection separate cleanly. A frame answering THIS request while naming another transfer is REJECTED rather than skipped: that is the daemon answering the right ask with the wrong bytes, and it is the failure the payload id catches and in_reply_to cannot — which is what makes the two non-redundant rather than belt-and-braces.
THE PUBLISHED RECEIVER RULES, applied to the selected set:
- NEVER ALLOCATE FROM A CLAIM. TotalChunks and Size are integers chosen by whoever sent the frame, so attachments.CheckDeclaration cross-checks them through the published per-chunk bound on the FIRST selected chunk, before anything is sized. Reusing the project's own enforcement point rather than re-deriving the equality keeps this a reference to the real contract.
- A receiver ADDRESSES BY INDEX and never appends, so chunks may arrive in ANY ORDER. That is deliberately weaker than debug_bundle_chunk's Seq, which demands strict succession — the neighbouring rule is the obvious thing to copy and it is the wrong one here. A duplicate index, an index outside [0, TotalChunks), or a declaration disagreeing with the transfer's earlier chunks is refused.
- Completion is every index in [0, TotalChunks) having arrived exactly once. Only then is the assembled length compared against Size and sha256(assembled) against SHA256, as lowercase hex for EXACT EQUALITY.
On ANY failure it returns (nil, err) — never partial or corrupted bytes. No error it builds names the filename or the digest, both of which ride the frames it is reading.
func ReassembleBundle ¶ added in v0.16.0
ReassembleBundle is the receiver-contract reference and test oracle: it walks frames in arrival order and reconstructs the original blob, or fails cleanly. It is pure and exported — run in production only phone-side (out of repo); the daemon has no inbound caller. It is what proves AC#2 and the "fail cleanly" correctness requirement (you cannot test clean-failure without a reassembler).
A debug_bundle_chunk must carry Seq == the count of chunks already seen (0-based contiguous ascending), else a reorder/gap/duplicate is rejected. A debug_bundle_done must carry Total == the count of chunks seen, else a truncated/count-mismatch stream is rejected. Any other frame type is skipped (tolerates interleaved assistant_delta etc.). Frames exhausted with no done marker is an incomplete stream. On ANY failure it returns (nil, err) — never partial or corrupted bytes.
func ShippedMinClientVersions ¶ added in v0.25.0
ShippedMinClientVersions returns this build's minimums keyed by app name, the shape V2SessionConfig.MinClientVersions takes.
func ValidEffort ¶ added in v0.28.0
ValidEffort is validEffort for create_conversation (#2665), on ValidModel's terms.
func ValidModel ¶ added in v0.28.0
ValidModel is validModel for create_conversation (#2665), which accepts a model under set_session_settings' shape rule so one grammar bounds every client model this daemon stores. Exported as a wrapper rather than by rename so validModel's own tests stay where they are.
func WorkspaceRoot ¶ added in v0.27.0
func WorkspaceRoot() string
WorkspaceRoot is the folder new workspaces live under, $HOME/pyry-workspace, sent to an accepted client as hello_ack's workspace_root. Exported so the daemon's first-start seed (#2569) roots the Default workspace here rather than spelling the folder a second time. Empty when $HOME is unknown or not absolute.
Types ¶
type ActiveConn ¶ added in v0.15.0
type ActiveConn struct {
ConnID string
Interactive bool
Thread bool
DeviceName string
ClientVersion string
ClientFeatures string
DeviceTokenHash string
View ThreadView
PendingView ThreadView // admitted items query; Unjoined when no query is pending
ThreadCompact bool
}
ActiveConn is one open v2 session in the capability-aware enumeration: its routing conn-id, the negotiated interactive-capability decision recorded at handshake, and what the client reported about itself there. It holds no *V2Session, CipherState, key, or credential material, so the snapshot is safe to hand to a consumer goroutine. The downstream structured-stream fan-out selects interactive vs non-interactive conns on the Interactive flag.
DeviceName, ClientVersion and ClientFeatures are REMOTE-AUTHORED, UNVALIDATED strings (#2148) — the only fields here that are not daemon-authored routing or decision data, which is why they carry an obligation the routing fields do not. A consumer MUST NOT log them, interpolate them into an error message, or render them without applying its own gate; internal/sessions' admitClient is the gate the one consumer that renders them uses. A consumer MUST ALSO NOT format this struct wholesale — "%+v", slog.Any — which would emit them into the daemon log by accident. Each is "" when absent or over its retention bound: 256 bytes for name, 64 for version and 1024 for features, inclusive. They are never persisted to the device registry as a group; features are memory-only.
DeviceTokenHash is the TokenHash of the device the handshake AUTHENTICATED (s.device), which is what "this conn belongs to that device" must be decided on — never DeviceName, which any phone may set to another device's name (#2564). It is daemon-authored but credential-derived, so it too MUST NOT be logged.
View is set only by ActiveThreadConns: the projection this conn's last successful items query selected for that conversation. It is the routing hint for which live update family to deliver; delivery rechecks it before sealing. ThreadCompact, also set only by ActiveThreadConns, reports a negotiated thread_compact, so an unjoined conn may be loading either projection. PendingView is an admitted items query for the same conversation, captured with View; switching projections requires live cancellation for both views.
type AgentCapabilities ¶ added in v0.27.0
type AgentCapabilities struct {
Interrupt bool
MidTurnInput bool
SlashCommands bool
MCPServers bool
ContextUsageDetail bool
EffortLevels []string
Models []string
}
AgentCapabilities is the half of a session's capability list that depends on its agent and model, the value half of V2SessionConfig.CapabilitiesFor. Primitives only, like RunConfig. The relay composes it with the permission modes and attachment types it owns into protocol.SessionCapabilities.
type AgentSwitchFailure ¶ added in v0.37.0
type AgentSwitchFailure uint8
AgentSwitchFailure contains only safe classifications, never downstream text.
const ( AgentSwitchOtherFailure AgentSwitchFailure = iota AgentSwitchConversationNotFound AgentSwitchInvalidRequest AgentSwitchModelNotOffered AgentSwitchEffortNotOffered AgentSwitchBusy AgentSwitchWorkspaceRejected )
type AgentSwitchOutcome ¶ added in v0.37.0
type AgentSwitchOutcome struct {
State AgentSwitchState
Failure AgentSwitchFailure
}
AgentSwitchOutcome is the switch result. A nonempty daemon session ID means State MUST be AgentSwitchCommitted, even if cleanup failed. Committed outcomes owe no error reply; existing state events are the adapter's responsibility. The zero value is an uncommitted offline failure, never silent success.
type AgentSwitchState ¶ added in v0.37.0
type AgentSwitchState uint8
AgentSwitchState distinguishes an inert preflight refusal from an uncommitted failure (which may follow wrap-up) and commitment even with cleanup failure.
const ( AgentSwitchFailed AgentSwitchState = iota AgentSwitchRefused AgentSwitchCommitted )
type AgentSwitcher ¶ added in v0.37.0
type AgentSwitcher interface {
SwitchAgent(ctx context.Context, request protocol.SwitchAgentPayload) AgentSwitchOutcome
}
AgentSwitcher switches a named conversation on a relay worker, never on Run. SwitchAgent may block during wrap-up. It must honor manager cancellation, be safe for concurrent calls and classify admission/busy failures itself. Client disconnect does not cancel ctx. The conversation ID is untrusted: implementations must validate and resolve it without a cursor fallback before any path use. Production adaptation and committed event publication belong to cmd/pyry.
type AttachmentIntake ¶ added in v0.16.0
type AttachmentIntake interface {
// Receive routes one decoded chunk of one conn's upload; see the type doc for
// its three answers. connID keeps distinct conns' transfers apart.
//
// conversationID MUST already have passed KnownConversation, because it
// becomes a path component below this seam (attachments.EnsureDir).
// handleAttachmentChunk checks it on every chunk, so a transfer naming an
// unusable conversation is refused on its first frame. It is a string rather
// than a conversations.ConversationID so this package need not import
// internal/conversations.
Receive(connID, conversationID string, chunk protocol.AttachmentChunkPayload) (attachmentID string, stored bool, err error)
// ReleaseConn drops every upload still in flight for one conn, returning the
// daemon-wide capacity they held without waiting for the idle window. A
// no-op for a conn holding nothing, so closeWith calls it unconditionally.
ReleaseConn(connID string)
}
AttachmentIntake drives one decoded attachment_chunk from admission to stored bytes and releases a departing conn's uploads; *attachments.Intake satisfies it. handleAttachmentChunk maps the returned internal/attachments sentinels to wire codes with errors.Is.
Receive has three answers, and the first is not a refusal:
- ("", false, nil): accepted, the transfer wants more. Most chunks of a healthy upload get this; attachments.ErrIncomplete never crosses the seam.
- (attachment_id, true, nil): the completing chunk's verified bytes are stored.
- ("", false, err): refused, with the failing layer's own sentinel unwrapped so errors.Is reaches it.
Security: a returned error may wrap host paths, the daemon's conversation id or the sanitised filename, so it is neither logged nor replied. The handler sends a static per-code message and logs the mapped code. An implementation must not add annotation that leaks more.
Receive requires a single feeder, one goroutine at a time per conn id; the manager guarantees it by running uploads on the conn's FIFO appFrameWorker. ReleaseConn has no such precondition: it only removes, so closeWith calls it on Run while that conn's worker may still be inside Receive.
type BackgroundTaskStopOutcome ¶ added in v0.33.0
type BackgroundTaskStopOutcome uint8
BackgroundTaskStopOutcome is the result of one task stop attempt. Refused is the zero value so an implementation must explicitly accept an attempt.
const ( BackgroundTaskStopRefused BackgroundTaskStopOutcome = iota BackgroundTaskStopAccepted BackgroundTaskStopCannotActOnConversation )
type BackgroundTaskStopper ¶ added in v0.33.0
type BackgroundTaskStopper interface {
StopBackgroundTask(ctx context.Context, conversationID, taskID string) BackgroundTaskStopOutcome
}
BackgroundTaskStopper stops one named task. The implementation owns conversation validation and resolution: ids are untrusted lookup keys, never paths, and must never select the cursor conversation. CannotActOnConversation silently means the requested conversation cannot be acted on; Refused produces the fixed wire error. The call runs on the connection's appFrameWorker and must honor ctx cancellation. It receives no device permission decision: stopping is a paired-device action.
type Config ¶
type Config struct {
ServerID identity.ServerID
RelayURL string
BinaryVersion string
Logger *slog.Logger
// AdmissionToken is the selected startup credential: exactly 64 lowercase
// hexadecimal characters, or empty to omit the admission header. It is sent
// unchanged on every upgrade attempt and must never be logged.
AdmissionToken string
// AllowInsecureScheme, when true, lets RelayURL use plain ws:// in
// addition to wss://. Test-only seam so e2e suites can point pyry at
// an httptest-hosted fakerelay over plaintext. Production callers
// leave this false; cmd/pyry flips it only when the operator sets
// PYRY_ALLOW_INSECURE_RELAY=1.
AllowInsecureScheme bool
// ServerIDConflictThreshold overrides the number of CONSECUTIVE 4409
// closes required before Wait returns ErrServerIDConflict. Zero (the
// default) uses the production serverIDConflictThreshold (8). Test-only
// seam so the e2e suite can reach the persistent-conflict → fatal
// shutdown path in a few seconds of backoff instead of the ~91s the
// production threshold takes; cmd/pyry sets it only from
// PYRY_RELAY_4409_THRESHOLD, mirroring the AllowInsecureScheme seam.
ServerIDConflictThreshold int
}
Config carries the static configuration for a Connection. The caller resolves ServerID via internal/identity.LoadOrCreate before constructing Config — the relay package never touches the on-disk store, keeping the net package free of pairing / storage concerns.
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection runs the binary↔relay leg of the wire protocol. Lifecycle is tied to the context passed to Connect; cancellation closes the WS cleanly. Wait blocks until the lifecycle terminates; the returned error is ErrAdmissionFailed for HTTP 401, ErrServerIDConflict for persistent 4409, ctx.Err for graceful shutdown, or a wrapped transport error.
func Connect ¶
func Connect(ctx context.Context, cfg Config) (*Connection, error)
Connect builds the transport, starts the lifecycle goroutine, and returns immediately. The connection is not yet Ready — observe Frames to consume post-handshake inbound frames, or call Wait to block on terminal classification. The caller is responsible for invoking Close during shutdown to release resources; ctx cancellation also drains the lifecycle.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close requests a clean shutdown. Idempotent. After Close, Frames drains and closes; Wait returns.
func (*Connection) CloseConn ¶
func (c *Connection) CloseConn(connID string, code uint16) error
CloseConn asks the relay to close the named phone conn with the given WS close code. Builds a close-only routing envelope (no Frame) with CloseCode set and forwards via the transport. Returns transport.ErrNotConnected when the underlying WS is currently dropped or transport.ErrDisconnected if the live conn drops while Send is blocked (caller decides whether to retry; transport reconnect runs asynchronously). Wire mechanism: docs/protocol-mobile.md § Routing envelope (CloseCode).
CloseConn does NOT block on the relay's close-frame being delivered to the phone — the request is fire-and-forget at this layer. The per-conn close ack is implicit (no more inbound frames will arrive for connID).
The dispatcher's auth-reject path does NOT call CloseConn; instead it publishes one routing envelope carrying both Frame and CloseCode so the error envelope and the close are atomic on the wire. CloseConn is the explicit surface for callers that want close-without-payload (none today; reserved for the idle/inactivity sweep hinted at in #307).
func (*Connection) Connected ¶ added in v0.16.0
func (c *Connection) Connected() bool
Connected reports whether the binary↔relay transport leg currently has a live conn — a level poll of the underlying transport.Client for the v2 push drain's pre-seal probe (V2SessionConfig.Connected, #874). A false result means Send would be dropped, so the drain holds the head unsealed rather than burning a Noise nonce on a frame that cannot reach the phone.
func (*Connection) Frames ¶
func (c *Connection) Frames() <-chan protocol.RoutingEnvelope
Frames returns the channel of inbound frames. The channel closes when the lifecycle terminates. Frames are delivered in the order the underlying conn produces them; reconnects are transparent — frames resume on the new conn directly.
func (*Connection) Reconnected ¶ added in v0.16.0
func (c *Connection) Reconnected() <-chan struct{}
Reconnected returns a channel that emits once per fresh binary↔relay conn (the initial connect and every reconnect). Cap-1 drop-on-full, single observer — the v2 push drain (V2SessionConfig.Reconnect) uses it to flush held control envelopes the instant the leg recovers, without waiting for the next Push (#875). Derived from the connection's own (sole) observation of transport.Client.Connected(); the manager must NOT observe that transport channel directly, which is documented single-observer.
func (*Connection) Send ¶
func (c *Connection) Send(env protocol.RoutingEnvelope) error
Send marshals env to JSON and forwards it to the relay over the current transport conn. Returns transport.ErrDisconnected if the underlying conn is currently dropped (caller decides whether to retry or drop the frame); transport reconnect happens asynchronously, so a frame sent while disconnected is lost — that's consistent with the protocol's connection-lifecycle expectations (docs/protocol-mobile.md § Connection lifecycle).
func (*Connection) SendContext ¶ added in v0.39.0
func (c *Connection) SendContext(ctx context.Context, env protocol.RoutingEnvelope) error
SendContext waits for cancellable, bounded delivery through Send's ordered transport pump. The caller still owns Noise sealing and sender ID order.
func (*Connection) SendPushWake ¶ added in v0.23.0
func (c *Connection) SendPushWake(platform, token string) error
SendPushWake asks the relay to send a platform push to token (#2564). The envelope is relay-addressed and never sealed in a Noise session; the relay is its only reader. Returns the transport sentinels unchanged (ErrNotConnected, ErrDisconnected, ErrClosed) — no error from this method carries the token, and the caller MUST NOT log the token either.
func (*Connection) SendPushWakeFeedback ¶ added in v0.40.2
func (c *Connection) SendPushWakeFeedback(ctx context.Context, platform, token, requestContext string) (<-chan string, error)
SendPushWakeFeedback submits on the current socket and waits for write completion. requestContext is an immutable caller-owned correlation handle or snapshot; it stays local and is never logged or serialized. The returned buffered channel emits it at most once for invalid_token, then closes. A closed channel without a value means retirement, expiry or feedback overflow, never invalidity. Cancellation retires feedback even after this method returns successfully.
func (*Connection) Wait ¶
func (c *Connection) Wait() error
Wait blocks until the lifecycle terminates and returns the terminal classification: ErrAdmissionFailed (HTTP 401), ErrServerIDConflict (persistent 4409), ctx.Err (graceful shutdown), or a wrapped transport error.
type DiagnosticQuestionResolver ¶ added in v0.33.0
type DiagnosticQuestionResolver interface {
QuestionResolver
ResolveAnswerDiagnostic(p protocol.QuestionAnswerPayload, dev *devices.Device) (consumed bool, reason string)
ResolveRefusalDiagnostic(p protocol.QuestionRefusedPayload, dev *devices.Device) (consumed bool, reason string)
}
DiagnosticQuestionResolver optionally extends QuestionResolver with the outcome of the same resolution attempt. The handler calls a diagnostic method INSTEAD OF its bool-only counterpart, never both. Existing configuration wiring and bool-only implementations remain valid.
Each method performs resolution under QuestionResolver's validation, eligibility-before-consume and bounded-time obligations. consumed reports whether it consumed the batch. On non-consumption, reason MUST be a stable, content-free outcome code: never client text, an answer token, a payload value or an error message. On consumption the handler logs "resolved" regardless of reason. Neither result triggers a reply, dismissal or security audit decision.
type HistoryPageOutcome ¶ added in v0.16.0
type HistoryPageOutcome uint8
HistoryPageOutcome discriminates the seam's answers finely enough for the handler to choose a wire code, and no more. internal/history has six sentinels a Page call can reach, but the wire has one code for a bad cursor and one for every other failure.
const ( // HistoryPageOK means the page is the log's answer, including the empty // terminal page of a conversation with no log. It is the zero value, so an // implementation that forgets to set an outcome reports that inert empty page, // never a refusal the client did not earn. HistoryPageOK HistoryPageOutcome = iota // HistoryPageBadCursor is the one client fault: a cursor that does not decode, // was minted for another conversation, or names a position not in this log. // internal/history raises the single ErrInvalidCursor for all three, so the // handler cannot tell them apart. HistoryPageBadCursor // unknown-version segment, a containment refusal, an I/O error, or no log // wired. It is the only retryable outcome. It also covers two refusals that // are unreachable by construction (a non-canonical conversation id, a page // size below one), so a daemon bug reads as a daemon problem rather than as // the client's malformed request. HistoryPageUnavailable )
type HistoryPageResult ¶ added in v0.16.0
type HistoryPageResult struct {
// Entries is the page, newest first, forwarded to the client verbatim. An
// implementation sizes it from what the log returned, never from limit, which
// a remote caller chose (protocol.RequestHistoryPayload.Limit states the rule).
//
// The payloads are replayed content with the trust class of the live frame
// they mirror: claude-authored for an assistant frame, so docs/protocol-mobile.md
// § Security model threat 1 applies. They are forwarded unchanged, not
// re-encoded or sanitised, so the client's live-lane reducer and sanitisation
// handle them.
Entries []protocol.HistoryEntry
// Cursor is the opaque position to ask with next. Empty whenever AtStart.
Cursor string
// AtStart reports that the start of the log was reached while filling this
// page; it is the only signal that ends a walk. It comes from the log and is
// never synthesised, so a page the handler shortened to fit the envelope cap
// cannot forge an end of log.
AtStart bool
// Outcome says whether the three fields above mean anything.
Outcome HistoryPageOutcome
}
HistoryPageResult is one answer from the HistoryPage seam: history.Page's three fields in wire types, plus the outcome. Entries, Cursor and AtStart mean something only when Outcome is HistoryPageOK; otherwise they are zero and the handler answers a reject.
type HistoryPager ¶ added in v0.16.0
type HistoryPager func(conversationID, cursor string, limit int) HistoryPageResult
HistoryPager is the type of the V2SessionConfig.HistoryPage seam, whose field doc carries the contract.
Primitives in, protocol types out: protocol.HistoryEntry mirrors history.Entry key for key (frozen by TestHistoryPagePayload_WireKeys), so returning it keeps that correspondence in one place and internal/relay never imports internal/history. The result is a struct rather than comma-ok because the handler must tell a bad cursor (history.invalid_cursor) from a read failure (history.unavailable); they differ in the retryable flag a client branches on.
type HostedAppsAPI ¶ added in v0.39.0
type HostedAppsAPI interface {
ForwardAPI(context.Context, string, string, string, apps.APIRequest) (*apps.PreparedResponse, error)
}
HostedAppsAPI forwards once to the exact generation and prepares a stable response. Calls and disposal run off Run and must honor cancellation without mutation replay.
type HostedAppsAssets ¶ added in v0.39.0
type HostedAppsAssets interface {
PrepareAsset(context.Context, string, string, string, apps.AssetRequest) (*apps.PreparedResponse, error)
}
HostedAppsAssets prepares stable confined assets bound to the exact backend generation. Calls and disposal run off Run; implementations must honor context cancellation.
type HostedAppsDiscovery ¶ added in v0.39.0
HostedAppsDiscovery returns an atomic detached committed host snapshot. List may block; relay retains its read capacity until it returns.
type InnerFrameV2Decoded ¶ added in v0.14.0
InnerFrameV2Decoded is the post-validation form of an InnerFrameV2: Type matches one of the discriminator constants and Data has been base64-decoded with the size cap enforced.
type Interrupter ¶ added in v0.15.0
Interrupter stops the running turn in one conversation, the remote equivalent of a local Esc (claude's own interrupt). SendEsc is safe to call from any goroutine. cmd/pyry's activeInterrupter is the sole implementation.
conversationID is untrusted: it comes from a paired client and this package validates nothing about it, because every check lives in the composition root. An implementation MUST shape-check it before any use and MUST NOT let it become a path component.
The empty string means the conversation the daemon's cursor points at, which is also what an older client that sends no payload gets. handleInterrupt maps every "nothing named" shape (absent payload or field, explicit "", undecodable body) onto it, so an implementation has one such state to handle.
A returned error is a best-effort diagnostic that the caller only logs. A conversation with no live child returns streamsup.ErrNoLiveChild having written nothing, so the call is inert there.
type LateSessionStarter ¶ added in v0.19.0
type LateSessionStarter interface {
SessionStarter
StartNewSessionLate(conversationID string, outcome func(error))
}
LateSessionStarter is an optional widening of SessionStarter for an implementation whose rotation finishes after the call returns (production first asks the outgoing child for a handoff note, bounded at ninety seconds). handleNewSession uses it when the configured SessionStarter implements it and falls back to StartNewSession otherwise.
It exists because StartNewSession's one meaningful answer, *RotatedWithoutWorkspaceError, may only describe a rotation that has already happened. A deferred rotation reports through outcome once the answer is true.
outcome receives exactly what StartNewSession would have returned, with the same meanings. An implementation MUST call it exactly once, MAY call it after StartNewSessionLate has returned, and MUST NOT call it while holding a lock a caller could hold. outcome runs on the implementation's goroutine, so handleNewSession passes one that only hands the value to Run, where the reply is sealed.
type LiveState ¶ added in v0.39.0
type LiveState struct {
Envelope protocol.Envelope
ConversationID string
SessionGeneration uint64
ReadingID string
Revision uint64
// Answerable is captured prompt eligibility. False withholds prompt shows;
// nil leaves supplied eligibility unspecified.
Answerable *bool
// ModelListUnprojected marks canonical Claude model rows for per-recipient
// MergedModelOptions projection. False preserves provider-projected replies.
ModelListUnprojected bool
}
LiveState binds a detached reading to its source through asynchronous delivery. SessionGeneration increases on every transition, including reuse of a session ID. Revision increases per (conversation, generation, family, ReadingID). Shown/dismissed prompts and session-settings replies share their family. Empty ReadingID names a singleton; prompts and tool/task readings use their IDs. Envelope.SessionID is supplied provenance, never resolved from current binding. InReplyTo may be set for on-demand replies; payload session fields are preserved.
type MCPActuator ¶ added in v0.17.0
type MCPActuator interface {
// Reconnect reconnects the named MCP server in the named conversation. Returns
// the post-acknowledgement status to answer with and true, or the zero payload
// and false for every refusal.
Reconnect(ctx context.Context, p protocol.MCPReconnectPayload, dev *devices.Device) (protocol.MCPStatusPayload, bool)
// SetEnabled moves the named MCP server to p.Enabled in the named conversation.
// It sets the requested value and never flips the current one, which is why it
// is not named for the wire's mcp_toggle. Same two-way answer as Reconnect.
SetEnabled(ctx context.Context, p protocol.MCPTogglePayload, dev *devices.Device) (protocol.MCPStatusPayload, bool)
}
MCPActuator performs one inbound mcp_reconnect or mcp_toggle against one conversation's live claude child. dev is the conn's authenticated device.
Both methods run on the addressed conn's appFrameWorker, not Run, because a live implementation waits for a child round trip. An implementation MUST honor ctx so manager shutdown ends that wait, and MUST NOT touch V2Session or Noise state; replies return through forwardToRun for Run-owned sealing.
On true, the returned status MUST be one read after the child acknowledged the actuation, which only the implementation can do; the relay does not call MCPStatusFor on this path. true with an empty Servers is a real answer. false means refused for any reason, a caller MUST NOT read the payload, and the relay answers every false with protocol.CodeMCPActuationRefused.
The relay applies no authorization and must not grow any. The implementation is the per-device actuation gate and records its decision through internal/audit, so the denial and its record stay in one place. A gate denial returns at once while a real actuation waits for the child, so the merged refusal does not hide timing; the relay cannot close that.
Security: what crosses this seam is remote-authored.
- ConversationID has passed KnownConversation. It stays a lookup key: never returned as the answer's ConversationID, logged, or joined into a path.
- ServerName has passed no validation anywhere; the implementation is its sole validator. It MUST be shape-checked before use and MUST NOT become a path component or reach a shell. Only the transport's AEAD frame cap bounds it.
- Every string in the returned payload is claude-authored and is never logged.
type ModalDismissal ¶ added in v0.15.0
type ModalDismissal struct {
Outcome string // e.g. "cancelled" (cancel); #717 uses the answered option_id
Source string // closed set {remote, local, timeout}; cancel ⇒ "remote"
}
ModalDismissal is the wire outcome+source the manager broadcasts after a resolver consumes an outstanding modal. The manager already holds modal_id (from the inbound control payload), so it is not repeated here.
type ModalResolver ¶ added in v0.15.0
type ModalResolver interface {
// ResolveCancel consumes modalID (registry Resolve), routes a cancel/ESC
// keystroke, audits outcome=cancelled, and returns the dismissal to
// broadcast with ok=true. An unknown/already-resolved id ⇒ (zero, false):
// no keystroke, no audit, no dismissal.
ResolveCancel(modalID string, dev *devices.Device) (ModalDismissal, bool)
// ResolveAnswerWithAlwaysAllow resolves an inbound modal_answer. The Boolean
// is only a request to use daemon-retained rules; implementations must still
// authorize the device, classify an allow option, and consume the modal once.
ResolveAnswerWithAlwaysAllow(modalID, optionID, answerToken string, alwaysAllow bool, dev *devices.Device) (ModalDismissal, bool)
}
ModalResolver resolves an inbound modal control frame against the daemon's outstanding-modal state; the cmd/pyry resolver satisfies it. dev is the conn's authenticated device. Both methods run on the manager's Run goroutine, so they MUST return in bounded time.
type PairingMintOutcome ¶ added in v0.16.0
type PairingMintOutcome uint8
PairingMintOutcome discriminates the seam's answers finely enough for the handler to choose a wire code, and no more. A busy lock, a registry read or write failure and an RNG failure share protocol.CodePairingUnavailable, so they share one outcome.
const ( // PairingMintOK means a record was written and Pairing carries the // credential. It is deliberately not the zero value: a forgotten outcome must // deny, not report a mint with an empty credential. PairingMintOK PairingMintOutcome = iota + 1 // not, or no longer does, carry devices.Device.AllowRemotePermissions. An // implementation MUST reach it without writing a record, so a refusal leaves // the registry untouched. PairingMintUnauthorized // PairingMintFailed is every host-side failure: a devices.json lock not // acquired, a registry not read or written, or a CSPRNG that refused. It is // the only retryable outcome. PairingMintFailed )
type PairingMintResult ¶ added in v0.16.0
type PairingMintResult struct {
// Pairing is the pair.Encode string ({server, relay, token,
// server_static_pubkey} as base64url), byte for byte what `pyry pair` prints.
// It is a plaintext bearer credential: never logged, nothing decoded from it
// logged, and its only egress is the AEAD-sealed pairing_minted reply unicast
// to the conn that asked. Empty unless Outcome is PairingMintOK.
Pairing string
// Outcome says whether Pairing means anything.
Outcome PairingMintOutcome
}
PairingMintResult is one answer from the PairingMinter seam. It carries an outcome rather than an error because every mint error wraps the absolute devices.json path, which must not reach the handler; the error ends in the implementation. There are two refusal outcomes because they differ in the retryable flag a client branches on.
type PairingMinter ¶ added in v0.16.0
type PairingMinter interface {
// MintPairing mints one pairing for a new device and returns it encoded, or
// says why it did not. deviceName is the label for the record. An empty
// deviceName means the client named none, and the implementation uses the
// same device-<hash8> fallback `pyry pair` does, so both entry points produce
// indistinguishable records.
MintPairing(requester *devices.Device, deviceName string) PairingMintResult
}
PairingMinter mints a pairing for another device on behalf of an already-paired one, so internal/relay holds none of the minting machinery (randomness, pairing encoding, keys, audit). requester is the conn's authenticated device. cmd/pyry's resolver is the sole production implementation.
The implementation makes the authorization decision and records it through internal/audit, so the denial and its record cannot drift apart. The handler applies no privilege check and MUST NOT grow one.
It runs on the conn's appFrameWorker, not Run, so it may take a file lock and write devices.json. It still stalls that conn's later frames, so it MUST return in bounded time; production bounds its lock wait explicitly.
Security:
- deviceName is remote-authored and already shape-checked: bounded by protocol.MaxDeviceNameBytes at decode, with no C0, DEL or C1 control (mintLabelIsDisplaySafe), and valid UTF-8 because encoding/json guarantees it. That makes it safe to store, log and show in `pyry pair list`. An implementation MUST NOT re-derive the name from anywhere else and MUST NOT let it become a path component.
- The minted device is always unprivileged. MintPairingPayload has no field for devices.Device.AllowRemotePermissions, and an implementation MUST pass a literal false. A stolen privileged pairing must never mint a device that can itself mint or actuate MCP servers.
- requester is the only identity: the per-conn device bound at handshake. No request field names a device. A nil requester MUST be denied (devices.Device.MayAnswerRemotePermission is nil-receiver-safe).
type QuestionResolver ¶ added in v0.16.0
type QuestionResolver interface {
// ResolveAnswer resolves an inbound question_answer against the daemon's
// parked batch. Returns true iff it consumed an outstanding batch; an unknown
// or already-resolved question_batch_id is a safe no-op (false), the modal
// seam's unknown-id posture.
ResolveAnswer(p protocol.QuestionAnswerPayload, dev *devices.Device) bool
// ResolveRefusal resolves an inbound question_refused: the operator declined
// to choose, so the batch resolves with no selection. Same report and same
// no-op posture as ResolveAnswer.
ResolveRefusal(p protocol.QuestionRefusedPayload, dev *devices.Device) bool
}
QuestionResolver resolves an inbound question_answer or question_refused frame against the daemon's outstanding clarifying-question batches. dev is the conn's authenticated device. Both methods run on the manager's Run goroutine and MUST return in bounded time. The typed payload crosses whole because QuestionAnswerPayload nests an array of entries.
The bool reports whether the batch was consumed, and the handler uses it only to pick a content-free log reason. The relay MUST NOT broadcast question_dismissed on it: cmd/pyry's streamApprovalBridge.retireQuestion is that frame's sole broadcaster.
The relay applies no authorization, so the implementation is the answer gate: it MUST deny an ineligible device before consuming anything. The payload is remote-authored and only decoded, so the implementation also owes the checks QuestionAnswerEntry's doc names:
- QuestionIndex is not range-checked. Indexing the parked batch with it unchecked can panic, and any paired client picks the index.
- Indices may repeat or be missing; neither a partial nor a last-write-wins answer is acceptable.
- Answers may be arbitrarily long, bounded only by the transport's AEAD frame cap, so per-frame work must not grow unbounded with entry count.
- Nothing from the payload is logged beyond question_batch_id and answer_token; the values are client-authored free text.
type QueueRemover ¶ added in v0.15.0
QueueRemover drops a not-yet-drained queued message from a conversation's inbound backlog by id; *msgqueue.Queue satisfies it. Remove returns true iff a message was removed. An unknown or foreign conversation, an unknown or already-delivered id, or the draining head is a safe no-op (false). conversationID is the mutation scope: Remove never touches another conversation's backlog.
type QueueSender ¶ added in v0.31.0
QueueSender writes a queued message into the conversation's running turn instead of waiting for idle; *msgqueue.Queue satisfies it. SendNow returns true iff the message was written. Every refusal (idle turn, unknown id, committing head, a session that cannot take input mid-turn, a failed write) is a safe no-op (false) that leaves the backlog as it was. conversationID is the mutation scope, as for QueueRemover.
type RotatedWithoutWorkspaceError ¶ added in v0.19.0
type RotatedWithoutWorkspaceError struct {
// ConversationID is the conversation that rotated: the one the frame named, or
// the daemon's cursor conversation when it named none.
ConversationID string
}
RotatedWithoutWorkspaceError is what a SessionStarter returns when a rotation completed but the conversation's recorded workspace was refused, so the successor child runs in the directory the runner already had. handleNewSession answers it with one coded error reply to the conn that asked, correlated by in_reply_to. Callers match it with errors.As.
It is not a failure: by the time it exists the pool is re-keyed, the conversation rebound and the session_transition broadcast. An implementation MUST NOT return it when the rotation itself failed. It is a type rather than a sentinel because the reply must name the conversation, and a bare new_session names none.
Security: ConversationID is daemon-resolved (it passed conversations.ValidID, or it is the daemon's cursor id), never the raw client string and never a path. Error returns a constant that names neither the id nor the workspace path, because handleNewSession's other arm logs seam errors verbatim. The confinement error behind the refusal is discarded in cmd/pyry and never reaches this value.
func (*RotatedWithoutWorkspaceError) Error ¶ added in v0.19.0
func (e *RotatedWithoutWorkspaceError) Error() string
Error returns a constant message; see the type doc's security note.
type RunConfig ¶ added in v0.16.0
type RunConfig struct {
SessionID string
Model string
Effort string
YOLO bool
PermissionMode string
UsedTokens int
WindowTokens int
}
RunConfig is one conversation's run configuration as the daemon reports it: the session the conversation is bound to, that session's model, effort, YOLO and permission mode, and its context-window occupancy. It is the value half of V2SessionConfig.RunConfigFor and carries primitives only.
Every field describes SessionID: the cmd/pyry producer resolves the id and reads the settings under one pool acquisition, so no field can describe another session, even across a concurrent idle eviction.
An empty Model or Effort is a real value (the inherited daemon default) and YOLO false means permissions are enforced, so the zero RunConfig is indistinguishable from an all-defaults session. "Not addressable" is therefore RunConfigFor's comma-ok, never a field.
PermissionMode is different: a resolved RunConfig always names one of claude's six modes, so "" appears only in a refusal's zero value. It always agrees with YOLO, so a bypass session reports "bypassPermissions" here and YOLO true, a mode the write path refuses on its own mode field.
type SessionStarter ¶ added in v0.16.0
SessionStarter starts a fresh session in one conversation. StartNewSession is safe to call from any goroutine. cmd/pyry's activeSessionStarter is the production implementation.
conversationID is untrusted, with Interrupter's obligations: an implementation MUST shape-check it before any use and MUST NOT let it become a path component. The empty string means the daemon's cursor conversation, and handleNewSession maps every "nothing named" wire shape onto it, as handleInterrupt does.
A *RotatedWithoutWorkspaceError reports a rotation that completed with one caveat, and handleNewSession checks for it before its logging arm. Any other non-nil error means the rotation did not happen; the caller logs it and owes no reply.
type SettingsUpdate ¶ added in v0.16.0
type SettingsUpdate struct {
Model *string
Effort *string
YOLO *bool
// PermissionMode names the posture to switch to, mirroring
// sessions.SettingsUpdate.PermissionMode. handleSetSessionSettings has already
// checked it against validPermissionMode, so a non-nil value is one of claude's
// five non-escalating modes, never "" or bypassPermissions. The escalation
// travels only as YOLO, which keeps the bypass fail-safe to a single bit.
PermissionMode *string
}
SettingsUpdate is the presence contract for an inbound set_session_settings change: a nil field leaves the stored value untouched and a non-nil field sets it, including *"" for Model or Effort and *false for YOLO. It mirrors sessions.SettingsUpdate field for field, so the cmd/pyry adapter passes the pointers straight through. An absent YOLO leaves the stored value alone, so it can never enable --dangerously-skip-permissions.
type SettingsUpdater ¶ added in v0.16.0
type SettingsUpdater interface {
UpdateSettings(sessionID string, update SettingsUpdate) error
}
SettingsUpdater persists a per-session settings change named by an inbound set_session_settings frame; the cmd/pyry adapter wraps *sessions.Pool.UpdateSettings. UpdateSettings returns ErrSessionUnknown for a session the daemon does not host, which the handler answers with session.not_found. ErrModelNotOffered, ErrModelVocabularyUnavailable and ErrEffortNotOffered are validation outcomes returned before any mutation. Any other error is a persistence failure, reported as server-unavailable.
type ThreadView ¶ added in v0.41.0
type ThreadView uint8
ThreadView is one conn's recorded projection for one conversation.
const ( // ThreadViewUnjoined means no items query has completed for the conversation // on this conn. Compact updates are withheld from it. ThreadViewUnjoined ThreadView = iota // ThreadViewComplete selects complete thread item updates. ThreadViewComplete // ThreadViewCompact selects thread_compact_update. ThreadViewCompact )
type V2Session ¶ added in v0.14.0
type V2Session struct {
// contains filtered or unexported fields
}
V2Session is the per-conn_id state held by V2SessionManager. Mutation is serialised by the manager's single dispatch goroutine (the loop is the lock); there is no mutex because flynn/noise's CipherStates are not safe for concurrent use and the manager guarantees a single writer per conn_id. Rekey installs receive keys on Run; hosted send keys change at the ordered noise_resp barrier after old-key output drains. Old CipherState pointers become unreachable after that transition.
func (*V2Session) State ¶ added in v0.14.0
func (s *V2Session) State() V2SessionState
State returns the externally-observable state. Called from the same goroutine that mutates today; a cross-goroutine reader (e.g. a broadcast layer added in a later slice) would need atomic.Int32 or a small mutex — tracked in spec § Open questions.
type V2SessionConfig ¶ added in v0.14.0
type V2SessionConfig struct {
// HostedAppsAssets supplies generation-bound confined assets off Run.
// Nil returns app.unavailable; it does not activate production readiness.
HostedAppsAssets HostedAppsAssets
// HostedAppsAPI supplies generation-bound once-only API forwarding off Run.
HostedAppsAPI HostedAppsAPI
// HostedAppsDiscovery supplies committed registrations for this authenticated host.
// Nil disables hosted capability admission.
HostedAppsDiscovery HostedAppsDiscovery
// HostedAppsReady attests complete registration, supervision and resource routing.
// It must be nonblocking. Nil/false keeps production capability disabled.
HostedAppsReady func() bool
// HostedAppsSend provides ordered cancellable delivery for hosted connections.
// It must honor cancellation/deadlines and never publish cancelled work. Nil
// withholds the capability: context-free Outbound cannot promise retirement.
HostedAppsSend func(context.Context, protocol.RoutingEnvelope) error
// ThreadCatchUp returns a detached authoritative query result off Run and must
// honor cancellation. Nil explicitly fails catch-up; it never loads history.
ThreadCatchUp func(context.Context, protocol.ThreadCatchUpPayload) (thread.QueryResult, error)
// ThreadPage returns one detached authoritative older page off Run and must
// honor cancellation. Nil explicitly fails pages; it never loads history.
ThreadPage func(context.Context, protocol.ThreadPagePayload) (thread.QueryResult, error)
// ThreadToolBody returns one detached captured public tool/agent body in the
// requested conversation. It must honor cancellation and enforce public
// ownership and current epoch/revision. Nil refuses reads.
ThreadToolBody func(context.Context, protocol.ThreadExpansionRequest) (thread.ToolBodyResult, error)
// ThreadChildren returns detached direct summaries off Run. It must honor
// cancellation and enforce current epoch/revision/version and public parent
// and cursor membership in the requested conversation. Both expansion
// providers are required for negotiation; neither may fall back to another scope.
ThreadChildren func(context.Context, protocol.ThreadExpansionRequest) (thread.ChildPageResult, error)
// ThreadCompactCatchUp returns a detached compact newest window (version zero)
// or catch-up interval off Run and must honor cancellation. ThreadCompactPage
// returns one detached compact older page. Neither may fall back to complete
// rows. Both, plus a true ThreadCompactReady, are required to grant
// thread_compact; nil withholds it and refuses compact requests.
ThreadCompactCatchUp func(context.Context, protocol.ThreadCatchUpPayload) (thread.CompactQueryResult, error)
ThreadCompactPage func(context.Context, protocol.ThreadPagePayload) (thread.CompactQueryResult, error)
// ThreadCompactReady must be nonblocking and attest installed compact query
// and live publication. Nil/false keeps compact withheld.
ThreadCompactReady func() bool
// ThreadLiveState returns a detached current-state cursor, including inactive
// retry/compaction and only outstanding prompts/questions with answer IDs.
// Factory and cursor run on Run and must be nonblocking, hold no resources
// needing closure, and never consult replay. Each cursor call yields one
// source-bound reading; false ends it. Nil supplies no readings.
ThreadLiveState func() func() (LiveState, bool)
// LiveStateCurrent checks unsolicited captures immediately before Run delivery.
// It must be a bounded memory read; correlated replies keep captured evidence.
LiveStateCurrent func(LiveState) bool
// ThreadReady must attest installation of live publication, authoritative
// watermark lookup and session-state reconciliation. Nil/false disables thread;
// production must leave it unset until all three providers are installed.
ThreadReady func() bool
// ThreadLastShownVersion returns only an authoritative usable reading. False
// covers missing, rebuilding and unavailable state; zero with true is usable.
ThreadLastShownVersion func(conversationID string) (uint64, bool)
// WorkspaceBase is a caller-resolved base advertised only to admitted peers
// in the encrypted hello_ack. Nil uses WorkspaceRoot(); a supplied absolute
// value is reported verbatim, while empty or relative values omit the key
// without fallback. Advertisement performs no filesystem access. The caller
// must not mutate the pointed-to value while the manager runs.
WorkspaceBase *string
// Frames is the inbound RoutingEnvelope stream from a relay.Connection (or an
// in-memory channel in tests). Required. Run consumes it until it closes or
// ctx is done.
Frames <-chan protocol.RoutingEnvelope
// Outbound sends one RoutingEnvelope to the relay; production passes
// (*relay.Connection).Send. Required. An error is logged at debug and
// dropped, because the relay leg's reconnect handles recovery.
Outbound func(protocol.RoutingEnvelope) error
// OutboundContext is the cancellable transport path for hosted controls when
// HostedAppsSend is absent, including unsupported replies and terminal closes.
// It must return on cancellation/deadline without publishing cancelled work.
// Nil with no HostedAppsSend retires hosted work before sealing; Outbound
// cannot safely deliver it. This transport seam does not enable discovery.
OutboundContext func(context.Context, protocol.RoutingEnvelope) error
// Connected reports whether the relay transport leg is up. drainOnce consults
// it before sealing a queued envelope: false leaves the head unpopped and
// unsealed, so no Noise send nonce is burned on a frame that cannot arrive (a
// burned nonce gaps the phone's receive nonce and closes a live session with
// 4421). true is best effort, since the conn may drop between the poll and the
// send. It decides only when a seal happens, so it is not a security decision.
// Optional: nil means always connected and the drain never holds. Production
// wires (*relay.Connection).Connected.
Connected func() bool
// Reconnect fires once per fresh relay transport conn (edge-triggered, cap 1,
// drop on full, single observer). Run then re-signals the push drain so an
// envelope held while the leg was down flushes at once. It only wakes the
// drain; drainOnce still consults Connected before popping. Optional: nil is a
// channel that is never ready, so the drain wakes only on Push. Production
// wires (*relay.Connection).Reconnected.
Reconnect <-chan struct{}
// RekeyInterval overrides the scheduled re-key cadence read by armRekeyTimer.
// Optional: zero uses rekeyInterval (1h). It exists for e2e tests, which
// cannot reach this package's unexported timing vars; production leaves it
// zero, and it is never sourced from the wire, a file or operator input. A
// smaller value only rotates keys more often; it touches no key material, pin
// or AEAD.
RekeyInterval time.Duration
// RekeyReplyTimeout overrides how long armRekeyReplyTimer waits for the
// phone's fresh noise_init after a rekey_request before tearing the session
// down. Optional: zero uses rekeyReplyTimeout (30s). Test-only, like
// RekeyInterval.
RekeyReplyTimeout time.Duration
// MinClientVersions holds the minimum app version, as MAJOR.MINOR.PATCH,
// keyed by the app name a hello's client_version carries. Once any entry is
// non-empty, a hello whose token is accepted but whose client_version is
// unparsable, or below its app's minimum, is refused with
// client.update_required and close 4412. Optional: nil or an empty value means
// no minimum for that app. NewV2SessionManager errors on a value that does not
// parse. Production passes ShippedMinClientVersions(); tests pass their own
// map. Never sourced from the wire or operator input.
MinClientVersions map[string]string
// RekeyRetryInterval overrides the re-arm cadence armRekeyRetryTimer uses
// when a scheduled re-key fires while the relay leg is down. Optional: zero
// uses rekeyRetryInterval (1m). Test-only, like RekeyInterval.
RekeyRetryInterval time.Duration
// StaticPriv is the binary's 32-byte X25519 static private key. Required; see
// the type doc's security note.
StaticPriv []byte
// Devices validates hello.Token. Required.
Devices *devices.Registry
// DevicesPath is the on-disk devices.json. Each handshake reloads Devices from
// it before validating the token, so a device paired with `pyry pair` after
// startup is accepted without a restart (ADR 029). The handshake also records
// first redemption and the reported client version there. Optional: ""
// disables the reload and both writes. A reload read error keeps the
// in-memory set, which neither widens the accepted set nor loses devices.
DevicesPath string
// ServerID is surfaced in the hello_ack early-data payload. Required.
ServerID string
// Logger receives lifecycle and reject events. Required. Tokens, key bytes,
// payload bytes, AEAD ciphertext and their base64 forms MUST NOT appear in any
// logged field.
Logger *slog.Logger
// Handlers maps an application envelope type to its handler for open-state
// dispatch through dispatch.Route. Optional: nil or empty means every such
// envelope gets a sealed protocol.unsupported reply.
//
// Security: handlers run on the addressed conn's appFrameWorker, one frame at
// a time, so a handler MUST return in bounded time (bound long waits with a
// ctx timeout) or it stalls that conn's later frames. A handler MUST NOT touch
// Noise or session state; every reply is sealed on Run (forwardAppReply),
// keeping the send CipherState single-owner. A handler MUST NOT keep the
// *dispatch.Conn in a goroutine that outlives it. Send waits for Run to process
// the reply, including ordered plaintext admission, before it returns; it does
// not wait for peer receipt. Session teardown or cancellation ends the wait.
Handlers map[string]dispatch.Handler
// KnownConversation reports whether conversationID names a conversation this
// daemon hosts. The handlers for request_snapshot, request_history,
// request_attachment, attachment_chunk, read_workspace_file,
// request_model_list, request_context_usage, mcp_status_request and the MCP
// actuation verbs consult it before calling their seam and refuse an unknown
// id. It checks membership only, so a known but unbound conversation
// passes; request_session_settings resolves through RunConfigFor instead.
// Optional: nil reads every id as unknown. Production scans the conversations
// registry under its mutex.
KnownConversation func(conversationID string) bool
// CodexConversation reports whether conversationID's bound session runs
// Codex. forwardEnvelope consults it (withheldFromConn) on Run, per frame to a
// conn that did not negotiate protocol.CapabilityMultiAgent, and withholds
// every pushed frame about such a conversation from that conn. Production
// takes a conversations-registry lookup plus sessions.Pool.HarnessFor. An
// unknown conversation, one with no bound session and a harness miss all
// report false. Optional: nil means no conversation is Codex.
CodexConversation func(conversationID string) bool
// ConversationAgent returns conversationID's agent (protocol.AgentClaude or
// protocol.AgentCodex) by the rule list_conversations tags rows with; ok is
// false for a conversation it does not know. forwardEnvelope and
// forwardAppReply consult it (agentTaggedForConn) on Run for each
// conversation_updated sealed for a multi_agent conn. Optional: nil delivers
// every conversation_updated without an agent.
ConversationAgent func(conversationID string) (agent string, ok bool)
// MergedModelOptions returns, for a pushed model_list's Claude entries, the
// list a multi_agent conn receives instead: those entries tagged as Claude's,
// then the daemon's Codex entries, tagged as ModelListFor's replies tag them.
// forwardEnvelope consults it (mergedForConn) on Run for each pushed
// model_list, live or replayed, to such a conn; request replies and the
// connect-time reconcile are already merged and never reach it. It must
// return a slice it owns and never write through its argument. Optional: nil
// delivers every pushed model_list unchanged.
MergedModelOptions func(claude []protocol.ModelOption) []protocol.ModelOption
// HistoryPage serves one backward step of a conversation-history walk over
// the daemon's durable log, for an inbound request_history.
// handleRequestHistory is its sole caller, on the conn's appFrameWorker,
// which is why it may read files; it still stalls that conn's later frames,
// so it MUST return in bounded time. Optional: nil consumes the frame inertly,
// with no reply and no byte of the payload parsed.
//
// conversationID has already passed KnownConversation; the caller owes that,
// because the id becomes a path component below this seam. cursor is passed
// through unparsed: the wire declares it opaque, history.parseCursor is its
// only validator, and nothing in internal/relay may decode, log or branch on
// it. limit arrives positive and capped at maxHistoryPageEntries; never size a
// buffer from it (see HistoryPageResult.Entries).
HistoryPage HistoryPager
// RunConfigFor reports the named conversation's run configuration as one
// RunConfig describing one session. It is the legacy run-configuration source
// for handleRequestSessionSettings, so a client learns about the conversation it is
// in, never the shared bootstrap session.
//
// false means the conversation is not addressable (unknown, bound to nothing,
// or bound to a session the pool no longer holds), and the RunConfig MUST NOT
// be read. true with an empty Model or Effort is a real answer (see
// RunConfig). Optional: nil resolves no conversation.
//
// Security: conversationID is untrusted and stays a lookup key: never
// returned, joined into a path, logged or wrapped into an error. The reported
// session id comes from the daemon's registry record and the producer confirms
// the pool holds it, so an unresolvable conversation addresses nothing. That
// id is a routing key, not a secret. The seam is read-only; only
// SettingsUpdater writes.
RunConfigFor func(conversationID string) (RunConfig, bool)
// Supplied reading providers replace their legacy counterparts only on thread
// connections. Each returns source evidence captured with the reading, never
// reconstructed from a current binding. False results must not be inspected or
// retried through a legacy provider. Context/MCP queries must honor ctx and
// retain their existing bounded asynchronous admission.
ContextUsageReadingFor func(ctx context.Context, conversationID string) (LiveState, bool)
MCPStatusReadingFor func(ctx context.Context, conversationID string) (LiveState, bool)
// ModelListReadingFor must be a bounded in-memory read. multiAgent selects the
// same inventory availability/projection as ModelListFor. A reading marked
// ModelListUnprojected defers capability projection to relay delivery.
ModelListReadingFor func(conversationID string, multiAgent bool) (LiveState, bool)
// SessionSettingsReadingFor supplies the base session_settings payload. Relay
// enriches it once with EffectiveEffortFor, CapabilitiesFor and MemorySearchFor,
// using the supplied conversation and payload session/model keys. It must be a
// bounded read; unavailable results retain the zero-valued no-session reply.
SessionSettingsReadingFor func(conversationID string) (LiveState, bool)
// UpdateSettingsReading performs one atomic update and returns its success
// reading together with captured source evidence. It has SettingsUpdater's
// validation, bounded-operation and error contracts; errors emit no reading.
UpdateSettingsReading func(sessionID string, update SettingsUpdate) (LiveState, error)
// EffectiveEffortFor reports claude's applied effort for the named
// conversation's current child. handleRequestSessionSettings calls it once per
// request, only after RunConfigFor accepted the same conversation, and never
// uses it for the saved Effort or any other RunConfig field.
//
// A non-nil pointer is a confirmed string; nil with true is a confirmed JSON
// null (claude reported no effort). false means no current reading, and the
// pointer MUST then be ignored. Optional: nil omits effective_effort and keeps
// every saved field. It runs on the conn's appFrameWorker because it may wait
// on a child round trip, and it MUST honor ctx. The relay caches nothing.
EffectiveEffortFor func(ctx context.Context, conversationID string) (*string, bool)
// MemorySearchFor supplies a wire-ready search-access report for the named
// conversation and the session ID accepted by RunConfigFor. The handler calls
// it once per fully decoded, resolved settings request; it retains no result.
// An error produces an unknown report with no providers. Optional: nil omits
// memory_search. This runs on the conn's app-frame worker and must honor ctx.
MemorySearchFor func(ctx context.Context, conversationID, sessionID string) (protocol.MemorySearchReport, error)
// CapabilitiesFor reports the agent-and-model half of a session's capability
// list for a multi_agent conn's session_settings reply.
// handleRequestSessionSettings calls it once, after RunConfigFor accepted,
// with that RunConfig's SessionID and Model, never the client's conversation
// id. false means no session with a known agent, and the reply carries no
// capability object. The relay adds the permission modes and attachment types
// and drops any value its own shape checks refuse. The lists must come from
// the code the set_session_settings checks run, so every listed option is
// accepted. Runs on the conn's app-frame worker. Optional: nil omits the
// object.
CapabilitiesFor func(sessionID, model string) (AgentCapabilities, bool)
// ModelListFor reports the named conversation's model menu as a marshal-ready
// model_list payload, for an inbound request_model_list.
// handleRequestModelList is its sole caller, after KnownConversation accepted
// the id. It is keyed by conversation, unlike the RetainedModelLists
// enumerator, which must not be used here. Which vocabulary answers (a bound
// session's retained list, else the daemon-wide copy) is the cmd/pyry
// resolver's decision.
//
// false means no menu exists, and the handler sends a coded error frame; a
// caller MUST NOT read the payload then. An empty Models never stands for
// unknown (turnevent.ModelList.Models is never empty). Optional: nil answers
// every hosted request with the same retryable model_list.unavailable a
// refusal gets, so the reply does not reveal whether the source is wired.
//
// multiAgent is the asking conn's negotiated multi_agent decision: true asks
// for the merged list of both agents' entries, tagged with agent and family;
// false asks for the Claude-only list.
//
// Security: conversationID stays a lookup key: never returned, joined into a
// path or wrapped into an error, and the payload's conversation_id comes from
// the registry record. Payloads arrive bounded at construction
// (ModelListPayload.DroppedModels, ModelOption.TruncatedFields); this seam
// adds no second cap. The text is claude-authored and never logged here.
//
// It runs inline on Run, so it MUST stay a bounded in-memory read (production:
// a registry lookup and at most ten model rows). Moving a slower
// implementation off Run means switching the handler's emit from
// forwardEnvelope to forwardToRun in the same change.
ModelListFor func(conversationID string, multiAgent bool) (protocol.ModelListPayload, bool)
// MCPStatusFor reports one hosted conversation's current MCP server status as
// an mcp_status payload. handleMCPStatusRequest is its sole caller, after the
// payload decodes, the conn has negotiated interactive and KnownConversation
// accepts the id. The id stays an untrusted lookup key: never logged, joined
// into a path or returned as the answer's ConversationID. Every string in the
// payload is claude-authored and never logged.
//
// true with no servers is a current empty snapshot. false means no current
// status: a caller MUST NOT read the payload, and the relay replies retryable
// mcp_status.unavailable without falling back to a retained or empty frame.
// Optional: nil consumes the frame inertly, before decode, membership or
// reply.
//
// It runs on the conn's appFrameWorker because a live implementation waits
// for a child round trip, and it MUST honor ctx. Replies return through
// forwardToRun; an implementation never touches V2Session or Noise state.
MCPStatusFor func(ctx context.Context, conversationID string) (protocol.MCPStatusPayload, bool)
// ContextUsageFor reports one hosted conversation's context-window breakdown
// as a context_usage payload, for an inbound request_context_usage.
// handleRequestContextUsage is its sole caller, after KnownConversation
// accepted the id. Same shape as MCPStatusFor.
//
// A fresh reading is expensive: the implementation asks claude at detail
// "full", a token-count call per category, where the automatic post-turn frame
// carries the cheap "summary". The detail is the implementation's choice and
// is not in the request. The implementation may defer a mid-turn request
// until the turn ends and then wait on a child round trip; the relay bounds
// neither wait, so it MUST honor ctx. Asks close together are collapsed per
// conversation below this seam, so a caller must not assume its own ask caused
// the round trip it is answered from.
//
// true means a reading to show, not necessarily a fresh one. When none can be
// taken (no bound session, no live child, no answer) an implementation MAY
// return a stored reading, and then MUST set ContextUsagePayload.AsOf: a
// stored reading has empty inventories, which without AsOf would read as
// claude reporting none. A fresh reading omits AsOf; the relay neither sets
// nor inspects it. false means no reading: a caller MUST NOT read the payload,
// and the relay replies retryable context_usage.unavailable with nothing of
// its own, since an all-zero payload is indistinguishable from an empty
// context. Optional: nil consumes the frame inertly, before decode, membership
// or reply.
//
// Security: conversationID stays a lookup key: never returned, joined into a
// path, logged or wrapped into an error. The payload's ConversationID is
// daemon-authored; every other string is claude- or workspace-authored,
// including memory-file paths from the operator's filesystem. None of it is
// logged, and it reaches the wire only in the unicast, AEAD-sealed reply.
//
// It runs on the conn's appFrameWorker, not Run, for the waits above, and
// MUST NOT touch V2Session or Noise state; replies return through
// forwardToRun.
ContextUsageFor func(ctx context.Context, conversationID string) (protocol.ContextUsagePayload, bool)
// MCPActuator performs inbound mcp_reconnect and mcp_toggle against a
// conversation's live child; handleMCPReconnect and handleMCPToggle are its
// callers. The MCPActuator type doc carries the contract, including that the
// implementation is the per-device authorization gate. Optional: nil consumes
// both frames inertly, with no reply and no byte of the payload parsed.
//
// Leave it unset or assign a non-nil implementation. A typed nil pointer makes
// the field non-nil, so the frame is admitted and the handler calls a method
// on a nil pointer; internal/relay has no recover(), so that is a
// remote-triggerable crash.
MCPActuator MCPActuator
// SystemPromptFor reports the named conversation's stored system prompt and
// how the running session's spawned-with prompt compares to it, as a
// marshal-ready system_prompt payload, for an inbound request_system_prompt.
// handleRequestSystemPrompt is its sole caller.
//
// The comparison matters because a stored prompt takes effect only at the
// next session start. It is computed on the collapsed stored value: the
// registry stores nil, "" or text, and Pool.SystemPromptFor returns "" for
// both no-text states, so an explicitly empty stored prompt matches a session
// spawned with no operator text. The cmd/pyry producer owns that rule; this
// package does not re-derive it.
//
// false means the daemon does not host the conversation, and a caller MUST NOT
// read the payload. A hosted conversation with no running session is true,
// with SessionPromptStatus protocol.SystemPromptStatusNoSession and the stored
// value still reported. On false the handler answers the constant no-session
// reply, so the verb is not a membership oracle. Optional: nil answers every
// request with that same reply, never an error or a drop.
//
// It runs inline on Run, so it MUST stay a bounded in-memory read (production:
// a registry lookup and one pool map read). Moving a slower implementation off
// Run means switching the handler's emit from forwardEnvelope to forwardToRun.
//
// Security: conversationID stays a lookup key: never returned, joined into a
// path, logged or wrapped into an error. The session id the producer reads
// under comes from the resolved registry record, so a caller cannot reach
// another conversation's session. The prompt is operator-authored text that
// becomes standing instructions to claude: never logged, and sent only in the
// unicast, AEAD-sealed reply, never on the broadcast push path. The seam is
// read-only and can start, restart, rotate or interrupt nothing; do not widen
// it.
SystemPromptFor func(conversationID string) (protocol.SystemPromptPayload, bool)
// PairingMint mints a pairing for another device on behalf of the conn's
// authenticated one, for an inbound mint_pairing; handleMintPairing is its
// sole caller. The PairingMinter type doc carries the contract. Optional: nil
// consumes the frame inertly, with no reply and no byte of the payload parsed.
//
// Security: this is the only seam that mints a credential. The returned
// bearer token reaches only the AEAD-sealed pairing_minted reply unicast to
// the conn that asked; it is never logged, broadcast or wrapped into an error.
// Wiring it deliberately widens docs/protocol-mobile.md § Security model
// threat 4: any privileged paired device can mint, bounded by the minted
// device being unprivileged and an unredeemed token expiring at
// devices.RedemptionWindow.
PairingMint PairingMinter
// ModalResolver resolves inbound modal_answer and modal_cancel frames.
// Optional: nil makes both inert. Production wires the cmd/pyry resolver.
ModalResolver ModalResolver
// QuestionResolver resolves inbound question_answer and question_refused
// frames against the outstanding clarifying-question batches. The
// QuestionResolver type doc carries the contract, including that the
// implementation is the answer gate. Optional: nil still consumes both frames
// (they never reach dispatch.Route's unknown-type reply) but decodes, hands
// off and broadcasts nothing. It is a seam of its own rather than a
// ModalResolver method because a question batch is its own frame family.
QuestionResolver QuestionResolver
// AttachmentIntake receives inbound attachment_chunk frames and releases a
// departing conn's uploads; the AttachmentIntake type doc carries the
// contract. Optional: nil still consumes the frame (it never reaches
// dispatch.Route's unknown-type reply) but decodes, stores and replies
// nothing, and closeWith releases nothing. Wire exactly one per daemon: its
// in-flight ceiling is daemon-wide, so a second instance would be a second
// budget. Production builds it in cmd/pyry's startRelayV2.
AttachmentIntake AttachmentIntake
// AttachmentResolve returns the on-host path of one stored attachment in one
// conversation: the read half of AttachmentIntake and the retrieval leg's only
// filesystem reach. handleRequestAttachment is its sole caller. Optional: nil
// still consumes request_attachment but decodes, resolves and replies nothing.
//
// Comma-ok, not an error. attachments.ResolvePath answers one sentinel for an
// unknown id, a malformed id and an id outside the conversation's directory,
// so the handler cannot distinguish what CodeAttachmentNotFound merges, and its
// shape error embeds the raw client id, which docs/protocol-mobile.md
// § Attachments forbids logging. The error ends in cmd/pyry's
// attachmentResolve closure.
//
// It performs no registry check. ResolvePath requires a conversation id the
// caller already validated, and handleRequestAttachment consults
// KnownConversation before either id reaches this seam.
//
// Security: the only sanctioned implementation wraps attachments.ResolvePath.
// StreamAttachment re-validates nothing, so a path from elsewhere has no
// containment guarantee, and a non-regular file such as a FIFO would block
// os.ReadFile and wedge the conn's appFrameWorker. ResolvePath answers only
// regular files at exactly the path the two ids build. The path's leaf is a
// sanitised client filename, so the path is never logged and never reaches
// the wire.
AttachmentResolve func(conversationID, attachmentID string) (path string, ok bool)
// WorkspaceFileRead reads one regular file live from the workspace or the
// admitted read folders: the path a client names, not a stored copy.
// handleReadWorkspaceFile is its sole caller. Optional: nil consumes
// read_workspace_file inertly, as a nil AttachmentResolve does for
// request_attachment.
//
// Comma-ok for AttachmentResolve's reason: every refusal (denied name, no
// admitted root, missing file, out-of-tree path, non-regular file, over the
// size bound) is false inside cmd/pyry's workspaceFileReader, so the handler
// cannot tell them apart and never holds an error that prints a host path.
//
// It performs no registry check; the handler consults KnownConversation
// first. Confinement to the admitted roots, the two-leaf secret-name rule and
// the checked read belong to the implementation. The only sanctioned one is
// workspaceFileReader, which reuses the attach_file verb's confineFile and
// readChecked.
WorkspaceFileRead func(conversationID, path string) (WorkspaceFile, bool)
// Interrupter stops the running turn in the conversation an inbound
// interactive interrupt frame names, or in the daemon's cursor conversation
// when it names none. Optional: nil makes interrupt inert. Production wires
// cmd/pyry's activeInterrupter, which owns the shape check and the registry
// resolution.
Interrupter Interrupter
// BackgroundTaskStopper stops a named background task for an inbound
// stop_background_task. Optional; production installs the bound-child adapter
// in cmd/pyry. When unwired, leave a true nil interface, never a typed nil
// pointer: dispatchAppFrame's nil check must consume the verb before payload
// decode or enqueue. The negotiated interactive capability is the only other
// gate; this paired-device action bypasses the tool-permission gate.
BackgroundTaskStopper BackgroundTaskStopper
// SessionStarter starts a fresh session in the conversation an inbound
// interactive new_session frame names, or in the daemon's cursor conversation
// when it names none. Optional: nil makes new_session inert. Production wires
// cmd/pyry's activeSessionStarter, which owns the shape check and the registry
// resolution.
SessionStarter SessionStarter
// AgentSwitcher handles switch_agent asynchronously. Optional: nil replies
// binary_offline.
AgentSwitcher AgentSwitcher
// QueueRemover drops a queued message named by an inbound dequeue_message
// frame. Optional: nil makes dequeue_message inert. Production wires
// *msgqueue.Queue.
QueueRemover QueueRemover
// QueueSender writes a queued message named by an inbound send_queued_now
// frame into the running claude turn. Optional: nil makes send_queued_now
// inert. Production wires *msgqueue.Queue.
QueueSender QueueSender
// DebugBundler assembles the daemon's debug bundle (recent logs plus the
// newest recording, if any) as one in-memory archive, for an inbound
// request_debug_bundle. Optional: nil replies a deterministic unavailable
// error, never a silent drop. Production wires a closure over
// debugbundle.Assemble; the manifest travels inside the archive as
// manifest.json.
//
// Security: the bytes are the plaintext bundle, the most sensitive data in the
// system, and MUST NOT be logged. handleDebugBundleRequest streams them only
// over the AEAD-sealed push path and logs a byte count or the failure, never
// content.
DebugBundler func() (archive []byte, err error)
// SettingsUpdater persists an inbound set_session_settings change from an
// interactive paired client. Optional: nil replies "unavailable"
// deterministically, never a silent drop. Production wires a *sessions.Pool
// adapter. The fail-safe is SettingsUpdate's nil-pointer semantics: an absent
// YOLO never enables bypass.
SettingsUpdater SettingsUpdater
// OutstandingModals returns the daemon's outstanding modals as modal_shown
// payloads, each with its original modal_id, for connect-time reconcile (see
// the type doc). It mints no nonce and retires nothing, so it neither re-arms
// deny-on-timeout nor changes answerability: a re-sent modal_id stays
// answerable exactly once, through the registry's one-shot Resolve, which this
// path never calls. Production wires modalbridge.Registry.Snapshot.
OutstandingModals func() []protocol.ModalShownPayload
// OutstandingQueues returns one queue_state payload per conversation with a
// non-empty backlog, for connect-time reconcile (see the type doc).
// queue_state is full state, so re-sending it is idempotent. It mints no id
// and dequeues nothing. Production wires cmd/pyry's outstandingQueues adapter.
OutstandingQueues func() []protocol.QueueStatePayload
// RetainedModelLists returns one model_list payload per session holding a
// retained list, for connect-time reconcile (see the type doc). model_list is
// a full snapshot, so re-sending it is idempotent. Payloads arrive bounded at
// construction (ModelListPayload.DroppedModels, ModelOption.TruncatedFields),
// and their text is claude-authored. multiAgent is the opening conn's
// negotiated multi_agent decision, with ModelListFor's meaning.
RetainedModelLists func(multiAgent bool) []protocol.ModelListPayload
// OutstandingQuestions returns the outstanding clarifying-question batches as
// question_shown payloads, each with its question_batch_id and
// conversation_id, for connect-time reconcile (see the type doc). The frame is
// broadcast once when claude asks and carries no event id, so nothing else
// reaches a late client, and the daemon would keep re-arming a batch's window
// for a connected client that was never sent it. It mints no nonce and
// retires no batch; a re-sent batch stays answerable exactly once through the
// registry's Resolve. Correlate by question_batch_id.
//
// Each batch is bounded at parse time (questionbridge.Parse: 1 to 4
// questions, 2 to 4 options each, over a maxInputBytes-capped tool input), but
// the registry does not cap how many are outstanding. Question text and
// header, and option label and description, are claude-authored. Production
// wires questionbridge.Registry.Snapshot.
OutstandingQuestions func() []protocol.QuestionShownPayload
// RetainedSlashCommandLists returns one slash_command_list payload per session
// holding a list, each with its conversation_id, for connect-time reconcile
// (see the type doc). The list is session configuration decoded from one
// initialize reply, so re-sending it is idempotent. Without the reconcile a
// client that attaches later has no path to the list, because the live turn
// lane is the only other carrier and can drop it.
//
// Payloads arrive bounded at construction
// (SlashCommandListPayload.DroppedCommands, SlashCommand.TruncatedFields, cut
// against marshalled bytes so the envelope fits the v2 cap). Name,
// ArgumentHint, Description and Aliases are workspace-authored, untrusted
// text, forwarded unsanitised (Description can carry newlines); the client
// owes render sanitisation.
RetainedSlashCommandLists func() []protocol.SlashCommandListPayload
// RetainedBackgroundTaskRosters returns one background_task_roster payload per
// session holding a roster, each with its conversation_id, for connect-time
// reconcile (see the type doc). A roster is a full snapshot, so re-sending it
// is idempotent. Without it a client sees an empty task panel until claude
// next changes the roster.
//
// An empty roster is a positive statement that nothing is running, so a
// producer MUST NOT filter it out as an empty aggregate, and the consumer
// sends it (BackgroundTaskRosterPayload.MarshalJSON writes "tasks":[]).
//
// Payloads arrive bounded at construction
// (BackgroundTaskRosterPayload.DroppedTasks, BackgroundTask.TruncatedFields,
// over streamsup's maxTaskRosterEntries and maxTaskRosterDescription). Every
// string in a row is claude-authored. Description is a literal command line
// for local_bash tasks: render it as inert text, and never execute it or feed
// it to an HTML sink, attribute or URL.
RetainedBackgroundTaskRosters func() []protocol.BackgroundTaskRosterPayload
// RunningTurnPhases returns the current phase of every running turn as
// turn_state payloads, each with its conversation_id, for connect-time
// reconcile (see the type doc). turn_state otherwise travels only on the event
// stream, which a reconnect replays only after hello.last_event_id, and the
// emitter sends no repeated phase, so a long single-phase turn would show
// nothing.
//
// The current phase is the thinking or responding the daemon last sent for a
// turn still open. An implementation MUST NOT derive a phase that was never
// sent and MUST NOT return an idle conversation: absence is the idle answer,
// which the client reads under the reset-on-reconnect rule.
//
// This reconcile runs after replayMissed, and the producer must record a
// transition before the emitter appends its event to the replay ring and asks
// ActiveConns for the fan-out. A turn ending while a conn opens then either
// reads as ended here, or its idle event lands above the conn's replayThrough
// and arrives live after the reconciled frame. Payloads carry only a
// daemon-minted conversation_id and a phase from turnbridge's closed
// vocabulary.
RunningTurnPhases func() []protocol.TurnStatePayload
// ReplySuggestions returns the producer's suggested-reply state as
// reply_suggestion payloads, one per conversation that has state, for
// connect-time reconcile (see the type doc). A cleared suggestion is returned
// with SuggestedReply nil, because the clear is state a reconnecting client
// must apply. A leaf mutex over the producer's map is the expected shape. A
// live publish racing this read needs only the producer's per-conversation
// revision: forwardEnvelope drops a reply_suggestion at or below the highest
// revision already delivered for that conversation on that conn
// (replySuggestionStale). SuggestedReply is claude-derived text.
ReplySuggestions func() []protocol.ReplySuggestionPayload
// contains filtered or unexported fields
}
V2SessionConfig parameterises V2SessionManager. Frames, Outbound, StaticPriv, Devices, ServerID and Logger are required: NewV2SessionManager panics on a nil Frames or Logger and returns an error for the others. Every other field is optional and its doc states what the zero value does. Per-seam design notes live in docs/knowledge/features/v2-session-manager*.md.
Connect-time reconcile seams (OutstandingModals, OutstandingQueues, RetainedModelLists, OutstandingQuestions, RetainedSlashCommandLists, RetainedBackgroundTaskRosters, RunningTurnPhases, ReplySuggestions) share one contract, the Mode B rule of docs/protocol-mobile.md § Reconnect / Backfill semantics. handleNoiseInit's interactive-open tail calls each on the Run goroutine and unicasts the payloads to the just-opened conn only. An implementation MUST be a pure read in bounded time and MUST NOT round-trip through Run (ActiveConns, for example), or the handshake deadlocks. Each seam enumerates rather than taking a key, because a V2Session carries no conversation id; every payload names its own conversation, and slice order is not part of the contract. Where a producer bounds its payloads, the reconcile adds no second cap, and pushQueue's byte ceiling backstops the count. The reconcile path logs no payload field but the conversation id. nil means no reconcile.
Security: StaticPriv is the binary's 32-byte X25519 static private key. It MUST NOT be logged, wrapped into an error or emitted on any wire surface, the same contract internal/keys and internal/noise state for those bytes.
type V2SessionManager ¶ added in v0.14.0
type V2SessionManager struct {
// contains filtered or unexported fields
}
V2SessionManager owns the per-conn_id v2 state machine. Construct with NewV2SessionManager; drive with Run. The manager is single-shot — Run returns when Frames closes or ctx is done, and the manager must not be reused.
Concurrency: Run is the only goroutine the manager owns. sessions is mutated exclusively by Run; no lock. This is intentionally simpler than internal/dispatch.Dispatcher (which spins one goroutine per conn_id); v2 in this slice runs no application handlers, every frame processes synchronously (~100µs Noise call or sub-µs JSON decode), so single-goroutine fan-in is correct and obviously safe. The re-key responder and hosted delivery lane change CipherStates only on this goroutine, with noise_resp ordering the old-key and new-key output.
func NewV2SessionManager ¶ added in v0.14.0
func NewV2SessionManager(cfg V2SessionConfig) (*V2SessionManager, error)
NewV2SessionManager validates cfg and returns a ready manager. Panics on missing Frames or Logger (matching internal/dispatch.New style for programmer errors). Returns an error on missing Outbound, missing Devices, missing ServerID, or wrong-length StaticPriv.
func (*V2SessionManager) ActiveConns ¶ added in v0.15.0
func (m *V2SessionManager) ActiveConns(ctx context.Context) []ActiveConn
ActiveConns returns a snapshot of every session currently in V2StateOpen — the authenticated, token-validated sessions to which Push may deliver — each paired with its negotiated interactive flag. The result is an unordered set (Go's randomized map-iteration order); a caller that needs a stable order must sort it.
Safe to call from any goroutine other than the dispatch goroutine: the request is funneled onto Run via m.snapshot so m.sessions is never read concurrently with an in-flight handshake transition, dispatchAppFrame reply, re-key swap, or closeWith teardown. It is the enumeration half of the server-initiated fan-out primitive — a consumer calls this, then Push on each conn-id, fanning interactive events only to conns with Interactive set. It is the capability-aware v2 analog of v1's dispatch.Dispatcher.ActiveConns().
Sessions still handshaking (V2StateAwaitingInit) or handshake-complete-but- token-unvalidated (V2StateHandshakeComplete) are excluded — the same V2StateOpen security gate forwardEnvelope enforces, so the negotiated flag of an un-authenticated peer is never observable. A torn-down session (deleted from the map by closeWith) cannot appear.
Returns nil on caller ctx cancellation, or when Run has already exited (Frames closed, no receiver on m.snapshot) and the caller's ctx then fires — both equivalent to "no open sessions" for the broadcast consumer, which fans out to nobody this round and re-enumerates on the next turn. nil and an empty non-nil slice are interchangeable (both len 0); a snapshot has no failure the caller can act on, so no error is returned.
func (*V2SessionManager) ActiveThreadConns ¶ added in v0.39.0
func (m *V2SessionManager) ActiveThreadConns(ctx context.Context, conversation string) []ActiveConn
ActiveThreadConns returns open thread consumers eligible for this conversation. Selection shares delivery's membership and agent gates; delivery rechecks them.
func (*V2SessionManager) DeliverThread ¶ added in v0.39.0
func (m *V2SessionManager) DeliverThread(ctx context.Context, connID string, env protocol.Envelope) error
DeliverThread waits for local ordered transport acceptance of one envelope. Call only off Run, send sequences serially, and stop on any error before sending their final marker. Terminal error envelopes are also accepted. Enqueue and assembly completion alone do not certify delivery. Cancellation releases the caller; an already sealed canceled send retires the connection because its nonce may have reached the peer. Retirement, manager shutdown, or a missing ordered lane returns ErrConnNotFound. Legacy callers use Push.
func (*V2SessionManager) FlushPushes ¶ added in v0.37.0
func (m *V2SessionManager) FlushPushes(ctx context.Context) error
FlushPushes waits for each currently open connection's preceding pushes to pass Run's capability/agent gates and seal-and-forward path, or for that connection to close. It is called off Run with the daemon lifetime context. Later pushes cannot extend the wait. Transport-down, replay and hosted-capacity holds retain the markers in FIFO order until recovery; daemon cancellation always releases the caller. Markers contain no payload and never reach the wire or logs.
func (*V2SessionManager) HostedAppsChanged ¶ added in v0.39.0
func (m *V2SessionManager) HostedAppsChanged(change apps.Change)
HostedAppsChanged consumes current-process committed registry changes. It returns without peer I/O, registry re-entry or worker creation. Subscribe supplies increasing host revisions; subscription ownership stays with callers.
func (*V2SessionManager) Push ¶ added in v0.14.0
Push enqueues env onto the addressed session's bounded push buffer and returns immediately — it NEVER blocks on the relay/send path. The Run goroutine drains the buffer on its own schedule (drainOnce), sealing each envelope under s.send in order; so a slow or stalled relay can never wedge the calling producer/dispatch goroutine (the ADR-025 open-risk guard, decisions/025 line 220). Safe to call from any goroutine: Push touches only m.queues (under pushMu) — never s.send, m.sessions, or Outbound.
connID names a specific connected phone. The caller owns env entirely (Type, ID, TS, Payload); Push performs no envelope validation — it is a transport primitive.
Under pressure (queue at capacity) the event-class-aware drop policy runs pre-seal (pushQueue.enqueue): an assistant_delta evicts the oldest queued delta (drop-oldest); a control event is admitted by evicting a droppable delta and is never itself dropped. A drop is not an error — Push returns nil and debug-logs the running count + the dropped class (env.Type only; never payload bytes).
Past pushQueueByteCeiling the soft-overflow admission stops: the envelope is rejected, pushQueue.overflowed latches, and this Push signals m.pushOverflow so Run tears the session down (handlePushOverflow, #1505). That is still not an error the producer sees — the call returns nil, and promptly; the overflow is not the producer's failure, and both production callers only debug-log an error anyway. Pushes that follow the teardown find no queue and get the pre-existing ErrConnNotFound, so no new error value ever reaches a producer.
Returns ErrConnNotFound (wraps control.ErrConnNotFound) when no queue exists for connID — i.e. the session never reached V2StateOpen, was never seen, or has been torn down (closeWith deletes the queue). This collapses the former "session not open" case into ErrConnNotFound: a not-open conn has no queue. The V2StateOpen security gate is preserved on the drain side — forwardEnvelope re-checks s.state before sealing, so a buffered push to a conn that closed or de-authed before drain is dropped there, never delivered to an un-authenticated peer. Returns ctx.Err() only when ctx is already cancelled at entry (preserves the emitter's ctx-teardown branch). Both production callers (#632 emitter, #589 coarse bridge) only debug-log the error, so the collapse is invisible to them.
func (*V2SessionManager) PushLiveState ¶ added in v0.39.0
PushLiveState queues either a source-bound push or a correlated reply. Like Push it never seals on the producer. Invalid input returns a content-free error. Callers may reuse or mutate their input buffers after this call returns.
func (*V2SessionManager) Rekey ¶ added in v0.14.0
func (m *V2SessionManager) Rekey(ctx context.Context, connID string) error
func (*V2SessionManager) RetireLiveState ¶ added in v0.39.0
func (m *V2SessionManager) RetireLiveState(ctx context.Context, connID string) error
RetireLiveState forces reconnect reconciliation after a producer handoff gap. The queue latch quarantines pending output until Run handles gap teardown.
func (*V2SessionManager) Run ¶ added in v0.14.0
func (m *V2SessionManager) Run(ctx context.Context) error
Run drives the state machine until Frames closes or ctx is cancelled. Returns ctx.Err() on cancellation, nil on Frames close. Every per-conn session is released on return; no goroutines outlive Run.
runCtx is a derived-cancel context so per-session timer-callback goroutines (spawned by armRekeyTimer / armRekeyReplyTimer via time.AfterFunc) unblock cleanly when Run exits. The callbacks select on (m.wake, runCtx.Done) so a fired-but-undelivered wake completes via the ctx branch on shutdown and leaves no goroutine behind.
func (*V2SessionManager) SetReplaySource ¶ added in v0.15.0
func (m *V2SessionManager) SetReplaySource(ring *eventring.Ring, currentConv func() string)
SetReplaySource publishes the mid-turn-reconnect replay source to the manager (#647). It is called once during relay wiring, AFTER the interactive emitter (which owns the eventring) is constructed: the emitter and manager have a circular dependency (the emitter takes the manager as its broadcaster; the replay path needs the emitter-owned ring), so the ring does not exist when NewV2SessionManager runs — a construction-time V2SessionConfig field is not buildable without the constructor cascade #646 avoided. A late-bound setter is the seam that breaks the cycle. ring is the emitter's per-conversation event ring; currentConv resolves the conversation a reconnecting conn replays for (the supervisor's #312 cursor).
Stored under pushMu (the existing leaf lock, taken alone): this write happens off the Run goroutine during wiring, and replayMissed reads them on the Run goroutine at reconnect — much later, after a full network handshake. A nil ring or cursor leaves replay disabled. Idempotent by construction (the wiring calls it once).
func (*V2SessionManager) StreamAttachment ¶ added in v0.16.0
func (m *V2SessionManager) StreamAttachment(ctx context.Context, connID, attachmentID, path string, inReplyTo uint64) error
StreamAttachment moves one stored attachment to the addressed, open, authenticated v2 conn as a conforming stream of attachment_chunk frames, each correlated to the request that asked for it. It reads the whole file, builds the envelopes with attachmentEnvelopes, then enqueues each in order via Push — the manager's own asynchronous send path (Push → drainOnce → forwardEnvelope), the same path every unsolicited daemon → client frame uses. It deliberately does NOT use the per-frame handler-reply channel (handlerOutboundBuf = 8, a small fixed buffer sized for the 1-few-reply request/response case), so a file of any size cannot overrun it.
PRECONDITION, AND IT CARRIES THE WHOLE SECURITY PROPERTY: path must be one attachments.ResolvePath answered for the conversation the authenticated session is already on, and attachmentID must be the id those bytes are stored under. This function resolves nothing and validates neither — the same trusts-its-caller posture Store documents for the dir EnsureDir returned, and for the same reason: re-deriving here would fork a check that has to happen before a path is built at all, and the reject vocabulary that answers a failed check (attachment.not_found and attachment.stream_aborted alike) belongs to the handler that can correlate a reject to a request. That handler is #2054.
TWO CONSEQUENCES THE CALLER HAS TO HONOUR, stated because nothing here would notice either. A path this function did not get from ResolvePath carries NO CONTAINMENT GUARANTEE: every traversal defence is that function's full-path equality check. And a path naming a NON-REGULAR FILE misbehaves rather than erroring — os.ReadFile on a FIFO blocks indefinitely, wedging whichever goroutine the caller runs this on. ResolvePath answers only entries whose Type().IsRegular() holds and only a path equal to the one its two ids build, so both are unreachable through the sanctioned caller; a guard here would be a second, weaker copy of a check that already exists.
A whole-file read rather than a streaming one: the upload leg bounds one stored attachment at 16 MiB (maxUploadBytes in internal/attachments), so the read is comfortably bounded and a streaming read would buy nothing but a second failure mode mid-stream.
Safe to call from any goroutine, including a future #2054 handler on the Run goroutine or on a conn's appFrameWorker: Push never blocks and never touches s.send, so this sidesteps both the frame-cap wall and the handler-buffer wall, and no concurrent Encrypt on the single-owner send state is reachable however many callers stream at once. Attachment frames are control-class (not TypeAssistantDelta), so the pushQueue drop policy never evicts them — all chunks are delivered, in order.
Returns on successful ENQUEUE, not delivery (delivery is async on Run; a per-frame seal/forward failure is logged at debug by drainOnce). That is precisely why attachment.stream_aborted is #2054's to emit and not this slice's: a failure after enqueue is invisible here. Returns the first Push error and stops on it, since Push answers ErrConnNotFound for a conn that is not open and there is no point continuing.
SECURITY — the never-log rule, and it binds the RETURNED ERROR as well as the log call. protocol.AttachmentChunkPayload's SECURITY block and docs/protocol-mobile.md § Attachments fix the loggable set: conn id, attachment id, index and total may be logged; the streamed bytes, the filename, the digest and the host path never. ResolvePath's doc block adds that the path it returns is NOT fully daemon-authored — its leaf is a sanitised client filename — so it is no more loggable than the raw name is. os.ReadFile returns an *fs.PathError whose Error() prints that path, so a caller logging this function's error verbatim would defeat the rule through it; the error below is rebuilt around the STRIPPED cause instead, which keeps errors.Is(err, fs.ErrNotExist) working for #2054 while making the leak unavailable. Logs one content-free debug line on success — counts only.
func (*V2SessionManager) StreamBundle ¶ added in v0.16.0
StreamBundle moves an arbitrarily-large byte blob to the addressed, open, authenticated v2 conn as ordered, cap-respecting chunks ending in a completion marker. It builds the envelopes with bundleEnvelopes, then enqueues each in order via Push — the manager's own asynchronous send path (Push → drainOnce → forwardEnvelope), the same path every unsolicited daemon → client frame uses. It deliberately does NOT use the per-frame handler-reply channel (handlerOutboundBuf = 8, a small fixed buffer sized for the 1-few-reply request/response case), so a bundle of any size cannot overrun it.
Safe to call from any goroutine, including a future handler on the Run goroutine: Push never blocks and never touches s.send, so this sidesteps both the frame-cap wall and the handler-buffer wall. Bundle frames are control-class (not TypeAssistantDelta), so the pushQueue drop policy never evicts them — all chunks are delivered, in order.
Returns on successful ENQUEUE, not delivery (delivery is async on Run; a per-frame seal/forward failure is logged at debug by drainOnce, matching the package's fire-and-forget push posture). Returns the first Push error and stops on it: Push returns ErrConnNotFound for a conn that is not open, so there is no point continuing. Logs one content-free debug line on success — counts only, never the streamed bytes (AC#4).
type V2SessionState ¶ added in v0.14.0
type V2SessionState int
V2SessionState is the externally-observable lifecycle state of a per-conn V2Session. The handshakeComplete substate is distinct from open even though both can be set inside the same noise_init handler: the field exists so the gating test pins the "handler chain unreachable from handshakeComplete" invariant deterministically (AC #1 / #4).
const ( V2StateAwaitingInit V2SessionState = iota V2StateHandshakeComplete V2StateOpen V2StateClosed )
type WorkspaceFile ¶ added in v0.26.0
WorkspaceFile is one live read answered by the WorkspaceFileRead seam.
AttachmentID is daemon-minted per transfer, a lowercase UUIDv4 that keys this one chunk stream and addresses nothing afterwards: nothing is stored under it. Filename is the base name of the resolved file, which after symlink resolution may differ from the leaf the client named. Neither Filename nor Data may be logged.
Source Files
¶
- auth.go
- connection.go
- connection_feedback.go
- queue_item_binding.go
- v2attachmentstream.go
- v2bundlestream.go
- v2session.go
- v2session_agentgate.go
- v2session_appframe.go
- v2session_attachment.go
- v2session_attachment_request.go
- v2session_catchup.go
- v2session_children.go
- v2session_conns.go
- v2session_contextusage.go
- v2session_debugbundle.go
- v2session_handshake.go
- v2session_history_request.go
- v2session_hosted.go
- v2session_hosted_changes.go
- v2session_hosted_resources.go
- v2session_hosted_validation.go
- v2session_live_replies.go
- v2session_livestate.go
- v2session_mcpactuate.go
- v2session_mcpstatus.go
- v2session_mint_pairing.go
- v2session_modal.go
- v2session_modelreconcile.go
- v2session_modelrequest.go
- v2session_publication.go
- v2session_push.go
- v2session_question.go
- v2session_questionreconcile.go
- v2session_redemption.go
- v2session_rekey.go
- v2session_replay.go
- v2session_replysuggestionreconcile.go
- v2session_rosterreconcile.go
- v2session_seam_types.go
- v2session_seams.go
- v2session_settings.go
- v2session_slashreconcile.go
- v2session_stop_background_task.go
- v2session_switchagent.go
- v2session_systemprompt.go
- v2session_thread.go
- v2session_thread_delivery.go
- v2session_tool_body.go
- v2session_turnphasereconcile.go
- v2session_workspace_file.go