control

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: MIT Imports: 20 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 (
	EscapeKey byte = 0x02 // Ctrl-B
	DetachKey byte = 'd'
)

DetachKey is the byte that, when typed after EscapeKey, ends an attachment. Pattern: Ctrl-B (0x02) followed by 'd' — same convention as tmux.

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.

Variables

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 Attach

func Attach(ctx context.Context, socketPath string, cols, rows int, sessionID string, createIfMissing bool) error

Attach connects to a running pyry daemon's control socket, performs the JSON handshake, and bridges the local terminal to the PTY.

Cols/rows are sent in the handshake so the supervised child knows the initial window size. Subsequent live resize events are forwarded as VerbResize requests on fresh control connections (see SendResize) by an internal SIGWINCH watcher; the supervised child receives the new dimensions via the daemon's Bridge.Resize seam.

sessionID selects which session the server should attach to: a full UUID, a unique prefix, or empty to mean "the bootstrap session". The string is passed through verbatim; resolution rules live in the server's Pool.ResolveID.

createIfMissing opts in to take-or-create attach (Phase 1.3b): if sessionID is not registered, the daemon mints a session under that exact UUID before binding. With createIfMissing set, sessionID MUST be a full canonical UUIDv4 — prefix resolution does not apply.

Local stdin is put into raw mode for the duration of the attach so keystrokes pass through unmodified to the child. The terminal is restored when Attach returns.

The attach ends when:

  • The user types EscapeKey + DetachKey (Ctrl-B d): clean detach.
  • The server closes the connection: returns nil.
  • The local stdin or socket errors: returns the error.

func AttachStdio added in v0.9.0

func AttachStdio(ctx context.Context, socketPath, sessionID string, in io.Reader, out io.Writer, createIfMissing bool) error

AttachStdio is the no-PTY counterpart to Attach. It performs the same VerbAttach handshake, then bridges in→conn and conn→out as raw bytes — no raw mode, no SIGWINCH watcher, no escape-key detection. Intended for SDK consumers (stream-json, tooling) that exchange line-delimited payloads over their own stdin/stdout pipes and need pyry to be a transparent byte conduit.

sessionID resolution rules match Attach (full UUID, unique prefix, or "" → bootstrap; resolved server-side via Pool.ResolveID). With createIfMissing set (Phase 1.3b), sessionID must be a full canonical UUIDv4 — prefix resolution does not apply.

EOF on `in` ends the attach cleanly; the session itself stays alive (lazy-eviction semantics — detach ≠ destroy). Server-initiated close (daemon stop, session evicted from under us) returns nil. Any other I/O error propagates.

AttachStdio does not touch any tty. It is safe to call when stdin is a pipe, a file, /dev/null, or absent — there is no IsTerminal branch.

ctx scopes the dial only; once the conn is established the attach is driven by I/O on `in`/`out` and `conn`. Cancel by closing `in`.

func SendResize added in v0.8.0

func SendResize(ctx context.Context, socketPath, sessionID string, cols, rows int) error

SendResize asks the daemon to apply a window-size update to the named session. Empty sessionID selects the bootstrap session. cols/rows are the client's local terminal dimensions; either being zero is treated by the server as "no change". A successful return means the server received and dispatched the request — the seam's own success is best-effort and not visible to the client.

Callers (e.g. a SIGWINCH handler) should not retry on transient failure; the next SIGWINCH will re-emit a fresh resize.

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/SendResize/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/ SendResize.

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`.

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 AttachPayload

type AttachPayload struct {
	Cols      int    `json:"cols,omitempty"`
	Rows      int    `json:"rows,omitempty"`
	SessionID string `json:"sessionID,omitempty"`
	// CreateIfMissing opts in to take-or-create attach: if SessionID is
	// not registered, the daemon mints a session under that exact UUID
	// before binding. Off by default — pre-existing callers fail with
	// "no such session" against an unknown id, byte-for-byte unchanged.
	// Omitempty is load-bearing for the same v0.5.x rollover guarantee
	// that pins SessionID's tag.
	CreateIfMissing bool `json:"createIfMissing,omitempty"`
}

AttachPayload carries the client's terminal geometry at attach time and (Phase 1.1+) selects which session to attach to.

SessionID is a loose-input selector: a full UUID, a unique prefix, or empty to mean "the bootstrap session". The server resolves it through Pool.ResolveID; see that method for resolution rules. The omitempty tag is load-bearing — an empty SessionID must marshal to no field on the wire so v0.5.x clients (which don't know the field) keep round-tripping byte-identically against a v0.7.x server during the rollover window.

Handshake Cols/Rows are applied to the supervised PTY at attach time via Bridge.Resize (see #136). Either dimension being zero is the "unknown / don't touch" sentinel — no resize is issued.

Live resize updates while attached are carried by VerbResize on a separate control connection (see ResizePayload), emitted from the client by the SIGWINCH handler in pyry attach (startWinsizeWatcher).

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"
)

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

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 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"`
	Attach   *AttachPayload   `json:"attach,omitempty"`   // populated for VerbAttach
	Resize   *ResizePayload   `json:"resize,omitempty"`   // populated for VerbResize
	Sessions *SessionsPayload `json:"sessions,omitempty"` // populated for VerbSessionsNew (Phase 1.1+)
}

Request is the wire format for a single client request.

type ResizePayload added in v0.8.0

type ResizePayload struct {
	SessionID string `json:"sessionID,omitempty"`
	Cols      int    `json:"cols,omitempty"`
	Rows      int    `json:"rows,omitempty"`
}

ResizePayload carries a live window-size update for an attached session. SessionID resolution mirrors AttachPayload — empty selects bootstrap, full UUID or unique prefix selects a specific session. Cols/Rows are wire ints for symmetry with AttachPayload; the server narrows + swaps at the seam boundary. Either dimension being zero is the "unknown / don't touch" sentinel — no resize is issued (same rule as the handshake path).

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)
	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
  • 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.

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

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) 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) SocketPath

func (s *Server) SocketPath() string

SocketPath returns the configured socket path.

type Session added in v0.8.0

type Session interface {
	State() supervisor.State
	Attach(in io.Reader, out io.Writer) (done <-chan struct{}, err error)
	// 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
	// Resize applies the given window size (rows-then-cols) to the
	// session's PTY. Returns sessions.ErrAttachUnavailable for sessions
	// with no bridge (foreground mode); handleAttach swallows that case.
	Resize(rows, cols uint16) 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/SendResize/ 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.

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 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"

	// VerbAttach upgrades the connection: after a JSON ack from the server,
	// the rest of the connection is raw bytes bridged to the supervised
	// claude process's PTY. Standard "protocol upgrade" pattern.
	VerbAttach Verb = "attach"

	// VerbResize carries a live window-size update for an attached session.
	// One-shot request/response on a fresh control connection — independent
	// of the (long-lived) attach connection so a malformed resize never
	// disturbs the byte stream.
	VerbResize Verb = "resize"

	// 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"
)

Jump to

Keyboard shortcuts

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