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
- func Attach(ctx context.Context, socketPath string, cols, rows int) error
- func SlogTee(next slog.Handler, ring *RingBuffer) slog.Handler
- func Stop(ctx context.Context, socketPath string) error
- type AttachPayload
- type AttachProvider
- type LogProvider
- type LogsPayload
- type Request
- type Response
- type RingBuffer
- type Server
- type StateProvider
- type StatusPayload
- type Verb
Constants ¶
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.
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 ¶
This section is empty.
Functions ¶
func Attach ¶
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 not propagated in Phase 0 — detach and reattach to update.
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 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 AttachPayload ¶
AttachPayload carries the client's terminal geometry at attach time.
Phase 0 caveat: the server currently ACCEPTS this payload but does NOT propagate Cols/Rows to the PTY — the bridge has no API for setting window size yet. Clients send the values for forward compatibility (so no protocol change is needed when the server starts honoring them). Until the supervised child is taught to react to handshake-time geometry, all claude sessions render at whatever size the server's PTY was allocated with (typically 80×24 from creack/pty defaults).
Live SIGWINCH propagation while attached is also out of scope for Phase 0; it would need a small framing change to multiplex resize events into the raw byte stream, or a side-channel control verb.
type AttachProvider ¶
type AttachProvider interface {
Attach(in io.Reader, out io.Writer) (done <-chan struct{}, err error)
}
AttachProvider is the supervisor view the control server depends on for VerbAttach. Implementations bind a client's input/output streams to the supervised PTY for the lifetime of the attachment. Returns the done channel that fires when the input source ends (client disconnected), or an error if the attach can't proceed (e.g. another client already attached).
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 Request ¶
type Request struct {
Verb Verb `json:"verb"`
Attach *AttachPayload `json:"attach,omitempty"` // populated for VerbAttach
}
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"`
OK bool `json:"ok,omitempty"`
Error string `json:"error,omitempty"`
}
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
- 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, state StateProvider, logs LogProvider, attach AttachProvider, shutdown func(), log *slog.Logger) *Server
NewServer constructs a Server. The socket is not opened until Listen.
state must be non-nil — the supervisor is the canonical source of state, and VerbStatus would otherwise nil-pointer-panic on the first request. Passing a nil state 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.
attach is optional. When nil, VerbAttach returns an error response — the daemon is in foreground mode and the supervised child is already bound to a local terminal.
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.
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 "socket already in use" or "permission denied" errors before starting the supervisor proper.
Stale sockets from a prior crash are removed transparently — net.Listen would otherwise fail with "address already in use" since unix sockets don't auto-clean.
func (*Server) Serve ¶
Serve accepts connections and dispatches requests until ctx is cancelled. Listen must be called first.
func (*Server) SocketPath ¶
SocketPath returns the configured socket path.
type StateProvider ¶
type StateProvider interface {
State() supervisor.State
}
StateProvider is the supervisor view the control server depends on. Defining it here (where it is consumed) keeps the supervisor package free of control-plane concerns and makes the server trivial to test with a fake.
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" // 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" )