control

package
v0.41.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package control implements pyry's local control plane: a Unix domain socket that lets clients (such as `pyry status`) query the running daemon.

The protocol is line-delimited JSON. A client opens a connection, writes one JSON-encoded Request, and reads one JSON-encoded Response. The connection is then closed. Future verbs (attach, logs, stop) may extend this with streaming responses or upgraded connections, but the request shape stays JSON for forward compatibility.

Index

Constants

View Source
const DialTimeout = 5 * time.Second

DialTimeout is the default timeout for client connections to the control socket. Short — the server is local and a slow response means something is wrong, not slow.

View Source
const MaxChannelPostBytes = 64 << 10

MaxChannelPostBytes bounds ChannelPostPayload.Text. It is the ONE home of this bound: handleChannelPost refuses past it and the CLI reads the same constant to bound its own --file read, so neither side carries a second number that could drift from this one.

Sized against the consumer rather than against the storage. A paired client's frame is held to 1 MiB by maxFrameBytes in internal/transport, and a served history page carries many entries in one frame, so an entry near that bound could never be read back by the client this verb exists to reach. 64 KiB leaves a page room for a dozen such entries and is still far more than a reminder or an open question needs. Nothing downstream would have bounded it: history.MaxPageEntries caps entries per page, not bytes per entry.

Variables

View Source
var ErrConnNotFound = errors.New("rekey: conn not found")

ErrConnNotFound is returned by Rekeyer.Rekey when the named v2 conn is not currently open on the session manager. The dispatcher maps this to ErrCodeConnNotFound on the wire (via errors.Is, so wrapped sentinels also map); the client helper reconstructs this sentinel from the wire token so callers can errors.Is against it. Owned in this package because the Rekeyer contract is defined here — slice B's *relay.V2SessionManager wraps its internal not-found condition with %w against this sentinel.

View Source
var ErrInstanceRunning = errors.New("another pyry instance is already running")

ErrInstanceRunning is returned by Server.Listen when another live pyry is already answering on the configured socket path. Distinct from a stale-file scenario so callers can present a polished diagnostic without grepping the error message.

Functions

func ChannelNew added in v0.16.0

func ChannelNew(ctx context.Context, socketPath, cwd, name string) (string, error)

ChannelNew asks the daemon to create a promoted conversation — a channel — rooted at cwd, and returns the minted conversation id. cwd is the absolute directory the caller is standing in, sent RAW: the daemon canonicalises, confines it to $HOME and trust-marks the realpath, so this side does no path handling and a client cannot bypass any of it by pre-resolving. An empty name means "derive it from the base name of the resolved path".

Same one-shot dial → encode → decode → close lifecycle as SessionsNew, and the same empty-result guard. No typed ErrorCode is mapped: every refusal this verb produces is a static message the caller prints rather than a sentinel it must reconstruct, so a server error arrives as errors.New(resp.Error) verbatim. That distinction is what lets a caller tell a server refusal from a transport failure — the latter arrives wrapped from request — without a hand-maintained list of message prefixes.

func ChannelPost added in v0.20.0

func ChannelPost(ctx context.Context, socketPath, name, text string) error

ChannelPost asks the daemon to record text in the channel named by label, creating that channel under the daemon's own default workspace when the label matches nothing. It returns nil only when the daemon confirms the message reached the durable log.

Same one-shot dial → encode → decode → close lifecycle as ChannelNew, and the same absence of any ErrorCode mapping: every refusal this verb produces is a message the caller prints rather than a sentinel it must reconstruct.

The missing-OK guard is not defensive padding — it is the difference between "delivered" and "the daemon answered nothing", and the first caller is a cron whose exit code is the only thing anyone reads. SessionsRename's shape, for the same reason.

This side does NO name or content handling. It does not trim the label, and the bound on text is enforced by the daemon; a caller that wants to refuse an over-long message before dialling reads MaxChannelPostBytes itself.

func ConversationNew added in v0.37.0

func ConversationNew(ctx context.Context, socketPath string, payload ConversationPayload) (string, error)

ConversationNew requests creation with caller settings and returns the id. Workspace, name and settings policy belong to the installed daemon creator. Every error returns an empty id; a wire refusal takes precedence over a result.

func ConversationPost added in v0.37.0

func ConversationPost(ctx context.Context, socketPath, conversationID, text string) error

ConversationPost submits a user message to an existing conversation id. It returns nil only for confirmed queue acceptance, not completed model output. Values are forwarded unchanged; validation and id resolution belong to the server and its installed submitter. Wire refusals take precedence over OK.

func MintPairing added in v0.17.0

func MintPairing(ctx context.Context, socketPath, deviceLabel string, allowRemotePermissions bool) (string, error)

MintPairing asks the selected daemon to mint a pairing for deviceLabel with the explicit remote-permission choice. The returned string is an opaque bearer credential and is never included in an error.

Unlike request's general deadline policy, this operation always uses the earlier of the caller's deadline and DialTimeout. Establishing that deadline before request calls dial gives the complete dial, write and read exchange a single budget.

func Rekey added in v0.14.0

func Rekey(ctx context.Context, socketPath, connID string) error

