Documentation
¶
Index ¶
- Variables
- func AgentOf(conv conversations.Conversation, harnessFor SessionHarnessFunc) string
- func ArchiveConversation(reg ConversationArchiver, registryPath string, logger *slog.Logger, ...) dispatch.Handler
- func ChangeWorkspace(reg ConversationWorkspaceUpdater, resolve WorkspaceResolver, ...) dispatch.Handler
- func CreateConversation(reg ConversationCreator, creator SessionCreator, ...) dispatch.Handler
- func CreateWorkspaceFolder(resolve WorkspaceFolderResolver, logger *slog.Logger) dispatch.Handler
- func DeleteConversation(reg ConversationDeleter, registryPath string, logger *slog.Logger) dispatch.Handler
- func ListConversations(reg ConversationLister, hist historyLatestReader) dispatch.Handler
- func ListConversationsWithAgents(reg ConversationLister, harnessFor SessionHarnessFunc, ...) dispatch.Handler
- func MarkConversationRead(reg ConversationReadMarker, hist historyLatestReader, registryPath string, ...) dispatch.Handler
- func PromoteConversation(reg ConversationPromoter, registryPath string, logger *slog.Logger) dispatch.Handler
- func RecentWorkspaces(reg RecentWorkspacesReader) dispatch.Handler
- func RegisterPushToken(reg *devices.Registry, registryPath string, logger *slog.Logger) dispatch.Handler
- func RenameConversation(reg ConversationRenamer, registryPath string, logger *slog.Logger) dispatch.Handler
- func RenameWorkspace(reg WorkspaceLabeler, registryPath string, announce WorkspaceAnnouncer, ...) dispatch.Handler
- func RequestClaudeAccount(src ClaudeAccountSource, logger *slog.Logger) dispatch.Handler
- func RequestHostSystemPrompt(store HostSystemPromptStore, logger *slog.Logger) dispatch.Handler
- func SendMessage(router SessionRouter, queue Enqueuer, resolve AttachmentResolver, ...) dispatch.Handler
- func SetConversationMuted(reg ConversationMuter, registryPath string, announce ConversationAnnouncer, ...) dispatch.Handler
- func SetHostSystemPrompt(store HostSystemPromptStore, logger *slog.Logger) dispatch.Handler
- func SetSystemPrompt(reg ConversationSystemPromptSetter, registryPath string, logger *slog.Logger) dispatch.Handler
- type AttachmentResolver
- type ClaudeAccountSource
- type ConversationAnnouncer
- type ConversationArchiver
- type ConversationAutoNamer
- type ConversationCreator
- type ConversationDeleter
- type ConversationLister
- type ConversationMuter
- type ConversationPromoter
- type ConversationReadMarker
- type ConversationRenamer
- type ConversationResetter
- type ConversationSystemPromptSetter
- type ConversationToucher
- type ConversationWorkspaceUpdater
- type CreateSettings
- type Enqueuer
- type HostSystemPromptStore
- type RecentWorkspacesReader
- type SessionCreator
- type SessionHarnessFunc
- type SessionRouter
- type TurnWriter
- type WorkspaceAnnouncer
- type WorkspaceFolderResolver
- type WorkspaceLabeler
- type WorkspaceResolver
Constants ¶
This section is empty.
Variables ¶
var ErrSpawnDirRejected = errors.New("conversation spawn directory rejected")
ErrSpawnDirRejected marks a deterministic rejection of a conversation's requested spawn workdir (it escapes $HOME after symlink resolution, or is unresolvable). SessionCreator implementations wrap it; the handler maps it to a non-retryable protocol.malformed reply rather than a retryable server.binary_offline, because re-issuing the same Cwd fails identically. The sentinel lives in this consumer/mapper package (cmd/pyry wraps it, no import cycle); mirrors the errors.Is mapping convention pinned in PROJECT-MEMORY.
var ErrWorkspaceFolderRejected = errors.New("workspace folder rejected")
ErrWorkspaceFolderRejected marks a deterministic rejection of the target folder (its resolved path escapes $HOME, is unresolvable, or cannot be created). WorkspaceFolderResolver implementations wrap every failure with it; the handler maps any non-nil resolver error to a non-retryable protocol.malformed reply, because re-issuing the same request fails identically (there is no transient failure mode — this verb does not spawn or mint). The sentinel lives in this consumer/mapper package (the cmd/pyry adapter wraps it, no import cycle), documents intent, and gives tests an errors.Is anchor; mirrors ErrWorkspaceRejected / ErrSpawnDirRejected.
var ErrWorkspaceRejected = errors.New("conversation workspace directory rejected")
ErrWorkspaceRejected marks a deterministic rejection of a change_workspace target path (it escapes $HOME after symlink resolution, or is unresolvable). WorkspaceResolver implementations wrap every failure with it; the handler maps any non-nil resolver error to a non-retryable protocol.malformed reply, because re-issuing the same path fails identically (there is no transient failure mode — this verb does not spawn or mint). The sentinel lives in this consumer/mapper package (the cmd/pyry adapter wraps it, no import cycle), documents intent, and gives tests an errors.Is anchor; mirrors ErrSpawnDirRejected.
Functions ¶
func AgentOf ¶ added in v0.27.0
func AgentOf(conv conversations.Conversation, harnessFor SessionHarnessFunc) string
AgentOf is the wire agent of conv: its bound session's, and AgentClaude when there is no bound session, no harness read, or a session the pool does not hold. The mapping is closed, so the wire only ever carries the two values a client codes against. Exported so the daemon's pushed-frame gate (#2644) resolves a conversation's agent by this same rule.
func ArchiveConversation ¶ added in v0.16.0
func ArchiveConversation(reg ConversationArchiver, registryPath string, logger *slog.Logger, archived bool) dispatch.Handler
ArchiveConversation returns a dispatch.Handler that processes an archive_conversation or unarchive_conversation frame from a paired client — a symmetric toggle of one durable flag selected by archived. It flips the named conversation's IsArchived flag, eagerly persists the registry so the change survives a daemon restart, and replies with the reused conversation_updated record (reflecting the new archived state) correlated via in_reply_to. archived=true archives; archived=false restores. The verb is idempotent: toggling an already-archived (or already-active) row still Saves and still replies with the unchanged state.
reg is the conversations registry (the single writer — no reload-before-save); registryPath is the canonical on-disk path passed to the eager Save; logger is the daemon's slog logger. archived is baked into the returned handler, so the same factory registered twice yields the two verbs.
SECURITY (mirrors delete_conversation, per the security-sensitive label): the one untrusted payload field, conversation_id, is used ONLY as an exact-match registry key inside SetArchived and Get (a byte comparison, no path/argv construction — a miss is conversation.not_found, and a client can only name an id that already exists). Both reject branches reply with a fixed static string — no payload bytes (the supplied id, a decode-error fragment) reach the wire.
Two deliberate divergences from the rename_conversation template — keep them, do not "fix" them back: (1) the flip goes through SetArchived + a follow-up Get rather than an Update closure, honoring #880's single-field mutator (structurally cannot touch another field); (2) the malformed branch logs conn_id ONLY — not the decode err (Go's json.Unmarshal errors can embed offending input bytes) and not conversation_id (a decode failure leaves the struct at most partially populated, so p.ConversationID may hold raw attacker bytes). The not_found and success branches log the (never-wire-reaching, or proven-real) conversation_id as a structured slog field. The verb label in the malformed message is env.Type, a trusted dispatch-validated constant (the dispatcher matched it against the registered key to route here), never attacker bytes.
func ChangeWorkspace ¶ added in v0.16.0
func ChangeWorkspace(reg ConversationWorkspaceUpdater, resolve WorkspaceResolver, registryPath string, logger *slog.Logger) dispatch.Handler
ChangeWorkspace returns a dispatch.Handler that processes a change_workspace frame from a paired client (desktop Workspace Picker; later mobile): it moves an existing conversation to a client-chosen workspace folder by setting its recorded Cwd to the $HOME-confined realpath of the target, eagerly persists the registry so the change survives a daemon restart, and replies with the reused conversation_updated record (carrying the new workspace) correlated via in_reply_to. "Workspace" IS the conversation's Cwd; this verb changes the RECORDED workspace only — the new folder takes effect on the conversation's next fresh session spawn (conv.Cwd is decoupled from a live session's captured spawn WorkDir, #685/#686) — and the reply goes only to the requester (other clients pick up the change on their next list_conversations, which reads the live registry with no list-handler change).
reg is the conversations registry (the single writer — no reload-before-save); resolve confines the untrusted target path to $HOME; registryPath is the canonical on-disk path passed to the eager Save; logger is the daemon's slog logger.
SECURITY (this verb is security-sensitive — the one material difference from its rename/delete siblings — because it stores an untrusted FILESYSTEM PATH supplied by a network-paired party): the target Cwd becomes the conversation's spawn workdir on its next fresh session, so it is confined to $HOME (rejecting any path escaping $HOME after symlink resolution, fail-closed) BEFORE it is stored, and the RESOLVED realpath — the value that was security-confined — is what is persisted, not the raw path (validate == store). All four reject branches reply with a fixed static string; no supplied bytes (the path, the id, the decode-error text) reach the wire.
Two logging divergences from the create_conversation / rename_conversation templates — keep them, do NOT "fix" them back by pattern-matching create:
(1) Malformed branch (inherited from delete_conversation #822): log conn_id
ONLY — not the decode err (Go's json.Unmarshal errors can embed offending
input bytes) and not conversation_id (a decode failure leaves the struct
at most partially populated, so p.ConversationID may hold raw attacker
bytes).
(2) Confine-rejected branch (NEW to this verb, the load-bearing one):
create_conversation.go logs the wrapped confine err on rejection — and
that err NAMES the offending path. This handler must NOT: it logs conn_id
+ conversation_id only, never the confine err, never the path (AC #5 — no
attacker-controlled bytes echoed to the daemon log). conversation_id is a
decode-success, slog-escaped structured field here and is safe to log,
consistent with delete's not_found branch.
func CreateConversation ¶ added in v0.15.0
func CreateConversation(reg ConversationCreator, creator SessionCreator, registryPath, defaultCwd string, logger *slog.Logger) dispatch.Handler
CreateConversation returns a dispatch.Handler that processes a create_conversation frame from the phone: it settles the requested agent (claude unless a multi_agent client asks for codex, #2647), mints a fresh conversation id, mints and binds a dedicated session of that agent for it via the sessions pool, records a registry row carrying the bound session id plus the effective cwd / promoted flag / name (server defaults applied when a field is null), eagerly persists the registry, and replies with a conversation_created envelope correlated via in_reply_to.
reg is the conversations registry; creator mints the per-conversation session; registryPath is the canonical on-disk path passed to the eager Save; defaultCwd is the absolute cwd recorded when the payload's cwd is null; logger is the daemon's slog logger.
SECURITY: this handler feeds the spawn path — it mints a per-conversation claude session via creator.Create, whose child will later spawn in the conversation's own (phone-influenced) Cwd rather than the daemon's shared workdir (#685, reversing the prior deferral). Since #2085 the mint no longer starts that child; the validation below is unchanged and still runs here, at mint time, and the accepted consequence of the wider validated-then-spawn window is recorded on sessionMinter. The phone's raw requested Cwd is forwarded verbatim as creator.Create's spawnDir, and the row records the dir creator.Create answers with, never the raw string (#2568); this handler does NO path handling and stays free of internal/sessions / cmd-layer imports. The cmd-layer adapter (sessionMinter → resolveSpawnDir) is the sole validator: it canonicalises + confines the Cwd to $HOME (rejecting any path that escapes after symlink resolution) and trust-marks the realpath before claude spawns, identical to the daemon's own bootstrap-workdir posture. A rejected Cwd surfaces as a non-retryable protocol.malformed reply (errors.Is ErrSpawnDirRejected) with no half-bound row; a null Cwd yields an empty spawnDir → the shared trusted workdir (unchanged). The session id reaching claude's argv (--session-id) is server-minted (sessions.NewID, crypto/rand); the created conversation id is server-minted (conversations.NewID), never phone-supplied, so a phone cannot choose, collide, or overwrite a row (Create appends).
func CreateWorkspaceFolder ¶ added in v0.16.0
func CreateWorkspaceFolder(resolve WorkspaceFolderResolver, logger *slog.Logger) dispatch.Handler
CreateWorkspaceFolder returns a dispatch.Handler that processes a create_workspace_folder frame from a paired client (desktop Workspace Picker's Create-folder dialog; later mobile): it creates a new folder on the daemon host under a client-supplied parent path — confined to $HOME — and replies with the new workspace_folder_created record carrying the created folder's canonical absolute path, correlated via in_reply_to. It consumes NO conversations registry: it creates a directory and returns its path, nothing more — the leanest handler in the write-verb family. resolve validates + creates the target under $HOME; logger is the daemon's slog logger.
SECURITY (this verb is security-sensitive — it WRITES TO THE HOST FILESYSTEM a directory named by two untrusted fields, `parent` and `name`, supplied by a network-paired party). Two independent, fail-closed, deterministic properties hold — belt-and-suspenders, DIFFERENT FABRIC (two distinct code checks, not one gate twice):
(1) The resolved target is confined to $HOME — confineWorkdirToHomeCreating
(in the injected resolver) rejects any path escaping $HOME after symlink
resolution, BEFORE any directory is created (path traversal / symlink
escape).
(2) The new folder lands DIRECTLY under the supplied parent — the name-shape
guard below rejects a name that is empty, absolute, contains a path
separator, or contains "..". Confinement alone does NOT give this: a name
like "sub/dir" stays inside $HOME yet is not directly under the parent.
No-leak logging is the co-crux, and is UNIFORM here (simpler than change_workspace's per-branch divergence) because there is no safe-to-log structured field except conn_id: BOTH decoded fields (`parent`, `name`) are attacker-controlled path components, so neither may be logged. The invariant: NO log record this handler emits — on ANY branch, including success — ever contains `parent`, `name`, a joined/resolved path, or a decode/confine `err`. Only conn_id + a static `event` name. Two traps a future editor will hit by pattern-matching the siblings — do NOT "fix" them back:
- Malformed branch: do NOT log the decode `err` (`CreateConversation` and rename_conversation do). Go's json.Unmarshal errors can embed the offending input bytes.
- Rejected branch: do NOT log the confine `err` or the path (`CreateConversation` logs the wrapped confine err, which NAMES the offending path). AC #7.
All four reject branches reply with a fixed static string; no supplied bytes (the parent, the name, the decode-error text) reach the wire.
func DeleteConversation ¶ added in v0.16.0
func DeleteConversation(reg ConversationDeleter, registryPath string, logger *slog.Logger) dispatch.Handler
DeleteConversation returns a dispatch.Handler that processes a delete_conversation frame from a paired client: it PERMANENTLY removes an existing conversation from the registry (hard delete — the reversible path is archive/unarchive), eagerly persists the registry so the removal survives a daemon restart, and replies with a conversation_deleted acknowledgement carrying the deleted id, correlated via in_reply_to.
reg is the conversations registry (the single writer — no reload-before-save); registryPath is the canonical on-disk path passed to the eager Save; logger is the daemon's slog logger.
SECURITY: the one untrusted payload field, conversation_id, is used ONLY as an exact-match registry key inside Delete (a byte comparison, no path/argv construction — a miss is conversation.not_found, and a client can only name an id that already exists). Both reject branches reply with a fixed static string — no payload bytes (the supplied id, a decode-error fragment) reach the wire.
Two deliberate divergences from the rename_conversation template, mandated by the spec's AC #5 ("no attacker-controlled payload bytes ... logged"): the malformed branch logs conn_id ONLY — not the decode err (Go's json.Unmarshal errors can embed offending input bytes) and not conversation_id (a decode failure leaves the struct at most partially populated, so p.ConversationID may hold raw attacker bytes). The not_found and success branches log the (now proven-real, or never-wire-reaching) conversation_id as a structured, handler-escaped slog field, consistent with the rename/create precedent.
func ListConversations ¶
func ListConversations(reg ConversationLister, hist historyLatestReader) dispatch.Handler
ListConversations is ListConversationsWithAgents with no harness read: every conversation reads as Claude's, so the reply is the pre-#2643 list for every client. The daemon wires the agent-aware form; this one serves callers that hold no pool.
func ListConversationsWithAgents ¶ added in v0.27.0
func ListConversationsWithAgents(reg ConversationLister, harnessFor SessionHarnessFunc, hist historyLatestReader) dispatch.Handler
ListConversationsWithAgents returns a dispatch.Handler that answers a list_conversations request with a conversations envelope. The handler reads the registry, projects each row to a protocol.ConversationSummary, sorts by LastUsedAt asc / ID asc (mirroring Registry.Save), and replies via Conn.Reply (which stamps id, ts, and in_reply_to).
The reply depends on the conn's negotiated multi_agent decision (#2643). A client that negotiated it reads every row with its agent. A client that did not is never sent a Codex conversation, and each row it is sent carries no agent key, byte-identical to the row it read before agents existed.
func MarkConversationRead ¶ added in v0.33.0
func MarkConversationRead(reg ConversationReadMarker, hist historyLatestReader, registryPath string, announce ConversationAnnouncer, logger *slog.Logger) dispatch.Handler
MarkConversationRead returns a dispatch.Handler for a mark_conversation_read frame (#2780). It raises the named conversation's host-local read mark to max(held, min(up_to, newest durable history entry id)), so a mark can neither move back nor cover entries that do not exist yet. Every success replies with conversation_updated, correlated via in_reply_to and carrying the stored read_up_to. Only an actual advance is also pushed through announce, to every eligible client including the requester; a no-op pushes nothing.
Unlike set_conversation_muted's best-effort Save, an advance that cannot be persisted is refused with the retryable read_mark.unavailable: the registry reverted it, so the same request advances afresh once saving works again.
The handler holds no pool or runner seam, so it cannot spawn, restart or interrupt a session.
SECURITY (security-sensitive label): conversation_id is first used as an exact-match registry key; only an id the registry has proven reaches the history store, which re-validates it before building a path. up_to decodes into a uint64, so encoding/json enforces the wire range. Every refusal sends a static message, and no refusal branch logs a payload field: not the decode err (encoding/json can quote input bytes), not an unproven conversation_id.
func PromoteConversation ¶ added in v0.16.0
func PromoteConversation(reg ConversationPromoter, registryPath string, logger *slog.Logger) dispatch.Handler
PromoteConversation returns a dispatch.Handler that processes a promote_conversation frame ("Save as channel") from a paired client: it flips an existing scratch conversation to a named channel via Registry.Promote, eagerly persists the registry so the promotion survives a daemon restart, and replies with the reused conversation_updated record correlated via in_reply_to.
reg is the conversations registry (the single writer — no reload-before-save); registryPath is the canonical on-disk path passed to the eager Save; logger is the daemon's slog logger.
SECURITY (this verb carries the security-sensitive label — see the spec's § The Cwd decision and § Security review): PromoteConversationPayload carries a required Cwd that this handler deliberately does NOT consume. Promotion is a naming/persistence operation, not a relocation — the channel inherits the scratch conversation's existing (already $HOME-confined at create time) Cwd, and the payload Cwd reaches no filesystem operation, no registry write, and no spawn argument (Option B). It is read off the wire into the payload struct and discarded; the reply's Cwd is the row's pre-existing stored value, read back via Get. A future editor MUST NOT "wire up" p.Cwd without re-opening that decision and the security review — doing so would open the untrusted-path-as- workdir surface change_workspace guards (#823) that this verb, by design, does not have. The "Cwd ignored" unit test is the deterministic guard against that regression.
The three untrusted payload fields are each contained: conversation_id is used ONLY as an exact-match registry key (a miss is conversation.not_found; a client can only name an id that already exists); name is stored as an opaque display string and echoed only to the requester (Registry.Promote enforces non-empty and cross-row name-uniqueness); cwd is discarded. All reject branches reply with a fixed static string — no supplied bytes (name, id, decode-error text) reach the wire — and the channel name is never logged (it is user content).
Logging divergence from rename (adopt change_workspace's malformed discipline, do NOT "fix" it back): the malformed branch logs conn_id ONLY — not the decode err (Go's json.Unmarshal errors can embed offending input bytes) and not conversation_id (a decode failure may leave p.ConversationID holding raw attacker bytes). Every other branch runs post-decode, so conversation_id is a proven-decoded, slog-escaped structured field and is safe to log.
func RecentWorkspaces ¶ added in v0.16.0
func RecentWorkspaces(reg RecentWorkspacesReader) dispatch.Handler
RecentWorkspaces returns a dispatch.Handler that answers a recent_workspaces request with a recent_workspaces_list reply. It derives the distinct set of workspace folders from the conversations registry's Cwd values: each distinct Cwd appears exactly once, carrying the most-recent LastUsedAt across the conversations that share it, ordered most-recent-first (tie broken by Path ascending so ordering is deterministic).
Archived conversations are included by design (#888): a workspace is a folder, not a conversation, and archiving a conversation does not "un-use" its folder. A folder whose conversations are all archived simply carries an older LastUsedAt and sinks to the bottom of the recency-ordered list. Conversations with an empty Cwd contribute no entry (an empty string is not a workspace path). An empty registry yields "workspaces":[], not an error.
The request payload is empty by spec and ignored, mirroring ListConversations. The handler replies via Conn.Reply (which stamps id, ts, and in_reply_to).
func RegisterPushToken ¶
func RegisterPushToken(reg *devices.Registry, registryPath string, logger *slog.Logger) dispatch.Handler
RegisterPushToken returns a dispatch.Handler that processes a register_push_token frame from the phone. reg is the devices registry; registryPath is the canonical on-disk path passed to Save; logger is the daemon's slog logger used for every branch's structured event.
SECURITY:
- The push token (p.Token, dev.PushToken) is opaque infrastructure data (FCM/APNs registration id); not a secret on par with the device auth token. It is logged at INFO when a write happens (as a side-effect of the write event) and never as a field value at any level.
- The Device.Name is logged on every authenticated branch that predates #2219. The unauth branch has no name to log, and that ticket's three reject branches deliberately log neither it nor the payload's own value.
- p.DeviceName and p.Platform are CLIENT-AUTHORED and are gated here before they can be stored (#2219) — see the block at the guards. dev.Name, the value already in the registry, carries NO such guarantee and Device.Name is not display-safe as a type invariant: a name written before this gate existed is read back unchecked, and `pyry pair --name` is operator-authored and deliberately ungated (mintLabelIsDisplaySafe's block states why the check does not live in the shared mint step). A consumer still owes its own escaping.
Concurrency: the handler is stateless beyond the closure capture. Its reconcile, mutation and save run as ONE region under devices.WithLock (#1532) — reg's mutex alone cannot serialise them, since `pyry pair` is a separate process and every writer rewrites the whole file. Two concurrent calls for the same TokenHash now serialise on the file lock rather than interleaving at the mutex boundary, with last-writer-wins between whole regions. The acquisition is bounded by pushRegistryLockWait and refuses rather than queues past it, so a contended lock costs the conn that bound at most and never an unlocked write. No goroutine is spawned.
func RenameConversation ¶ added in v0.16.0
func RenameConversation(reg ConversationRenamer, registryPath string, logger *slog.Logger) dispatch.Handler
RenameConversation returns a dispatch.Handler that processes a rename_conversation frame from a paired client: it sets an existing conversation's display name to the requested title, eagerly persists the registry so the rename survives a daemon restart, and replies with the reused conversation_updated record correlated via in_reply_to.
reg is the conversations registry (the single writer — no reload-before-save); registryPath is the canonical on-disk path passed to the eager Save; logger is the daemon's slog logger.
SECURITY: the two untrusted payload fields are contained. conversation_id is used ONLY as an exact-match registry key inside Update (a byte comparison, no path/argv construction — a miss is conversation.not_found, and a client can only name an id that already exists). The title is stored as an opaque display string and echoed only to the requester. All three reject branches reply with a fixed static string — no payload bytes (title, id, decode error) reach the wire — and the title is never logged (it is user content); only the non-secret conversation_id is logged, mirroring create_conversation.
func RenameWorkspace ¶ added in v0.16.0
func RenameWorkspace(reg WorkspaceLabeler, registryPath string, announce WorkspaceAnnouncer, logger *slog.Logger) dispatch.Handler
RenameWorkspace returns a dispatch.Handler that processes a rename_workspace frame from a paired client: it sets or clears the operator-chosen display name of a workspace, eagerly persists the registry so the change survives a daemon restart, and replies with a workspace_updated record correlated via in_reply_to.
Keyed by WORKSPACE, not by conversation, and that is why the reply is a new type rather than the reused conversation_updated record change_workspace answers with: N conversations share one cwd, a workspace has no row of its own, and no conversation record could carry the change without naming one arbitrary member of that set.
The requester gets the correlated reply and EVERY OTHER connected interactive client gets the same record as an unsolicited push (#2209), so a name chosen on one machine is the name shown on all of them without a reload. The fan-out runs last, after the store, the persist and the reply, and it returns nothing — see WorkspaceAnnouncer for why, and the announce call below for what that buys.
reg is the conversations registry (the single writer — no reload-before-save); registryPath is the canonical on-disk path passed to the eager Save; announce fans the record to the other clients and may be nil; logger is the daemon's slog logger.
SECURITY (this verb is security-sensitive — it stores untrusted operator text supplied by a network-paired party, keyed by a path that party also supplies):
Reachability is the authenticated, paired Noise session. A frame is decrypted under the session's receive state before it reaches dispatch, so only the paired phone arrives here — the same gate every conversation write verb has, needing no new code. No interactive-capability gate, matching set_system_prompt: that capability is read only in the outbound fan-out and is not an inbound gate.
The path is a LOOKUP KEY AND NOTHING MORE. It is compared byte-for-byte against stored cwds and used as a map key; it is never resolved, joined, stat-ed, opened, or passed to a process. The one filesystem operation this handler performs, Save, takes the daemon-derived registryPath — no client byte reaches it. And the reply's path is projected from the MATCHED ROW's Cwd rather than from the request (see the success arm), so no request byte reaches the wire on any branch, reject or success.
The label is an opaque display string: stored verbatim, echoed as stored to the requester and — since #2209 — to the other paired interactive clients, never logged, never interpolated into an error message, never a path component or an argv element. The fan-out widens the audience and nothing else: every recipient is inside the same paired-Noise-session trust boundary the requester is, and each could already read the label back off its next list_conversations (#2208). Its byte bound is a size limit and NOT a safety property — see protocol.MaxWorkspaceLabelBytes, which says so at length. Validity is inherited rather than checked: encoding/json substitutes U+FFFD for invalid bytes and unpaired surrogates while decoding into a Go string, so the value handed to SetWorkspaceLabel is always valid UTF-8, which is exactly the assumption that setter documents it relies on.
The not-found refusal is the label map's ONLY CEILING, a containment property rather than a UX nicety: a key is creatable only at a path that byte-equals a stored cwd, so the key count is bounded by the number of distinct cwds the daemon hosts. Relaxing it would remove that bound.
All four reject branches reply with a fixed static string, so no payload byte — path, label, or decode error — reaches the wire on a refusal, and none of them stores anything.
Logging follows set_system_prompt's strict posture rather than rename_conversation's, and the divergence is deliberate — do NOT "fix" it back by pattern-matching the sibling that logs its conversation_id. Every branch logs event and conn_id (daemon-minted) and nothing else. Never logged: the label (operator content), the path (a host filesystem path, and attacker-supplied on every reject branch), and the decode error. The single exception is persist_failed's err, a filesystem error naming the daemon's own registry path. The cost is visible and accepted: the record says a label changed and over which conn_id, but not for which workspace.
func RequestClaudeAccount ¶ added in v0.36.0
func RequestClaudeAccount(src ClaudeAccountSource, logger *slog.Logger) dispatch.Handler
RequestClaudeAccount answers request_claude_account with one claude_account to the requester. A failed source read is reported in-band by the payload's state, never as an error frame.
func RequestHostSystemPrompt ¶ added in v0.33.0
func RequestHostSystemPrompt(store HostSystemPromptStore, logger *slog.Logger) dispatch.Handler
RequestHostSystemPrompt reads the paired daemon's current and reset values.
func SendMessage ¶
func SendMessage(router SessionRouter, queue Enqueuer, resolve AttachmentResolver, reg ConversationAutoNamer, registryPath string, announce ConversationAnnouncer, reset ConversationResetter, logger *slog.Logger) dispatch.Handler
SendMessage returns a dispatch.Handler that processes a send_message frame from the phone. router validates the frame's ConversationID against its bound claude session (#678) and stamps the active-conversation cursor (#687); queue is the daemon's inbound backlog the message is appended to; logger is the daemon's slog logger used for every branch's structured event.
Since #721 the handler acks on ENQUEUE (accepted into the backlog), not on delivery-confirm. It validates the binding synchronously, enqueues non-blocking, and returns an ack; the daemon's msgqueue drain delivers the backlog one message at a time through the reliable WriteUserTurn path, paced by claude reaching idle (#704). This is the ADR 025 line 123 contract — send_message is unchanged at the wire level, queued by the daemon when claude is busy.
The ack contract (which failures still produce an error reply vs are absorbed by the drain) is asymmetric by design:
- At enqueue we have a live phone to tell "retry", so a malformed payload, an unknown conversation, and an unbound conversation are all rejected synchronously, before any enqueue; a full backlog is rejected at the enqueue point (Enqueue returns 0) with the same retryable shape.
- Once enqueued, the ack promised delivery, so a transient resolve/activate/ write failure is held and retried by the drain rather than surfaced (a conversation that becomes unbound post-ack is retried, not dropped).
SECURITY:
- payload.Text is treated as opaque transit content: it is stored in the in-memory FIFO and reaches the supervised claude child's stdin verbatim only at the drain's WriteUserTurn call. No transformation, no length cap beyond the transport's WS read ceiling (1 MiB; see internal/transport).
- payload.Text is NEVER logged at any level. conversation_id and message_id (phone-supplied opaque ids) plus the assigned queued_msg_id are logged on the enqueue path; the binding-reject paths log conversation_id, and the backlog-full reject logs conversation_id + message_id (no queued_msg_id — nothing was queued).
- The phone supplies only the ConversationID lookup key and the Text; the routing target (the bound session) is read from the server-stored registry row, never phone-writable. An unbound conversation is rejected before enqueue, so a turn is never silently routed to the shared bootstrap session (#678 AC#4).
- Since #2159 a prefix of payload.Text can become the conversation's stored display name, so it crosses into persisted state and onto a broadcast frame. That is not a new class of value in that field — rename_conversation already stores an arbitrary remote string as the name, unbounded — and the derived title is bounded at 41 runes, so this path admits strictly less than the field already did. It is still never logged: see autoNameConversation, which explains why the title counts as the same untrusted content the text is.
Since #2159 it also takes the auto-naming seams: reg is the conversations registry (nil means no registry leg, which names nothing), registryPath is the canonical on-disk path passed to the eager Save, and announce fans the renamed row to every interactive client and may be nil. See autoNameConversation.
Since #2438 reg and registryPath carry a second registry write as well: an accepted message stamps its conversation's LastUsedAt so the 30-day idle sweep spares a conversation in use. A nil registry therefore now names nothing AND stamps nothing. See touchConversation. Since #2456 it also takes reset, the conversation-reset seam an intercepted "/clear" runs instead of enqueuing. See the intercept below and ConversationResetter.
func SetConversationMuted ¶ added in v0.24.0
func SetConversationMuted(reg ConversationMuter, registryPath string, announce ConversationAnnouncer, logger *slog.Logger) dispatch.Handler
SetConversationMuted returns a dispatch.Handler for a set_conversation_muted frame (#2572). It sets or clears the named conversation's IsMuted from the payload's required muted value, eagerly persists the registry so the value survives a daemon restart, replies to the requester with conversation_updated correlated via in_reply_to, and pushes the same record through announce to every interactive conn. The push is what makes a mute set on one client stop alerts on the others without a re-list; archive, the template, has no push. Sending the value the conversation already has succeeds and changes nothing.
announce is the send_message auto-naming announcer (#2159) reused as is: it does not exclude the requester, which folds the pushed record by its payload id. A nil announce means no fan-out.
Muting touches no session: the handler holds no pool or runner seam, so it cannot restart, spawn or interrupt anything.
SECURITY (security-sensitive label): conversation_id is used only as an exact-match registry key inside SetMuted and Get; muted is a bool. Every reject replies with a fixed static message, and no reject branch logs a payload field: not the decode err (encoding/json can quote input bytes), not conversation_id (a partial decode can leave raw bytes in it, and an unknown id is still client-supplied bytes). Only the success branch logs the id, once the registry has proven it names a real row.
func SetHostSystemPrompt ¶ added in v0.33.0
func SetHostSystemPrompt(store HostSystemPromptStore, logger *slog.Logger) dispatch.Handler
SetHostSystemPrompt acknowledges only after the pool has persisted the value.
func SetSystemPrompt ¶ added in v0.16.0
func SetSystemPrompt(reg ConversationSystemPromptSetter, registryPath string, logger *slog.Logger) dispatch.Handler
SetSystemPrompt returns a dispatch.Handler that processes a set_system_prompt frame from a paired client: it stores or clears a conversation's durable per-conversation system prompt — the operator-authored text every session that conversation spawns is given — eagerly persists the registry so the change survives a daemon restart, and replies with the reused conversation_updated record correlated via in_reply_to.
Keyed by CONVERSATION, not by session, and deliberately so: a prompt must be settable with no session live and must outlive every session the conversation has. (The session-keyed sibling is set_session_settings, which reaches sessions.Pool.UpdateSettings and pairs with a restart. This verb does not, and must not.)
The new value takes effect at the conversation's NEXT session start, not on a running child — the daemon stores the value and leaves the live session alone. That cost is real and is surfaced rather than hidden: an operator who edits the prompt and keeps typing sees no change. Telling them why is the read half's job (#2152) and the client's.
reg is the conversations registry (the single writer — no reload-before-save); registryPath is the canonical on-disk path passed to the eager Save; logger is the daemon's slog logger.
SECURITY (this verb is security-sensitive — it stores untrusted operator TEXT supplied by a network-paired party, text that becomes standing instructions to a claude child holding full tool permissions):
Reachability is the authenticated, paired Noise session. A frame is decrypted under the session's receive state before it reaches dispatch, so only the paired phone arrives here — the same gate every conversation write verb has, needing no new code. The interactive capability is NOT an inbound gate (V2Session.interactive is read only in the outbound ActiveConns fan-out), which is why change_workspace carries no such check either.
No privilege is escalated: the same gate already permits send_message, i.e. arbitrary user-role input to that same claude. What IS new is durability — a prompt survives restarts, applies to every future session including ones started from the host CLI, and appears in no message history. Making it readable so an operator can see what is set is #2152.
Validation is delegated whole to the registry door and re-implemented nowhere. The handler does NO work before that call, which is what makes "nothing is persisted on a reject" a property of the door rather than of handler discipline.
The reply cannot carry the prompt: ConversationUpdatedPayload has no such field (see the note there). A projection type that lacks a field is a stronger guarantee than a handler that declines to fill one in.
Logging divergence from BOTH templates — keep it, do NOT "fix" it back by pattern-matching change_workspace or archive_conversation, which each log conversation_id as a structured field on their non-malformed branches. This handler logs conversation_id on NO branch, the success path included. Only conn_id (daemon-minted) and a per-branch event string appear. Never logged: the prompt, its length, the conversation id, the decode error (Go's json.Unmarshal errors can embed offending input bytes), and the registry sentinel — the sentinels are static and would be safe, but a distinct event per branch carries the same diagnostic signal with no per-sentinel judgment call. The single exception is persist_failed's err, a filesystem error naming the daemon's own registry path.
The cost of that is visible and accepted: the applied record says a prompt changed and over which conn_id, but not which conversation.
Types ¶
type AttachmentResolver ¶ added in v0.16.0
AttachmentResolver resolves one attachment id named by a send_message to the on-host path of its stored file, confined to conversationID. *The* production implementation adapts attachments.ResolvePath; the interface lives here, consumer-side, so handlers/ stays free of an internal/attachments import (mirrors SessionRouter and Enqueuer).
conversationID MUST be an id the caller has already validated against the registry binding — ResolvePath's precondition, which it cannot check itself and which carries the whole confinement property. SendMessage discharges it by calling SessionRouter.Route first, and only then resolving against that same id; see the ordering note there.
COMMA-OK RATHER THAN AN ERROR, deliberately, and for a logging reason rather than an aesthetic one. ResolvePath answers exactly one sentinel for an unknown id, a non-canonical id and an id stored under a different conversation alike, so an error carries nothing a caller could branch on — but its shape-invalid refusal formats the RAW client-supplied id into its message, which is a log-injection value docs/protocol-mobile.md § Attachments forbids logging. The adapter is the only scope that holds that error, and it discards it, so the handler cannot log what it never receives.
A nil AttachmentResolver refuses every id: a message naming attachments is answered attachment.not_found, and one naming none is unaffected. Fail-closed, so an unwired seam can never deliver a message with its attachments silently dropped.
type ClaudeAccountSource ¶ added in v0.36.0
type ClaudeAccountSource interface {
ClaudeAccount() protocol.ClaudeAccountPayload
}
ClaudeAccountSource reports the daemon's Claude account source as wire data. It cannot trigger a read: the reply is the outcome of the latest read the daemon made on its own.
type ConversationAnnouncer ¶ added in v0.16.0
type ConversationAnnouncer func(p protocol.ConversationUpdatedPayload)
ConversationAnnouncer fans a conversation_updated record, unsolicited, to every interactive-capable connected client. It is supplied by cmd/pyry, where #2156's emitter closes over the v2 session manager; this package cannot name that manager, so it takes this func instead. Its signature matches that emitter's announce exactly, so the wiring needs no adapting closure beyond a nil guard.
IT TAKES NO excludeConnID, unlike WorkspaceAnnouncer, and the difference is what the requester already holds. rename_workspace answers its requester with the very record it broadcasts, so pushing it again would be a duplicate; a send_message is answered with an ack carrying no record at all, so excluding the sender would starve the one client that caused the change.
It RETURNS NOTHING, which is the contract rather than an omission: nothing about the fan-out may fail the message the operator sent. A nil ConversationAnnouncer is valid and means "no fan-out" — the shape a caller with no relay leg takes.
type ConversationArchiver ¶ added in v0.16.0
type ConversationArchiver interface {
SetArchived(id conversations.ConversationID, archived bool, now time.Time) bool
Get(id conversations.ConversationID) (conversations.Conversation, bool)
Save(path string) error
// WorkspaceLabel supplies the reply's workspace_label (#2210). Archiving a
// conversation does not un-name its folder, so the flip and the restore both
// report the label exactly as an untouched row would.
WorkspaceLabel(cwd string) (string, bool)
}
ConversationArchiver is the minimal write surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required. SetArchived flips exactly the durable IsArchived flag and its ArchivedAt stamp (#880's deterministic mutator, stamped by #2698 with the now the handler passes); Get snapshots the post-flip record for the reply; Save eagerly persists.
type ConversationAutoNamer ¶ added in v0.16.0
type ConversationAutoNamer interface {
Update(id conversations.ConversationID, fn func(*conversations.Conversation)) bool
Save(path string) error
WorkspaceLabel(cwd string) (string, bool)
}
ConversationAutoNamer is the minimal registry write surface the auto-naming step consumes. *conversations.Registry satisfies it structurally; no adapter required.
Method-set-identical to ConversationRenamer and still declared separately, matching this package's one-narrow-interface-per-handler convention (ConversationPromoter, ConversationArchiver and ConversationDeleter already overlap each other). The difference that earns the second name is the contract stated here rather than the methods: this consumer writes Name ONLY over a nil one, which the rename interface must not claim.
WorkspaceLabel supplies the pushed record's workspace_label (#2210) and MUST NOT be called from inside the Update callback: Update holds the registry's mutex for the callback's duration and this method takes that same non-reentrant lock, so a read there parks the goroutine forever holding the registry lock and stalls every registry consumer — a denial of service reachable by one ordinary send_message. autoNameConversation captures the cwd in the callback and reads the label after Update returns.
type ConversationCreator ¶ added in v0.15.0
type ConversationCreator interface {
Create(c conversations.Conversation)
Save(path string) error
// WorkspaceLabel supplies the reply's workspace_label (#2210). A freshly
// created conversation inherits whatever name its workspace already carries,
// so a client that creates into a labelled folder renders the label from this
// reply rather than from its next list.
WorkspaceLabel(cwd string) (string, bool)
}
ConversationCreator is the minimal write surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required.
type ConversationDeleter ¶ added in v0.16.0
type ConversationDeleter interface {
Delete(id conversations.ConversationID) bool
Save(path string) error
}
ConversationDeleter is the minimal write surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required.
type ConversationLister ¶
type ConversationLister interface {
List(filter ...conversations.ListFilter) []conversations.Conversation
WorkspaceLabel(cwd string) (string, bool)
}
ConversationLister is the minimal surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required. The variadic shape mirrors conversations.Registry.List exactly so structural matching holds.
WorkspaceLabel (#2208) is the per-key read the row projection needs. Its presence here is not in tension with WorkspaceLabeler in rename_workspace.go deliberately lacking one: that interface omits the door because its reply echoes the requester's own validated value, so having no way to fetch a stored label is a disclosure barrier. This handler's job IS to disclose the stored label, to every client already permitted to read the row's cwd.
type ConversationMuter ¶ added in v0.24.0
type ConversationMuter interface {
SetMuted(id conversations.ConversationID, muted bool) bool
Get(id conversations.ConversationID) (conversations.Conversation, bool)
Save(path string) error
WorkspaceLabel(cwd string) (string, bool)
}
ConversationMuter is the minimal write surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally. SetMuted writes exactly the durable IsMuted flag; Get snapshots the stored record for the reply and the push; Save eagerly persists; WorkspaceLabel fills the record's workspace_label, which muting does not change.
type ConversationPromoter ¶ added in v0.16.0
type ConversationPromoter interface {
Promote(id conversations.ConversationID, name string) error
Get(id conversations.ConversationID) (conversations.Conversation, bool)
Save(path string) error
// WorkspaceLabel supplies the reply's workspace_label (#2210), read under the
// read-back row's own cwd — the payload's Cwd is not consumed here either.
WorkspaceLabel(cwd string) (string, bool)
}
ConversationPromoter is the minimal registry surface this handler consumes: Promote flips the target row to a named channel, Get reads the promoted row back for the reply (Promote returns only an error, not the updated record), and Save eagerly persists. *conversations.Registry satisfies it structurally; no adapter required.
type ConversationReadMarker ¶ added in v0.33.0
type ConversationReadMarker interface {
Get(id conversations.ConversationID) (conversations.Conversation, bool)
AdvanceReadUpTo(id conversations.ConversationID, upTo, latest uint64, path string) (conversations.Conversation, bool, error)
WorkspaceLabel(cwd string) (string, bool)
}
ConversationReadMarker is the registry surface MarkConversationRead consumes. *conversations.Registry satisfies it structurally. AdvanceReadUpTo applies the clamped, monotonic advance and persists it itself; Get resolves the row before its history is read; WorkspaceLabel fills the record's workspace_label.
type ConversationRenamer ¶ added in v0.16.0
type ConversationRenamer interface {
Update(id conversations.ConversationID, fn func(*conversations.Conversation)) bool
Save(path string) error
// WorkspaceLabel supplies the reply's workspace_label (#2210) and MUST NOT be
// called from inside the Update callback: Update holds the registry's mutex
// for the callback's duration and this method takes the same non-reentrant
// lock, so a read there deadlocks the daemon. The handler captures the cwd in
// the callback and reads after Update returns.
WorkspaceLabel(cwd string) (string, bool)
}
ConversationRenamer is the minimal write surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required.
type ConversationResetter ¶ added in v0.19.0
ConversationResetter starts the conversation reset an intercepted "/clear" runs (#2456): the outgoing child's wrap-up turn, its handoff note, and the rotation onto a fresh session. cmd/pyry's activeSessionStarter is the production implementation, and it is the SAME value an inbound new_session reaches through relay.SessionStarter — which is the whole point of this seam. The two verbs give the same reset because they call one entry point, not because two implementations agree.
Named for the role this handler puts it to (the package convention that gives us SessionRouter and ConversationToucher) while keeping the method name of the sealed surface — the same split relay.SessionStarter's own doc argues for. That name difference costs nothing at the wiring site: handlers/ imports neither internal/relay nor internal/sessions, and an interface value is assignable to any interface its method set covers, so cmd/pyry passes its existing relay.SessionStarter-typed field with no adapter (as it already does for ConversationToucher over the registry).
THE PLAIN FORM, NOT relay.LateSessionStarter, and deliberately so. #2443's new_session.workspace_refused reply is the late form's entire reason, and it is correlated by in_reply_to against a new_session frame; answering a send_message with it would misreport which frame it describes. A "/clear" whose rotation cannot re-enter the conversation's recorded workspace therefore gets no error frame at all — see the intercept in SendMessage.
conversationID MUST already be registry-validated by the caller. SendMessage discharges that by intercepting only BELOW SessionRouter.Route, so the id crossing this seam is a known registry key with a live binding — stricter than the raw client string relay's own new_session path hands the same entry point.
Every outcome is BEST-EFFORT from this handler's side: an inert arm, a reset already in progress, and a failed rotation all mean the message is gone and the client has its ack, so there is nothing to roll back and no reply is owed. That is handleNewSession's posture for the same seam, and SendMessage keeps it.
type ConversationSystemPromptSetter ¶ added in v0.16.0
type ConversationSystemPromptSetter interface {
SetSystemPrompt(id conversations.ConversationID, prompt *string) error
Get(id conversations.ConversationID) (conversations.Conversation, bool)
Save(path string) error
// WorkspaceLabel supplies the reply's workspace_label (#2210). It is a fourth
// registry door on a handler whose narrowness is itself asserted — see
// TestSetSystemPrompt_TouchesNoSessionSurface, which pins the exact call
// sequence. Still a conversations-registry read and still no session,
// pool or runner seam.
WorkspaceLabel(cwd string) (string, bool)
}
ConversationSystemPromptSetter is the minimal write surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required. SetSystemPrompt is #2149's validating door (byte bound, UTF-8 validity, then existence, all under the registry lock); Get snapshots the post-write record for the reply, because unlike Update that door returns an error rather than the mutated record; Save eagerly persists.
That this interface names NO session, pool or runner surface is load-bearing, not incidental — it is the structural half of "setting the prompt leaves a running session alone". The handler cannot restart, rotate, recompose the argv of, or interrupt a live child because it holds no seam through which any of those could be reached. Do not widen it. The value's route to a running session's NEXT start is #2150's refreshSystemPrompt, called from Pool.Activate, which re-reads exactly the registry field written here.
type ConversationToucher ¶ added in v0.19.0
type ConversationToucher interface {
Update(id conversations.ConversationID, fn func(*conversations.Conversation)) bool
Save(path string) error
}
ConversationToucher is the registry write surface the last-used bump consumes (#2438): one locked mutation, plus the eager persist that follows it.
Deliberately NARROWER than ConversationAutoNamer rather than a reuse of it, even though the same value satisfies both and SendMessage hands its one registry parameter to each step — an interface value is assignable to any interface its method set covers, so the narrowing costs no adapter and no constructor argument. The separate name is what keeps the auto-namer's stated contract honest: that interface promises it writes Name only over a nil one, and a step writing LastUsedAt on every accepted message must not quietly arrive under that promise.
Update's callback contract is the registry's own (ADR 022): it runs holding the registry mutex, so it must not call back into the registry, and it must not retain the *Conversation past return.
type ConversationWorkspaceUpdater ¶ added in v0.16.0
type ConversationWorkspaceUpdater interface {
Update(id conversations.ConversationID, fn func(*conversations.Conversation)) bool
Save(path string) error
// WorkspaceLabel supplies the reply's workspace_label (#2210) and MUST NOT be
// called from inside the Update callback: Update holds the registry's mutex
// for the callback's duration and this method takes the same non-reentrant
// lock, so a read there deadlocks the daemon. The handler reads after Update
// returns.
WorkspaceLabel(cwd string) (string, bool)
}
ConversationWorkspaceUpdater is the minimal write surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required.
type CreateSettings ¶ added in v0.28.0
CreateSettings is a create_conversation's requested model and effort (#2665), the payload's own pointers: nil is absent, and a pointer to "" is the agent's default, as on set_session_settings.
type Enqueuer ¶ added in v0.15.0
type Enqueuer interface {
EnqueueSent(conversationID, messageID, text, delivery string, attachmentIDs []string, deviceName, clientVersion string, clientSentAt time.Time) uint64
}
Enqueuer is the inbound backlog the send_message handler appends to instead of delivering synchronously. *msgqueue.Queue satisfies it. The interface is defined here, consumer-side, so handlers/ stays free of an internal/msgqueue import (mirrors SessionRouter and TurnWriter). Enqueue is non-blocking and returns the stable per-conversation id assigned to the message (>= 1), or 0 if the conversation's backlog is at capacity and the message was rejected (reject, never drop) — the handler maps a 0 to a retryable "backlog full" reply.
Since #2038 the method is EnqueueDelivery rather than Enqueue: a message naming attachments is DELIVERED as a composed prompt naming their on-host paths while the text a client reads back stays the user's own words. Passing both halves here — rather than widening what is queued — is what keeps a host path off the wire on both queue_state arms without any consumer having to remember to strip it. Since #2092 it also takes the client's own messageID, relayed verbatim onto the queued record so a client can merge the queued row with the optimistic echo it already drew. The handler neither validates, normalises nor mints it — an empty id is legal and stays empty. Since #2596 it is EnqueueAttached and also takes the resolved attachment ids, stored beside text so the history log keeps them on the operator's turn. The ids travel as their own argument, never derived from delivery, which is the half that names on-host paths. Since #2704 it is EnqueueSent and also takes who sent the message — the pairing record's device name and the app version this connection's hello reported — and the client's tap time, already parsed and normalised to UTC by parseClientSentAt (zero when absent or unparseable). Positional, because a struct for them would have to live in a package both sides import.
type HostSystemPromptStore ¶ added in v0.33.0
type HostSystemPromptStore interface {
DaemonInstructions() string
DefaultDaemonInstructions() string
SetDaemonInstructions(string) error
}
HostSystemPromptStore exposes only the daemon-wide durable instructions door. It cannot look up, restart, rotate or interrupt a conversation session.
type RecentWorkspacesReader ¶ added in v0.16.0
type RecentWorkspacesReader interface {
List(filter ...conversations.ListFilter) []conversations.Conversation
}
RecentWorkspacesReader is the minimal surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required. The variadic shape mirrors conversations.Registry.List exactly so structural matching holds.
A fresh interface rather than a reuse of ConversationLister: the per-handler consumer-named narrow interface is the convention in this package, and it keeps the two read handlers decoupled. The one-line duplication is intentional.
type SessionCreator ¶ added in v0.15.0
type SessionCreator interface {
Create(ctx context.Context, label, spawnDir, agent string, settings CreateSettings) (sessionID, dir string, err error)
}
SessionCreator is the minimal session-mint surface this handler consumes from the sessions pool: mint and supervise one dedicated session of the given agent that will spawn in spawnDir, returning the session id and the directory it will spawn in. agent is protocol.AgentClaude or protocol.AgentCodex, already validated by the handler (#2647); an implementation never sees another value. It does NOT start the child (#2085) — that happens on the conversation's first message, so that every per-session setting chosen before it is simply what the child launches with. It is adapted at the cmd/pyry boundary (sessionMinter) rather than satisfying *sessions.Pool directly — keeping handlers/ free of internal/sessions imports, mirroring TurnWriter.
spawnDir == "" → the daemon's shared trusted workdir (default, unchanged). A non-empty spawnDir is the phone's *requested* working directory (the raw, untrusted conversation Cwd); the implementation validates it (confine to $HOME, symlink-resolve both sides) and trust-marks it before spawning. A requested dir that escapes $HOME is rejected with an error wrapping ErrSpawnDirRejected; the handler maps that to a non-retryable reply.
The returned dir is the validator's output — "" for an empty spawnDir, the confined, trust-marked realpath otherwise — and it is what the handler records as the conversation's Cwd for a set request (#2568). Returning it from the one place that resolves is what keeps the recorded path and the spawn dir from disagreeing: "default", "~/x/default" and "/home/u/x/default" all spawn in one folder and must be stored as one workspace.
settings is the request's model and effort (#2665), already past the shape checks. Create checks a present, non-empty one against agent's own vocabulary before anything else it does — before resolving spawnDir, which trust-marks a directory, and before the mint — and a refusal returns relay.ErrModelNotOffered, relay.ErrEffortNotOffered or relay.ErrModelVocabularyUnavailable with nothing created. An accepted value is the session's stored setting from the mint; an absent one keeps what a mint gives today.
type SessionHarnessFunc ¶ added in v0.27.0
SessionHarnessFunc answers the agent that runs the pool session sessionID, for a session the pool holds live or dormant; ok is false for any other id. Built over sessions.Pool.HarnessFor at the composition root, which keeps the internal/sessions dependency out of this package.
type SessionRouter ¶ added in v0.15.0
type SessionRouter interface {
Route(conversationID string) (TurnWriter, error)
}
SessionRouter resolves a send_message frame's conversation id to the write surface for that conversation's bound claude session (#678). Resolution is a pure in-memory lookup (no I/O, non-blocking) — the blocking activation happens in the returned TurnWriter's Activate, under the handler's existing budget. The interface lives in this package, returning a TurnWriter rather than any internal/sessions type, so handlers/ stays free of an internal/sessions import (mirrors SessionCreator in create_conversation.go).
Failure mapping the handler relies on:
- unknown conversation → conversations.ErrConversationNotFound (maps to conversation.not_found, not retryable)
- conversation has no bound session, or the bound session id is not in the pool → any other non-nil error (maps to retryable server.binary_offline)
type TurnWriter ¶
type TurnWriter interface {
Activate(ctx context.Context) error
WriteUserTurn(ctx context.Context, conversationID string, payload []byte) error
}
TurnWriter is the minimal per-conversation write-surface that the inbound delivery seam drives. *sessions.Session satisfies it via one-line passthroughs to Session.Activate and Supervisor.WriteUserTurn. The interface lives in this package so handlers/ stays free of internal/sessions and internal/supervisor imports.
Since #721 the send_message handler no longer drives a TurnWriter directly — it enqueues, and the daemon's msgqueue drain (cmd/pyry.newInboundDeliver) resolves and writes one message at a time. SessionRouter.Route still returns a TurnWriter so the handler can validate the binding before enqueue.
Activate is called before WriteUserTurn so an idle-evicted bootstrap session lazily respawns claude on the next delivery rather than dropping it silently (#396). On an already-active session Activate is a near-no-op (two non-blocking channel receives).
type WorkspaceAnnouncer ¶ added in v0.16.0
type WorkspaceAnnouncer func(p protocol.WorkspaceUpdatedPayload, excludeConnID string)
WorkspaceAnnouncer fans a workspace_updated record, unsolicited, to every connected interactive client EXCEPT the one named by excludeConnID — the requester, which already holds its correlated reply. It is supplied by cmd/pyry, where the emitter closes over the v2 session manager; the handler cannot name that manager, so it takes this func instead.
excludeConnID is a dispatch.Conn.ConnID() value, compared by the emitter against relay.ActiveConn.ConnID — one string space, no mapping. Exclusion is therefore per CONN and not per device: a requester with a second client open is pushed on that second conn, which asked for nothing.
It RETURNS NOTHING, and that is the contract rather than an omission: nothing about the fan-out may fail the operation the operator asked for. A nil WorkspaceAnnouncer is valid and means "no fan-out" — the shape a caller with no relay leg takes, and the shape every test written before #2209 still uses.
type WorkspaceFolderResolver ¶ added in v0.16.0
WorkspaceFolderResolver validates and creates the target folder under an untrusted parent path, returning the created folder's realpath confined to $HOME. It is injected at the cmd/pyry boundary (resolveWorkspaceFolder) so internal/relay/handlers stays free of cmd/pyry imports — the same seam change_workspace uses for WorkspaceResolver and create_conversation for SessionCreator. Any failure (target escapes $HOME after symlink resolution, is unresolvable, or cannot be created) is returned as an error wrapping ErrWorkspaceFolderRejected. On an escape the resolver's confiner creates nothing (the $HOME check runs before MkdirAll); on an already-existing folder it returns that folder's realpath (idempotent MkdirAll semantics).
type WorkspaceLabeler ¶ added in v0.16.0
type WorkspaceLabeler interface {
List(filter ...conversations.ListFilter) []conversations.Conversation
SetWorkspaceLabel(cwd string, label *string)
Save(path string) error
}
WorkspaceLabeler is the minimal surface this handler consumes from the conversations registry. *conversations.Registry satisfies it structurally; no adapter required. The List line is copied verbatim from RecentWorkspacesReader so the variadic signature keeps matching structurally.
IT DELIBERATELY HAS NO WorkspaceLabel READ METHOD. The reply's label is the request's own value, which IS the stored value by SetWorkspaceLabel's verbatim-store contract, so no read-back is needed — and lacking the method makes it structurally impossible for this handler to reply with a label the requester did not itself supply. A projection that cannot reach a value is a stronger guarantee than a handler that declines to fetch one. Do not widen it.
type WorkspaceResolver ¶ added in v0.16.0
WorkspaceResolver validates and canonicalises an untrusted target workspace path, returning the realpath confined to $HOME. It is injected at the cmd/pyry boundary (resolveWorkspaceDir) so internal/relay/handlers stays free of cmd/pyry imports — the same seam create_conversation uses for SessionCreator. A path escaping $HOME after symlink resolution, or one that is unresolvable, is returned as an error wrapping ErrWorkspaceRejected. The resolver performs NO filesystem mutation (it uses the strict, non-creating confiner), so any reject leaves no partial state.
Source Files
¶
- archive_conversation.go
- autoname.go
- change_workspace.go
- claude_account.go
- create_conversation.go
- create_workspace_folder.go
- delete_conversation.go
- host_system_prompt.go
- list_conversations.go
- mark_conversation_read.go
- promote_conversation.go
- recent_workspaces.go
- register_push_token.go
- rename_conversation.go
- rename_workspace.go
- send_message.go
- set_conversation_muted.go
- set_system_prompt.go