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
- Variables
- func ChannelNew(ctx context.Context, socketPath, cwd, name string) (string, error)
- func Rekey(ctx context.Context, socketPath, connID string) error
- func SessionsHasID(ctx context.Context, socketPath, id string) (bool, error)
- func SessionsNew(ctx context.Context, socketPath, label string) (string, error)
- func SessionsRename(ctx context.Context, socketPath, id, newLabel string) error
- func SessionsRm(ctx context.Context, socketPath, id string, policy JSONLPolicy) error
- func SlogTee(next slog.Handler, ring *RingBuffer) slog.Handler
- func Stop(ctx context.Context, socketPath string) error
- type ApprovePayload
- type ApproveResult
- type AttachFilePayload
- type AttachFileResult
- type ChannelNewResult
- type ChannelPayload
- type ErrorCode
- type GetOrCreator
- type JSONLPolicy
- type Lister
- type LogProvider
- type LogsPayload
- type RekeyPayload
- type Rekeyer
- type Remover
- type Renamer
- type Request
- type Response
- type RingBuffer
- type Server
- func (s *Server) Close() error
- func (s *Server) Listen() error
- func (s *Server) Serve(ctx context.Context) error
- func (s *Server) SetApprovalRegistry(reg *permbridge.Registry, timeout time.Duration)
- func (s *Server) SetApprovalSurfacer(surface func(permbridge.Request) func())
- func (s *Server) SetChannelCreator(create func(cwd, name string) (string, error))
- func (s *Server) SetFileAttacher(attach func(sessionID, path string) (string, error))
- func (s *Server) SetRekeyer(r Rekeyer)
- func (s *Server) SocketPath() string
- type Session
- type SessionInfo
- type SessionResolver
- type Sessioner
- type SessionsHasIDResult
- type SessionsListPayload
- type SessionsNewResult
- type SessionsPayload
- type StatusPayload
- type Verb
Constants ¶
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.
Variables ¶
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.
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
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 Rekey ¶ added in v0.14.0
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
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
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
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`.
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
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
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 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 GetOrCreator ¶ added in v0.9.0
type GetOrCreator interface {
GetOrCreate(ctx context.Context, id sessions.SessionID, label string) (sessions.SessionID, error)
}
GetOrCreator is the per-pool view the control server depends on for take-or-create attaches (Phase 1.3b). *sessions.Pool satisfies it structurally via Pool.GetOrCreate. Defined here, where it is consumed; tests fake it directly.
GetOrCreate returns the canonical SessionID for id, creating a new session under that exact UUID if one is not already registered. Errors: sessions.ErrInvalidSessionID for empty / non-UUIDv4 ids; sessions.ErrPoolNotRunning when Pool.Run is not active. See Pool.GetOrCreate for the full contract, including the atomic register+persist+supervise critical section.
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 ¶
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.
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
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
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
}
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
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
- 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) 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.
Foreground vs service mode is no longer surfaced as a distinct constructor parameter; it is a property of the resolved session's bridge. A foreground-mode session's Attach returns sessions.ErrAttachUnavailable, which the attach handler maps back to the existing "no attach provider configured (daemon may be in foreground mode)" wire string for byte-identical client output.
func (*Server) Close ¶
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 ¶
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) Serve ¶
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
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) SetFileAttacher ¶ added in v0.16.0
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) SetRekeyer ¶ added in v0.14.0
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) SocketPath ¶
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. handleAttach calls this before Attach so the bridge has a
// live claude on the other side.
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 — handleAttach wraps them as "attach: <err>".
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)
GetOrCreator
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. Phase 1.1e (attach orchestration) will continue this pattern — 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. Phase 1.1e (attach) will add further omitempty fields to the same struct.
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.
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" )