Rekey asks the daemon to trigger an immediate Noise re-key on the named v2 conn. Returns nil on a successful enqueue (the underlying handshake runs asynchronously on the conn's state machine — the helper does not wait for it).

ErrConnNotFound is reconstructed from Response.ErrorCode so callers can errors.Is against it. Other server errors (no rekeyer configured, missing connID, manager-internal failures) return as errors.New(resp.Error) verbatim.

No production caller exists in slice A (#459) — wired now so slice B (#460) is a one-file change in cmd/pyry/. Same one-shot dial → encode → decode → close lifecycle as the other client helpers.

func SessionsHasID added in v0.9.0

func SessionsHasID(ctx context.Context, socketPath, id string) (bool, error)

SessionsHasID asks the daemon whether a session is currently registered under the given UUID. Returns true for a known UUID, false for a well-formed UUID that is absent, and an error for empty / malformed input or transport failure.

In-process Go callers (the future 1.3c-2 foreground auto-attach path) consume this directly. Same one-shot dial → encode → decode → close lifecycle as Status/Logs/Stop/SessionsNew/SessionsRm/ SessionsRename/SessionsList.

No typed-sentinel mapping. Server-side validation errors flow through Response.Error verbatim.

func SessionsNew added in v0.8.0

func SessionsNew(ctx context.Context, socketPath, label string) (string, error)

SessionsNew asks the daemon to mint a new session with the given (possibly empty) label and returns the new session's UUID. In-process Go callers (the future cmd/pyry sessions new) consume this directly. Same one-shot dial → encode → decode → close lifecycle as Status/Logs/Stop.

Empty label sends {"verb":"sessions.new","sessions":{}}; the inner SessionsPayload is non-nil so the field is present, but Label's omitempty drops the empty string. The server treats nil and empty-Label identically.

func SessionsRename added in v0.8.0

func SessionsRename(ctx context.Context, socketPath, id, newLabel string) error

SessionsRename asks the daemon to update the named session's human-friendly label. Empty newLabel is a valid argument meaning "clear the label" — Pool.Rename treats it as such (per #62) and the wire forwards it unchanged via SessionsPayload.NewLabel's omitempty tag (an empty string elides the field, and the server decodes the absent field as "").

Typed errors propagate via Response.ErrorCode — a server response carrying ErrCodeSessionNotFound returns sessions.ErrSessionNotFound directly so callers can errors.Is against it. Other server errors (no sessioner configured, missing id, registry persist failures, ...) return as errors.New(resp.Error) verbatim.

func SessionsRm added in v0.8.0

func SessionsRm(ctx context.Context, socketPath, id string, policy JSONLPolicy) error

SessionsRm asks the daemon to remove the named session and apply the JSONL disposition policy. Empty policy is treated by the server as JSONLPolicyLeave (matches sessions.JSONLLeave's zero-value default).

Typed errors propagate via Response.ErrorCode — a server response carrying ErrCodeSessionNotFound returns sessions.ErrSessionNotFound directly so callers can errors.Is against it; same for ErrCodeCannotRemoveBootstrap. Other server errors (no sessioner configured, missing id, evict failures, ...) return as errors.New(resp.Error) verbatim.

func SlogTee

func SlogTee(next slog.Handler, ring *RingBuffer) slog.Handler

SlogTee returns an slog.Handler that forwards every record to next AND writes a text-formatted copy into the ring buffer. Use it to wrap the supervisor's primary logger so `pyry logs` can replay recent lifecycle events from another shell.

WithAttrs and WithGroup are propagated to BOTH the primary handler (so stderr stays consistent with what callers asked for) AND the parallel text formatter that feeds the ring. Without that propagation, attrs added via slog.Logger.With(...) would silently drop from `pyry logs`.

The one thing the ring copy leaves out is a value implementing LogDaemonOnly() (see daemonLogOnly): next receives it unchanged, the ring shows ringOmitted under the same key.

func Stop

func Stop(ctx context.Context, socketPath string) error

Stop asks the daemon to shut down. Returns when the server has acknowledged the request — the supervisor may still be unwinding its child process and removing the socket file. Callers that need to wait for full shutdown can poll Status until it returns a dial error.

Types

type ApprovePayload added in v0.16.0

type ApprovePayload struct {
	ToolName  string          `json:"tool_name"`
	Input     json.RawMessage `json:"input"`
	ToolUseID string          `json:"tool_use_id"`
}

ApprovePayload is the forwarded tool-approval request the `pyry mcp-approve` subcommand marshals from claude's --permission-prompt-tool call and dials over the control socket. Fields mirror permbridge.Request with the snake_case tags of the T1 spike contract (fixture-p4-approval-contract.json) so the subcommand marshals straight from claude's tool input.

Input is opaque tool-input carried as json.RawMessage so it round-trips byte-verbatim into the registry; the daemon never parses or dispatches on it. ToolUseID is the registry correlation key (not a credential); the server-side guard rejects an empty one. ToolName is echoed only in the content-free decision log's absence — it is never logged.

type ApproveResult added in v0.16.0

type ApproveResult struct {
	Behavior     string          `json:"behavior"`
	UpdatedInput json.RawMessage `json:"updatedInput,omitempty"` // allow only
	Message      string          `json:"message,omitempty"`      // deny only
}

ApproveResult is the allow/deny verdict returned to the socket caller. Its field/tag layout is deliberately byte-identical to permbridge.Verdict's wire shape so the `pyry mcp-approve` subcommand can marshal it straight to claude as the MCP tool result without a second translation. A future drift between the two must be caught here (same mirror justification as SessionInfo vs sessions.SessionInfo):

allow → {"behavior":"allow","updatedInput":{…}}
deny  → {"behavior":"deny","message":"…"}

func Approve added in v0.16.0

func Approve(ctx context.Context, socketPath string, req ApprovePayload) (*ApproveResult, error)

Approve forwards a claude tool-approval request to the daemon over the control socket (the mcp.approve verb, #1104) and returns the daemon's allow/deny verdict. It is the client half consumed by the `pyry mcp-approve` subcommand, which re-frames the verdict as the MCP tool result claude blocks on.

It is bounded by LIVENESS, not by duration — the sole behavioural difference from the other client helpers, which are all sub-second round-trips. No read deadline is derived from the ctx: an approval is held for as long as the daemon holds it, and a client-side ceiling would not merely lose the race for the verdict message but TERMINATE the approval, since closing the conn is what the server reads as a lost caller (#1929). The only things that end the wait are the caller cancelling ctx, the connection ending, and the daemon answering. An undeadlined ctx is therefore genuinely patient here rather than truncated at DialTimeout.

The dial itself still fails fast (<= dialRetryBudget, ~1.5s) on an unreachable socket, independently of the ctx's deadline or absence of one (see dial.go), so a missing daemon yields a bounded error rather than a hang. A daemon that is alive, holds the conn open and never resolves is knowingly NOT bounded here; the daemon owns that guarantee (the pending-approval registry's timer, plus watchApproveConn's disconnect and shutdown denies).

Any error (dial/transport/decode, a server-side Response.Error, or an empty verdict) is returned verbatim: the subcommand fail-closes to a deny on any error, so no typed-sentinel mapping is warranted.

type AttachFilePayload added in v0.16.0

type AttachFilePayload struct {
	SessionID string `json:"sessionID"`
	Path      string `json:"path"`
}

AttachFilePayload names the session making the call and the host path the file to file lives at. Both fields are required and both are rejected empty by handleAttachFile's guard.

SessionID is the CALLER's session, and it is the whole destination mechanism: the daemon maps it to a conversation through its own registry and takes the confinement root from that conversation's recorded workspace. Nothing here names a conversation, and naming one would not be honoured if it did. An empty SessionID is refused rather than defaulted — the seam it would otherwise reach, sessions.Pool.Lookup(""), resolves to the BOOTSTRAP session, so a defaulted empty id would silently file claude's bytes under a conversation that never asked for them.

Path is CLAUDE-AUTHORED and is the security surface of this verb: every other attachment path component is daemon-minted or sanitised from a client-declared name, and this one is a filesystem path chosen by the model naming a file to read. It is confined, never trusted — made absolute against the conversation's workspace, resolved through its symlinks, and boundary-tested against that workspace canonicalised the same way, all before anything opens it. A relative path resolves against the workspace, not against the daemon's process directory.

Neither field is loggable as sent: Path is a host path, and its leaf is the filename docs/protocol-mobile.md § Attachments bans logging for a privacy reason sanitising does not lift.

type AttachFileResult added in v0.16.0

type AttachFileResult struct {
	AttachmentID string `json:"attachmentID"`
}

AttachFileResult carries the daemon-minted id of the stored attachment. The id is a lowercase UUIDv4 drawn from crypto/rand (conversations.NewID), obeying the published attachment_id shape, and is NEVER taken from the request — a client-chosen id here would let a caller address, and overwrite, storage it did not create.

The id is not a capability: #2054 re-validates it against the conversation binding on retrieval, so holding one grants nothing an unannounced id would not. Safe to log; nothing else about this exchange is.

func AttachFile added in v0.16.0

func AttachFile(ctx context.Context, socketPath string, req AttachFilePayload) (*AttachFileResult, error)

AttachFile asks the daemon to file the host file at req.Path under the conversation bound to req.SessionID, and returns the minted attachment id.

Built on request, NOT requestPatient: this is a bounded round trip — a confinement check, a file read and a write — not a wait on a human, which is the one thing requestPatient exists for. It is therefore bounded by the ctx's deadline or DialTimeout when it carries none, like every other verb here; a caller filing a large file should pass a ctx whose deadline suits it rather than reaching for the patient helper, whose contract (a wait ended only by cancellation, disconnect or an answer) is wrong for this verb.

Shipped beside the verb rather than left to its consumers: #2165's subcommand and #2166's e2e both dial this, and without it each would write its own framing of the same exchange.

Any error — dial/transport/decode, a server-side Response.Error, or an empty result — is returned verbatim. No typed-sentinel mapping is warranted: the server's refusals are deliberately static prose for claude to act on, not tokens for a caller to branch on, which is why no ErrorCode accompanies them.

The returned id is safe to log. Nothing in req is: Path is a host path whose leaf is a filename docs/protocol-mobile.md § Attachments bans logging.

type ChannelNewResult added in v0.16.0

type ChannelNewResult struct {
	ConversationID string `json:"conversationID"`
}

ChannelNewResult carries the id of the created conversation. The id is a lowercase UUIDv4 drawn from crypto/rand (conversations.NewID) and is never taken from the request — a caller-chosen id could collide with, or overwrite, a row it did not create. Safe to log and to print: it is what the CLI writes to stdout.

The bound session id is deliberately NOT echoed. The row carries one, exactly as a client-created conversation's does, but nothing the operator does next takes a session id, and a verb that answers with more than its caller needs is a verb whose wire has to be kept compatible for no reason.

type ChannelPayload added in v0.16.0

type ChannelPayload struct {
	Cwd  string `json:"cwd"`
	Name string `json:"name,omitempty"`
}

ChannelPayload names the host directory a new channel is rooted at and, optionally, what to call it.

Cwd is the absolute directory the calling CLI is standing in (os.Getwd), sent raw: the daemon canonicalises and confines it, so the client does no path handling either. It has NO omitempty — an empty Cwd is invalid input rather than a defaulted one, and is refused twice over (see handleChannelNew). Deliberately so: the seam it would otherwise reach reads the empty string as "spawn in the shared trusted workdir" and skips confinement entirely, which is the same fail-open shape AttachFilePayload.SessionID guards against.

Name is the channel's display name. Empty means "derive it from the base name of the RESOLVED path", computed daemon-side after confinement so a symlinked entry directory names the real folder. Duplicate names are permitted, by construction: the registry's Create is a bare append and the wire create_conversation has the same property, so a uniqueness rule here would make this verb's rows distinguishable from a client's.

type ChannelPostPayload added in v0.20.0

type ChannelPostPayload struct {
	Name string `json:"name"`
	Text string `json:"text"`
}

ChannelPostPayload names the channel to post into and the content to record.

Name is the channel's display label, matched by EXACT name against non-archived promoted conversations. It is caller-authored text and is never echoed by a refusal, never logged, and never used to derive a filesystem path — the durable log keys on the daemon-minted conversation id.

Text is the message body. Neither field carries omitempty: an empty name and an empty message are invalid input rather than defaulted ones, which is ChannelPayload.Cwd's reasoning, and both are refused by handleChannelPost.

There is deliberately NO Cwd. A label that matches nothing creates its channel under the daemon's own default workspace, so no caller-supplied path crosses this wire and this verb carries none of channel.new's confinement surface.

type ConversationNewResult added in v0.37.0

type ConversationNewResult struct {
	ConversationID string `json:"conversationID"`
}

ConversationNewResult carries the creator's nonempty conversation id.

type ConversationPayload added in v0.37.0

type ConversationPayload struct {
	Cwd    string  `json:"cwd"`
	Name   string  `json:"name,omitempty"`
	Type   *string `json:"type,omitempty"`
	Model  *string `json:"model,omitempty"`
	Effort *string `json:"effort,omitempty"`
}

ConversationPayload carries caller-authored creation inputs. Cwd must be nonempty; workspace validation and name defaults belong to the creator. Type defaults to chat when absent/null, and otherwise must be chat or channel. Model/Effort follow protocol.CreateConversationPayload: absent/null is unset, while an explicit empty string remains present. The creator owns their policy.

type ConversationPostPayload added in v0.37.0

type ConversationPostPayload struct {
	ConversationID string `json:"conversationID"`
	Text           string `json:"text"`
}

ConversationPostPayload addresses an existing conversation with a user message. Both fields are required and forwarded unchanged to the installed submitter. Text is bounded by MaxChannelPostBytes in decoded UTF-8 bytes. Control performs no id resolution or creation; neither field is logged or echoed in diagnostics.

type ErrorCode added in v0.8.0

type ErrorCode string

ErrorCode is a stable wire token identifying a typed server-side error. Empty when the response carries no typed sentinel; the server still populates Response.Error with the human-readable message in every error case. Decoupling the token from the message string lets the client map it back to a Go sentinel for errors.Is matching without coupling the wire contract to error message text.

const (
	// ErrCodeSessionNotFound is set by the server when Pool.Remove returns
	// sessions.ErrSessionNotFound. The client maps this back to the same
	// sentinel so callers can errors.Is against it.
	ErrCodeSessionNotFound ErrorCode = "session_not_found"

	// ErrCodeCannotRemoveBootstrap is set by the server when Pool.Remove
	// returns sessions.ErrCannotRemoveBootstrap.
	ErrCodeCannotRemoveBootstrap ErrorCode = "cannot_remove_bootstrap"

	// ErrCodeConnNotFound is set by the server when Rekeyer.Rekey
	// returns ErrConnNotFound (or any error wrapping it). The client
	// maps this back to the same sentinel so callers can errors.Is
	// against it. Analogue of ErrCodeSessionNotFound for the v2 conn
	// namespace used by VerbRekey.
	ErrCodeConnNotFound ErrorCode = "conn_not_found"
)

type JSONLPolicy added in v0.8.0

type JSONLPolicy string

JSONLPolicy is the wire-level enum selecting how the daemon disposes of a removed session's on-disk JSONL transcript file. Empty string is treated as JSONLPolicyLeave (backward-compat / zero-value ergonomics, same default as sessions.JSONLLeave).

Kept distinct from sessions.JSONLPolicy (a uint8) so protocol.go stays import-free and the wire bytes are jq-debuggable strings rather than integers.

const (
	JSONLPolicyLeave   JSONLPolicy = "leave"
	JSONLPolicyArchive JSONLPolicy = "archive"
	JSONLPolicyPurge   JSONLPolicy = "purge"
)

type Lister added in v0.8.0

type Lister interface {
	List() []sessions.SessionInfo
}

Lister is the per-pool view the control server depends on for the sessions.list verb. *sessions.Pool satisfies it structurally via Pool.List. Defined here, where it is consumed; tests fake it directly.

List returns a snapshot of every session in the pool — bootstrap and minted alike — sorted by LastActiveAt descending with SessionID ascending tiebreak. The bootstrap entry's empty on-disk label is substituted with "bootstrap" by Pool.List itself; this seam renders verbatim. Read-only: does not bump LastActiveAt or transition state. See Pool.List for the full contract.

List does not take a context — Pool.List's signature is () []SessionInfo and the operation is bounded by Pool.mu (RLock) + each Session.lcMu (briefly). The seam mirrors Pool.List's shape so *sessions.Pool satisfies it adapter-free.

type LogProvider

type LogProvider interface {
	// Snapshot returns a copy of the recent log lines, oldest first.
	Snapshot() []string
	// Cap returns the configured buffer capacity. The server reports this
	// to clients so they know whether they have the full history or a
	// tail of a longer one.
	Cap() int
}

LogProvider is the read view the control server depends on for VerbLogs. Defining it here (where it is consumed) keeps the supervisor package free of control-plane concerns.

type LogsPayload

type LogsPayload struct {
	Lines    []string `json:"lines"`
	Capacity int      `json:"capacity"`
}

LogsPayload carries recent supervisor log lines, oldest first. Capacity is the ring buffer's configured size — useful for the client to know whether the response is the full history or a tail of a longer one.

func Logs

func Logs(ctx context.Context, socketPath string) (*LogsPayload, error)

Logs fetches the recent supervisor log lines from the daemon. Lines are returned oldest first.

type PairingPayload added in v0.17.0

type PairingPayload struct {
	DeviceLabel            string `json:"deviceLabel"`
	AllowRemotePermissions bool   `json:"allowRemotePermissions"`
}

PairingPayload carries the only caller-selected inputs to a local pairing mint. Identity, key, relay and registry values belong to the installed provider and cannot be supplied over this control request.

Neither field is omitted: an empty label requests the provider's existing generated fallback, while false is an explicit permission choice.

type PairingResult added in v0.17.0

type PairingResult struct {
	Pairing string `json:"pairing"`
}

PairingResult carries the provider's opaque pairing string. It is a plaintext bearer credential and must not be logged or copied into an error field.

type RekeyPayload added in v0.14.0

type RekeyPayload struct {
	ConnID string `json:"connID"`
}

RekeyPayload carries the v2 conn id to re-key. ConnID has no omitempty: an empty connID is invalid input and the server-side guard (handleRekey) rejects it before calling Rekeyer. The camelCase JSON tag matches the control-socket convention (SessionsPayload.ID) — not to be confused with RoutingEnvelope.ConnID's snake-case `conn_id`, which is the mobile-WS wire and unrelated.

type Rekeyer added in v0.14.0

type Rekeyer interface {
	Rekey(ctx context.Context, connID string) error
}

Rekeyer is the per-conn rekey-trigger view the control server depends on for VerbRekey. Slice B's *relay.V2SessionManager satisfies it via TriggerRekey; slice A (#459) ships no production implementer — until SetRekeyer is called handleRekey replies "rekey: no rekeyer configured".

Rekey triggers an immediate Noise re-key on the named conn (the operator-driven "manual" rekey path in docs/protocol-mobile.md § Re-key). Returns ErrConnNotFound (possibly wrapped) when no conn with the given id is currently open on the v2 session manager — the dispatcher maps this to ErrCodeConnNotFound on the wire via errors.Is. Any other non-nil error is surfaced verbatim through Response.Error with no ErrorCode.

Plumbing channel: the operator-facing verb routes through the control socket rather than a direct in-process call because the `pyry rekey <conn_id>` subcommand runs in a separate process; an in-process channel is not a workable alternative when the trigger originates outside the daemon process. The trade-off is one socket round-trip on a verb the operator invokes interactively — immaterial in practice.

Not embedded into Sessioner: slice B's implementer is a different type from *sessions.Pool, so aggregating would force a stub method on Pool or a covariant adapter. Free-standing matches the Remover/Renamer/Lister "interface-at-the-consumer" pattern.

type Remover added in v0.8.0

type Remover interface {
	Remove(ctx context.Context, id sessions.SessionID, opts sessions.RemoveOptions) error
}

Remover is the per-pool view the control server depends on for session removal. *sessions.Pool satisfies it structurally via Pool.Remove. Defined here, where it is consumed; tests fake it directly.

Remove terminates the named session's child, drops its registry entry, and applies opts.JSONL to the on-disk transcript file. Returns sessions.ErrSessionNotFound for an unknown id, sessions.ErrCannotRemoveBootstrap for the bootstrap entry, or ctx.Err() if termination is cancelled. See Pool.Remove for the full contract.

type Renamer added in v0.8.0

type Renamer interface {
	Rename(id sessions.SessionID, newLabel string) error
}

Renamer is the per-pool view the control server depends on for session rename. *sessions.Pool satisfies it structurally via Pool.Rename. Defined here, where it is consumed; tests fake it directly.

Rename updates the named session's label and persists the change to the registry. Empty newLabel is permitted and clears the on-disk label to "". Returns sessions.ErrSessionNotFound when id is not present in the pool. See Pool.Rename for the full contract, including the no-op shape (newLabel == current label) returning nil without persisting.

Rename does not take a context — Pool.Rename's signature is (id, newLabel) error and the operation is bounded by a single Pool.mu critical section + saveLocked. The seam mirrors Pool.Rename's shape so *sessions.Pool satisfies it adapter-free.

type Request

type Request struct {
	Verb     Verb             `json:"verb"`
	Sessions *SessionsPayload `json:"sessions,omitempty"` // populated for VerbSessionsNew (Phase 1.1+)
	Rekey    *RekeyPayload    `json:"rekey,omitempty"`    // populated for VerbRekey
	Approve  *ApprovePayload  `json:"approve,omitempty"`  // populated for VerbMCPApprove

	AttachFile   *AttachFilePayload   `json:"attachFile,omitempty"`   // populated for VerbAttachFile
	Channel      *ChannelPayload      `json:"channel,omitempty"`      // populated for VerbChannelNew
	Pairing      *PairingPayload      `json:"pairing,omitempty"`      // populated for VerbPairingMint
	Conversation *ConversationPayload `json:"conversation,omitempty"` // populated for VerbConversationNew

	// ChannelPost is a field of its own rather than two more members on
	// ChannelPayload, whose Cwd has no meaning for a post. Additive and
	// omitempty, so every existing verb's encoding stays byte-identical — the
	// property TestProtocol_SessionsRoundTripBackCompat pins.
	ChannelPost *ChannelPostPayload `json:"channelPost,omitempty"` // populated for VerbChannelPost

	ConversationPost *ConversationPostPayload `json:"conversationPost,omitempty"` // populated for VerbConversationPost
}

Request is the wire format for a single client request.

type Response

type Response struct {
	Status          *StatusPayload         `json:"status,omitempty"`
	Logs            *LogsPayload           `json:"logs,omitempty"`
	SessionsNew     *SessionsNewResult     `json:"sessionsNew,omitempty"`     // populated for VerbSessionsNew
	SessionsList    *SessionsListPayload   `json:"sessionsList,omitempty"`    // populated for VerbSessionsList (1.1b-B1)
	SessionsHasID   *SessionsHasIDResult   `json:"sessionsHasID,omitempty"`   // populated for VerbSessionsHasID (1.3c-1)
	Approve         *ApproveResult         `json:"approve,omitempty"`         // populated for VerbMCPApprove
	AttachFile      *AttachFileResult      `json:"attachFile,omitempty"`      // populated for VerbAttachFile
	ChannelNew      *ChannelNewResult      `json:"channelNew,omitempty"`      // populated for VerbChannelNew
	ConversationNew *ConversationNewResult `json:"conversationNew,omitempty"` // populated for VerbConversationNew
	Pairing         *PairingResult         `json:"pairing,omitempty"`         // populated for VerbPairingMint
	UpdateWhenIdle  *UpdateWhenIdleResult  `json:"updateWhenIdle,omitempty"`
	OK              bool                   `json:"ok,omitempty"`
	Error           string                 `json:"error,omitempty"`
	ErrorCode       ErrorCode              `json:"errorCode,omitempty"` // typed sentinel token (1.1d-B1)
}

Response is the wire format for a single server response. On success exactly one of the verb-specific fields is populated:

  • Status: payload for VerbStatus
  • Logs: payload for VerbLogs
  • SessionsNew: payload for VerbSessionsNew
  • SessionsList: payload for VerbSessionsList
  • SessionsHasID: payload for VerbSessionsHasID
  • Approve: verdict for VerbMCPApprove (allow or deny)
  • AttachFile: minted attachment id for VerbAttachFile
  • ChannelNew: minted conversation id for VerbChannelNew
  • ConversationNew: minted conversation id for VerbConversationNew
  • Pairing: opaque bearer string for VerbPairingMint
  • UpdateWhenIdle: scheduling decision for VerbUpdateWhenIdle
  • OK: success acknowledgment for verbs without a typed payload (e.g. VerbStop)

Error is set when the server rejects the request.

type RingBuffer

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

RingBuffer holds the most recent N supervisor log lines for `pyry logs`. Bounded — when it fills, new entries overwrite the oldest. Safe under concurrent reads and writes.

func NewRingBuffer

func NewRingBuffer(size int) *RingBuffer

NewRingBuffer constructs a buffer that holds up to size entries. A size less than 1 yields a buffer of size 1 — there is no "disabled" mode.

func (*RingBuffer) Add

func (r *RingBuffer) Add(line string)

Add appends a line. If the buffer is full, the oldest line is overwritten.

func (*RingBuffer) Cap

func (r *RingBuffer) Cap() int

Cap returns the configured buffer capacity.

func (*RingBuffer) Snapshot

func (r *RingBuffer) Snapshot() []string

Snapshot returns a copy of the entries in order, oldest first.

type Server

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

Server listens on a Unix domain socket and answers control requests.

Lifecycle: NewServer → Listen → Serve(ctx) → Close. Listen creates the socket file (and any missing parent directory) and returns synchronously, so callers can fail fast if the path is unusable. Serve blocks until ctx is cancelled or the listener is closed. Close is safe to call multiple times and removes the socket file.

func NewServer

func NewServer(socketPath string, sessions SessionResolver, logs LogProvider, shutdown func(), log *slog.Logger, sessioner Sessioner) *Server

NewServer constructs a Server. The socket is not opened until Listen.

sessions must be non-nil — every verb that needs session state resolves through it, and the first VerbStatus would otherwise nil-pointer-panic. Passing a nil resolver is a programmer error and panics at construction time so the failure surfaces immediately rather than on a request from a future shell.

logs is optional. When nil, VerbLogs returns an error response.

shutdown is optional. When nil, VerbStop returns an error response. When set, a successful VerbStop invokes it after acknowledging the client — typically the signal-driven context's cancel function so a stop request walks the same shutdown path as SIGINT/SIGTERM.

sessioner is optional. When nil, VerbSessionsNew, VerbSessionsRm, VerbSessionsRename, and VerbSessionsList all return error responses — same precedent as logs/shutdown. VerbSessionsHasID is independent of sessioner (consults SessionResolver instead) and answers correctly even with sessioner == nil. The CLI ticket wires *sessions.Pool here.

func (*Server) Close

func (s *Server) Close() error

Close shuts the listener and removes the socket file. Idempotent. Safe to call from any goroutine, including the ctx-watcher goroutine in Serve.

func (*Server) Listen

func (s *Server) Listen() error

Listen creates the socket file. It is split from Serve so callers can surface "another pyry is running", "socket already in use", or "permission denied" errors before starting the supervisor proper.

Stale sockets from a prior crash are removed transparently. A LIVE pyry on the same path is detected via a short Dial probe and rejected with ErrInstanceRunning, rather than silently hijacking the path — see #17.

func (*Server) Seal added in v0.39.0

func (s *Server) Seal()

Seal refuses new handlers and joins admitted handlers without closing the listener. The bound listener retains instance ownership until Close.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context) error

Serve accepts connections and dispatches requests until ctx is cancelled. Listen must be called first.

func (*Server) SetApprovalRegistry added in v0.16.0

func (s *Server) SetApprovalRegistry(reg *permbridge.Registry, timeout time.Duration)

SetApprovalRegistry installs the pending-approval registry and the human-approval timeout used to service VerbMCPApprove requests. Safe to call from any goroutine; canonically called once between NewServer and Serve as part of daemon startup. A nil registry (never calling this, or v1/foreground) leaves handleApprove replying "no approval registry configured" — the same nil-dependency-degrades-cleanly shape as SetRekeyer.

timeout bounds a pending approval NOBODY CAN ANSWER: permbridge's registry-owned timer denies the request once that window elapses on an approval its liveness report calls unanswerable. With a report installed (#1932's daemon wiring) the bound is conditional — the wait ends within one window of the FIRST reading that says nobody can answer — and with none installed (v1/foreground/relay disabled) it stays the hard deadline it has always been. Threading it through NewServer would cascade across every call site, so it rides the setter like the Rekeyer (see #451 split rationale).

func (*Server) SetApprovalSurfacer added in v0.16.0

func (s *Server) SetApprovalSurfacer(surface func(permbridge.Request) func())

SetApprovalSurfacer installs the optional surfacer that raises a parked approval to interactive clients — as a modal_shown, or as a question_shown when the approval is claude's clarifying-question tool call (#1973) — and returns a retire closure handleApprove defers to guarantee client-side cleanup + dismissal on every terminal Await path (#1080). Safe to call from any goroutine; canonically called once between NewServer and Serve, after SetApprovalRegistry, as part of daemon startup. A nil surfacer (never calling this, or v1/foreground/relay disabled) leaves handleApprove parking-and-awaiting with no client-facing modal — the pre-#1080 behaviour. Mirrors SetApprovalRegistry so NewServer's signature stays frozen across its call-site fan-out.

func (*Server) SetChannelCreator added in v0.16.0

func (s *Server) SetChannelCreator(create func(cwd, name string) (string, error))

SetChannelCreator installs the dependency that services VerbChannelNew: given a host directory and an optional name, it creates a promoted conversation rooted at that directory and returns the minted conversation id. Safe to call from any goroutine; canonically called once between NewServer and Serve as part of daemon startup. Passing nil clears a previously-installed creator (used by tests; production startup installs once and never clears).

Mirrors SetFileAttacher so NewServer's signature stays frozen across its call-site fan-out (see #451 split rationale). A nil creator — never calling this, or v1/foreground — leaves handleChannelNew replying "channel.new: no channel creator configured", the same nil-dependency-degrades-cleanly shape as SetRekeyer and SetApprovalRegistry.

TWO OBLIGATIONS on an implementation, both load-bearing:

The returned error's TEXT reaches the wire verbatim, so every refusal reason must be STATIC: no requested path, no resolved path, no $HOME. This is not general hygiene — the validator such an implementation is expected to reuse (cmd/pyry's resolveSpawnDir) wraps a confinement error whose message embeds both the resolved path and the operator's home directory, so forwarding it unchanged is the failure mode to design against, not a hypothetical one.

And cwd is passed through UNVALIDATED — this package deliberately does no path handling — so the implementation owns confinement in full: confine to $HOME and resolve symlinks BEFORE trust-marking anything, since a trust-mark carries no $HOME bound of its own. An empty cwd never arrives from here, but an implementation must refuse one anyway rather than treat it as a default: the seam it would otherwise reach reads the empty string as "use the shared trusted workdir" and skips validation entirely, which is the same fail-open shape SetFileAttacher's empty-sessionID guard exists to close.

func (*Server) SetChannelPoster added in v0.20.0

func (s *Server) SetChannelPoster(post func(name, text string) error)

SetChannelPoster installs the dependency that services VerbChannelPost: given a channel's display label and a message body, it records that content in the named conversation's durable log, creating the channel first when the label matches nothing. Safe to call from any goroutine; canonically called once between NewServer and Serve as part of daemon startup. Passing nil clears a previously-installed poster (used by tests; production startup installs once and never clears).

Mirrors SetChannelCreator, and for the same reason: everything the work needs — the conversation registry, the durable log, the daemon's resolved default workspace, and the channel creator itself — lives at cmd/pyry's composition root. This package therefore owns the wire and the guard order and nothing else. It does NO name handling in particular: the label reaches the poster exactly as it arrived, not trimmed and not case-folded, so the matching rule lives in one place.

TWO OBLIGATIONS on an implementation, both load-bearing:

The returned error's TEXT reaches the wire verbatim, so every refusal reason must be STATIC — or, where a count genuinely has to be reported, a static format over a value the DAEMON derived. In particular a refusal must not fold back the label it was given: that is caller-authored text, and this verb's whole answer to a mistyped label is that the operator sees a diagnostic, not an echo.

And the message body must never be logged. It is conversation content, and the durable log is the one place it may be written — the discipline appendConversationHistory records for the producers that share it.

func (*Server) SetConversationCreator added in v0.37.0

func (s *Server) SetConversationCreator(create func(cwd, name, conversationType string, model, effort *string) (string, error))

SetConversationCreator installs the independent VerbConversationNew creator. Safe to call concurrently; nil clears it. The creator receives the effective chat/channel type and otherwise unchanged caller values, returning a nonempty id. Like SetChannelCreator, every refusal message MUST be static and input-free: its text reaches the wire verbatim. The creator owns workspace confinement and symlink resolution before trust-marking, name defaults, and model/effort shape and membership validation. It must reject empty cwd even for non-control callers and bound its own work; the control response deadline cannot cancel execution.

func (*Server) SetConversationSubmitter added in v0.37.0

func (s *Server) SetConversationSubmitter(submit func(conversationID, text string) error)

SetConversationSubmitter installs the independent VerbConversationPost callback. Safe to call concurrently; nil clears it. It receives the caller's conversation id and user message unchanged and owns existing-id resolution and queue admission. A nil error means acceptance, not completed model output. It must not create a conversation on a miss or log the raw caller id or message text. Like SetChannelPoster, refusal text MUST be static or a static format over daemon-derived values: it reaches the wire verbatim and must not echo id/text. The submitter must bound its own work; the response deadline cannot cancel it.

func (*Server) SetFileAttacher added in v0.16.0

func (s *Server) SetFileAttacher(attach func(sessionID, path string) (string, error))

SetFileAttacher installs the dependency that services VerbAttachFile: given the calling session's id and a claude-named host path, it confines the path to that session's conversation's recorded workspace, files the bytes, and returns the minted attachment id. Safe to call from any goroutine; canonically called once between NewServer and Serve as part of daemon startup. Passing nil clears a previously-installed attacher (used by tests; production startup installs once and never clears).

Mirrors SetApprovalSurfacer so NewServer's signature stays frozen across its call-site fan-out (see #451 split rationale). A nil attacher — never calling this, or v1/foreground — leaves handleAttachFile replying "attachment.file: no file attacher configured", the same nil-dependency-degrades-cleanly shape as SetRekeyer and SetApprovalRegistry.

The returned error's TEXT reaches the wire verbatim, so an implementation must keep every refusal reason static: no host path, no filename, no workspace and no session id. docs/protocol-mobile.md § Attachments bans logging a filename for a privacy reason sanitising does not lift, and a host path is worse. Reasons must still be actionable — claude acts on them by writing the file into the workspace and calling again, which is what an explicit tool call buys over a daemon-side sweep.

func (*Server) SetPairingProvider added in v0.17.0

func (s *Server) SetPairingProvider(provider func(deviceLabel string, allowRemotePermissions bool) (string, error))

SetPairingProvider installs the dependency that services VerbPairingMint. The provider owns every daemon-authored mint input and returns the existing opaque pairing string. Safe to call from any goroutine; canonically called once between NewServer and Serve. Passing nil clears an installed provider. Provider errors are projected to fixed content-free text by the handler.

func (*Server) SetRekeyer added in v0.14.0

func (s *Server) SetRekeyer(r Rekeyer)

SetRekeyer installs the Rekeyer used to service VerbRekey requests. Safe to call from any goroutine; canonically called once between NewServer and Serve as part of daemon startup. Passing nil clears the previously-installed Rekeyer (used by tests; production startup installs once and never clears).

Threading the rekeyer through NewServer would cascade across every NewServer call site (~1 production + 10+ tests) — see #451 split rationale. SetRekeyer keeps the wire contract independent of the constructor.

func (*Server) SetUpdateWhenIdleProvider added in v0.32.0

func (s *Server) SetUpdateWhenIdleProvider(provider func() (UpdateWhenIdleResult, error))

SetUpdateWhenIdleProvider installs the optional release-decision provider. Safe to call from any goroutine; nil clears it. The provider must bound its release check and schedule accepted work independently of the connection, returning before idle waits, downloads, installation or restart.

func (*Server) SocketPath

func (s *Server) SocketPath() string

SocketPath returns the configured socket path.

type Session added in v0.8.0

type Session interface {
	State() sessions.State
	// Activate wakes an evicted session and blocks until the supervisor
	// is running again (or ctx cancels). A no-op on an already-active
	// session.
	Activate(ctx context.Context) error
}

Session is the per-session view the control server depends on. *sessions.Session satisfies it structurally; tests fake it directly. Defining it here (where it is consumed) keeps the sessions package free of control-plane concerns.

type SessionInfo added in v0.8.0

type SessionInfo struct {
	ID         string    `json:"id"`
	Label      string    `json:"label"`
	State      string    `json:"state"`       // "active" | "evicted"
	LastActive time.Time `json:"last_active"` // RFC3339Nano on the wire
	Bootstrap  bool      `json:"bootstrap,omitempty"`
}

SessionInfo is one session's operator-visible metadata as carried on the wire. Mirrors sessions.SessionInfo (#60) field-for-field with wire-appropriate types: ID is encoded as a plain string (not the sessions.SessionID newtype), State as a self-documenting string ("active" / "evicted") matching the on-disk registry encoding, and LastActive as a time.Time (encoding/json marshals to RFC3339Nano).

Bootstrap carries omitempty so the field elides for non-bootstrap entries — the discriminator is only meaningful for the one entry where it's true. ID, Label, State, and LastActive are always present.

Defined here, in protocol.go, rather than reusing sessions.SessionInfo directly so external Go callers / future hand-written clients of the wire don't transitively import internal/sessions for the lifecycleState uint8 enum (kept package-private for the same reason).

LastActive: encoding/json strips the monotonic-clock component on roundtrip. Tests that compare a pre-encode time.Time with the post-decode value must use time.Equal, not == or reflect.DeepEqual (see lessons.md § "JSON roundtrip strips monotonic-clock state").

func SessionsList added in v0.8.0

func SessionsList(ctx context.Context, socketPath string) ([]SessionInfo, error)

SessionsList asks the daemon for a snapshot of every session in the pool and returns the result. In-process Go callers (the future cmd/pyry sessions list) consume this directly. Same one-shot dial → encode → decode → close lifecycle as Status/Logs/Stop/SessionsNew/ SessionsRm/SessionsRename.

Snapshot ordering is whatever the server returned (Pool.List's LastActiveAt desc, SessionID asc tiebreak); callers needing a different order are responsible for re-sorting.

A nil SessionsList payload on a non-error response is treated as a malformed response. An explicit zero-length slice ({"sessionsList":{"sessions":[]}}) decodes to a non-nil payload with len(Sessions) == 0 and is returned as a well-formed empty result.

No typed-sentinel mapping (Pool.List does not return errors). All server errors flow through Response.Error verbatim.

type SessionResolver added in v0.8.0

type SessionResolver interface {
	Lookup(id sessions.SessionID) (Session, error)
	// ResolveID maps a loose-input session selector (full UUID, unique
	// prefix, or empty for bootstrap) to a concrete SessionID. Errors are
	// returned verbatim.
	ResolveID(arg string) (sessions.SessionID, error)
}

SessionResolver maps a SessionID to a Session. An empty id resolves to the default (bootstrap) entry — the seam Phase 1.1 will swap from Lookup("") to Lookup(req.SessionID) without changing handler shape.

type Sessioner added in v0.8.0

type Sessioner interface {
	Create(ctx context.Context, label string) (sessions.SessionID, error)
	Remover
	Renamer
	Lister
}

Sessioner aggregates the lifecycle methods the control server dispatches to. Phase 1.1a-B1 added Create; Phase 1.1d-B1 added Remove via the embedded Remover; Phase 1.1c-B1 added Rename via the embedded Renamer; Phase 1.1b-B1 adds List via the embedded Lister. The pattern is one method (or named sub-interface) per verb, embedded onto Sessioner so NewServer's signature stays stable across the namespace's growth.

*sessions.Pool satisfies Sessioner structurally — Pool.Create, Pool.Remove, Pool.Rename and Pool.List match the embedded interfaces' signatures exactly, so no covariant-return adapter is needed (contrast with poolResolver's Lookup). Defined here, where it is consumed; tests fake it directly.

Create mints a new supervised session with the given (possibly empty) label and returns the new SessionID. Errors are surfaced to the client verbatim through Response.Error.

type SessionsHasIDResult added in v0.9.0

type SessionsHasIDResult struct {
	Has bool `json:"has"`
}

SessionsHasIDResult carries the boolean answer to a sessions.has-id query. Has is emitted unconditionally (no omitempty) so the wire distinguishes "id absent" ({"has":false}) from a malformed empty response ({}). Defined here, in protocol.go, so external Go callers don't transitively import internal/sessions.

type SessionsListPayload added in v0.8.0

type SessionsListPayload struct {
	Sessions []SessionInfo `json:"sessions"`
}

SessionsListPayload carries the result of a successful sessions.list request: a snapshot of every session in the pool, in the order returned by Pool.List (LastActiveAt descending, SessionID ascending tiebreak). Final user-facing ordering is the responsibility of the CLI renderer (61-B); this layer does not re-sort.

type SessionsNewResult added in v0.8.0

type SessionsNewResult struct {
	SessionID string `json:"sessionID"`
}

SessionsNewResult carries the result of a successful sessions.new request. SessionID is the minted UUID as a string (not the sessions.SessionID newtype) so external clients need not import the sessions package.

type SessionsPayload added in v0.8.0

type SessionsPayload struct {
	Label       string      `json:"label,omitempty"`       // sessions.new
	ID          string      `json:"id,omitempty"`          // sessions.rm, sessions.rename
	JSONLPolicy JSONLPolicy `json:"jsonlPolicy,omitempty"` // sessions.rm
	NewLabel    string      `json:"newLabel,omitempty"`    // sessions.rename
}

SessionsPayload carries arguments shared across the sessions.* verb family. Today Label is used by sessions.new; ID and JSONLPolicy are used by sessions.rm; ID and NewLabel are used by sessions.rename.

Label is the human-friendly name supplied by the client. Empty maps to a no-label session — Pool.Create accepts it verbatim and the registry stores ""; not an error.

ID is populated for VerbSessionsRm and VerbSessionsRename.

JSONLPolicy is populated for VerbSessionsRm. Empty JSONLPolicy is treated by the server as JSONLPolicyLeave.

NewLabel is populated for VerbSessionsRename. An empty NewLabel on the wire (omitted via omitempty) is forwarded to Pool.Rename as the empty string and clears the on-disk label per #62's contract.

type StatusPayload

type StatusPayload struct {
	Phase        string `json:"phase"`                  // starting | running | backoff | stopped
	ChildPID     int    `json:"child_pid,omitempty"`    // 0 when no child is running
	StartedAt    string `json:"started_at"`             // RFC3339
	Uptime       string `json:"uptime"`                 // since StartedAt
	RestartCount int    `json:"restart_count"`          // number of times the child has exited
	LastUptime   string `json:"last_uptime,omitempty"`  // duration of the most recent child
	NextBackoff  string `json:"next_backoff,omitempty"` // delay scheduled before the next spawn
}

StatusPayload describes the supervisor's runtime state. All durations are formatted as Go duration strings (e.g. "310ms", "1.5s") so they survive a JSON round-trip without losing precision the way nanosecond integers do when piped through tools like jq.

func Status

func Status(ctx context.Context, socketPath string) (*StatusPayload, error)

Status connects to the control socket, requests a status snapshot, and returns the payload. The context's deadline is honored if set; otherwise DialTimeout applies.

type UpdateDecision added in v0.32.0

type UpdateDecision string

UpdateDecision identifies the provider's release/scheduling decision.

const (
	UpdateUpToDate    UpdateDecision = "up-to-date"
	UpdateNotEligible UpdateDecision = "not-eligible"
	UpdateWillInstall UpdateDecision = "will-install"
)

type UpdateWhenIdleResult added in v0.32.0

type UpdateWhenIdleResult struct {
	Decision   UpdateDecision `json:"decision"`
	Reason     string         `json:"reason,omitempty"`
	ReleaseTag string         `json:"releaseTag,omitempty"`
}

UpdateWhenIdleResult describes a scheduling decision, not a completed update. Not-eligible requires Reason; will-install requires the selected or already pending ReleaseTag. Release selection and eligibility belong to the provider.

func UpdateWhenIdle added in v0.32.0

func UpdateWhenIdle(ctx context.Context, socketPath string) (*UpdateWhenIdleResult, error)

UpdateWhenIdle requests a release/scheduling decision, without waiting for idle or installation. Dial, write and read share a 70-second ceiling, shortened by an earlier caller deadline. Cancellation wakes parked I/O but does not retract work accepted by the provider. Every failure returns a nil result.

type Verb

type Verb string

Verb identifies a control request.

const (
	// VerbStatus asks for a snapshot of supervisor state.
	VerbStatus Verb = "status"

	// VerbStop asks the daemon to shut down. The server acknowledges with
	// Response.OK before initiating shutdown so the client gets confirmation
	// even though the socket disappears moments later.
	VerbStop Verb = "stop"

	// VerbLogs returns the most recent supervisor log lines from an
	// in-memory ring buffer.
	VerbLogs Verb = "logs"

	// VerbSessionsNew creates a new session. Request.Sessions carries an
	// optional human-friendly label; Response.SessionsNew carries the
	// minted session UUID. First member of the Phase 1.1 sessions.* verb
	// family — the dot in the verb string is a documentation convention,
	// not a parser rule.
	VerbSessionsNew Verb = "sessions.new"

	// VerbSessionsRm removes an existing session. Request.Sessions carries
	// the session ID and JSONL disposition policy; Response.OK acknowledges
	// success. Typed errors from the pool (ErrSessionNotFound,
	// ErrCannotRemoveBootstrap) propagate through Response.ErrorCode so the
	// CLI can match them with errors.Is.
	VerbSessionsRm Verb = "sessions.rm"

	// VerbSessionsRename updates an existing session's human-friendly
	// label. Request.Sessions carries the session ID and the new label
	// (empty newLabel clears the on-disk label, per Pool.Rename's
	// contract); Response.OK acknowledges success. The typed
	// ErrSessionNotFound from the pool propagates through
	// Response.ErrorCode == ErrCodeSessionNotFound so the CLI can match
	// it with errors.Is. No new ErrorCode constants are introduced —
	// ErrCodeSessionNotFound (1.1d-B1) is reused.
	VerbSessionsRename Verb = "sessions.rename"

	// VerbSessionsList returns a snapshot of every session in the pool.
	// Request carries no payload. Response.SessionsList carries the
	// snapshot. First read-side member of the sessions.<verb> namespace;
	// Pool.List is the only data source the server-side handler calls
	// (see #60 for the underlying primitive's bootstrap-label
	// substitution and sort-order guarantees).
	VerbSessionsList Verb = "sessions.list"

	// VerbSessionsHasID asks whether a session is currently registered
	// with the given UUID. Request.Sessions.ID carries the UUID;
	// Response.SessionsHasID carries the boolean answer. Pure registry
	// read — no claude spawn, no state transition. The 1.3c-2
	// foreground auto-attach path consumes this as a cheap alternative
	// to sessions.list. Empty / malformed input returns Response.Error;
	// a well-formed but absent UUID returns {Has: false}.
	VerbSessionsHasID Verb = "sessions.has-id"

	// VerbRekey asks the daemon to trigger an immediate Noise re-key on
	// the named v2 conn. Request.Rekey carries the conn id;
	// Response.OK acknowledges that the trigger has been accepted by
	// the v2 session manager (the underlying handshake runs
	// asynchronously on the conn's own state machine — this verb does
	// not wait for it).
	//
	// Slice A (#459) lays this wire and the dispatcher. The operator
	// subcommand (`pyry rekey <conn_id>`) and the V2SessionManager
	// implementation that satisfies Rekeyer are slice B (#460); until
	// then every production-path VerbRekey request returns
	// "rekey: no rekeyer configured".
	VerbRekey Verb = "rekey"

	// VerbMCPApprove forwards a claude tool-approval request to the
	// daemon, which registers it with internal/permbridge, blocks for the
	// allow/deny verdict, and returns it. Request.Approve carries the
	// forwarded request; Response.Approve carries the verdict. The daemon
	// makes the human-facing decision (where modal surfacing lives, #1080)
	// rather than the ephemeral `pyry mcp-approve` MCP child that dials
	// this verb.
	//
	// Fail-closed: a socket disconnect, daemon shutdown, or approval
	// timeout mid-wait yields a deny verdict; a nil registry (v1 /
	// foreground, and production until #1080 wires a resolver) returns
	// Response.Error "no approval registry configured". The dotted
	// namespace matches sessions.* — the dot is a documentation
	// convention, not a parser rule.
	VerbMCPApprove Verb = "mcp.approve"

	// VerbAttachFile files a host file claude named — by a filesystem path
	// the model chose — under the conversation bound to the CALLING
	// session, and answers with the daemon-minted id of the stored
	// attachment. Request.AttachFile carries the session id and the path;
	// Response.AttachFile carries the id.
	//
	// The conversation is derived from the named session through the
	// daemon's own conversation registry, never from the request and never
	// from the follow-active cursor (which is stamped at enqueue by the
	// session router, so a file produced by a background conversation's
	// claude would otherwise be filed under whichever chat the operator
	// last messaged). #2143 established the same rule for uploads: the
	// destination travels per transfer, not through the cursor.
	//
	// Fail-closed: every error path answers. The path is confined to the
	// conversation's recorded workspace before it is read, and a nil file
	// attacher (never calling SetFileAttacher, or v1/foreground) returns
	// Response.Error "attachment.file: no file attacher configured" — the
	// same nil-dependency-degrades-cleanly shape as VerbRekey and
	// VerbMCPApprove. The dotted namespace matches sessions.* and
	// mcp.approve; the dot is a documentation convention, not a parser
	// rule.
	VerbAttachFile Verb = "attachment.file"

	// VerbChannelNew creates a promoted conversation — a channel, the
	// registry's own word for IsPromoted=true — rooted at a directory on the
	// host. Request.Channel carries that directory and an optional name;
	// Response.ChannelNew carries the minted conversation id.
	//
	// It is the first CONVERSATION verb on the local control plane, which
	// until now spoke only about sessions, logs and the daemon itself. It
	// exists because a conversation's workspace was reachable only from a
	// paired client, whose picker offers folders that have already hosted a
	// conversation — so a folder that merely exists on the host could not be
	// chosen at all. The operator's shell is already standing in the right
	// directory, which makes a local verb the cheapest picker there is.
	//
	// The Cwd is CALLER-AUTHORED and is the security surface of this verb: it
	// becomes the directory the conversation's claude is trust-marked in and
	// later spawns in. This package does NO path handling — it forwards the
	// string verbatim to the creator installed by SetChannelCreator, which
	// confines it to $HOME, resolves its symlinks and trust-marks the realpath,
	// in that order, through the same validator the wire create_conversation
	// uses. The socket is local and 0600, so the peer is the operator; the
	// confinement still applies, because any process running as the operator
	// can dial it.
	//
	// Fail-closed: every path answers exactly one Response, and a daemon with
	// no creator installed (v1/foreground, or a composition that never wired
	// it) returns "channel.new: no channel creator configured" rather than
	// panicking — the same nil-dependency-degrades-cleanly shape as VerbRekey,
	// VerbMCPApprove and VerbAttachFile. No refusal echoes the requested or the
	// resolved path. The dotted namespace matches sessions.* ; the dot is a
	// documentation convention, not a parser rule.
	VerbChannelNew Verb = "channel.new"

	// VerbConversationNew requests a chat or channel with optional settings.
	// The independent creator seam is unwired until daemon composition installs it.
	VerbConversationNew Verb = "conversation.new"

	// VerbConversationPost submits a user message to an existing conversation id.
	// Success is queue acceptance, not completed model output.
	VerbConversationPost Verb = "conversation.post"

	// VerbChannelPost records one message in a channel conversation named by
	// its display label. Request.ChannelPost carries the label and the
	// content; success answers Response.OK with no result body, because the
	// caller prints nothing and needs nothing back.
	//
	// It exists so a host-local script — a cron on the operator's box — can
	// reach the operator through the clients they already have open, now that
	// the chat-plugin channels are gone. The label resolves against
	// non-archived promoted conversations by exact name: one match is posted
	// into, no match creates the channel under the DAEMON's default workspace
	// and posts into that, and two or more refuse rather than pick, since the
	// conversation registry enforces no uniqueness rule on names.
	//
	// It is LOCAL-ONLY BY CONSTRUCTION, not by a check: internal/relay builds
	// no control.Request anywhere — it touches this package for ErrConnNotFound
	// and one interface assertion — and this verb mints no protocol type, so a
	// relay client has no frame with which to send it. Live delivery to an
	// already-connected client is #2498's problem; what this verb guarantees is
	// the durable record, which a client reads on its next history request.
	//
	// No path crosses this wire, which is the security difference from
	// VerbChannelNew: the create-on-miss workspace is the daemon's own resolved
	// default, so this verb has none of channel.new's confinement surface. The
	// caller-authored values are the label and the content, and neither reaches
	// a filesystem path — the conversation id the durable log keys on is minted
	// daemon-side.
	//
	// Fail-closed: every path answers exactly one Response, and a daemon with
	// no poster installed (v1/foreground, or a composition that never wired it)
	// returns "channel.post: no channel poster configured" rather than
	// panicking — VerbChannelNew's shape. No refusal echoes the label or the
	// content back.
	VerbChannelPost Verb = "channel.post"

	// VerbPairingMint asks the selected daemon to mint a pairing through its
	// installed provider. Request.Pairing carries only the new device's label
	// and explicit remote-permission choice; Response.Pairing carries the
	// provider's opaque pairing string.
	VerbPairingMint Verb = "pairing.mint"

	// VerbUpdateWhenIdle asks the provider to select and schedule the latest
	// release. It carries no payload; Response.UpdateWhenIdle is a decision,
	// returned before waiting for idle, downloading, installing or restarting.
	VerbUpdateWhenIdle Verb = "update.when-idle"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL