Documentation
¶
Overview ¶
Package supervisor runs Claude Code under process supervision: spawn in a PTY, stream I/O transparently to the controlling terminal, and restart the child with exponential backoff when it exits.
Phase 0 is deliberately narrow — it replaces the current tmux + bash restart loop. Future phases will add a control socket, multi-session routing, and in-process integrations for Channels, knowledge capture, memsearch, and crons.
Index ¶
- Variables
- func SpawnPTY(ctx context.Context, cfg SpawnConfig) (*exec.Cmd, *os.File, error)
- type Bridge
- func (b *Bridge) Attach(in io.Reader, out io.Writer) (done <-chan struct{}, err error)
- func (b *Bridge) Attached() bool
- func (b *Bridge) BeginIteration()
- func (b *Bridge) EndIteration()
- func (b *Bridge) Read(p []byte) (int, error)
- func (b *Bridge) Resize(rows, cols uint16) error
- func (b *Bridge) SetOutputObserver(fn func([]byte))
- func (b *Bridge) SetPTY(f *os.File)
- func (b *Bridge) Write(p []byte) (int, error)
- type Config
- type Phase
- type SpawnConfig
- type State
- type Supervisor
Constants ¶
This section is empty.
Variables ¶
var ErrBridgeBusy = errors.New("supervisor: bridge already has an attached client")
ErrBridgeBusy is returned by Bridge.Attach when another client is already attached.
Functions ¶
func SpawnPTY ¶ added in v0.12.0
SpawnPTY launches Bin in a PTY using exec.CommandContext + pty.Start. On ctx cancel, SIGTERM is forwarded via cmd.Cancel; cmd.WaitDelay enforces a SIGKILL grace. Caller owns lifecycle — must Wait the *exec.Cmd and Close the returned *os.File.
Callers that need different cancel/grace timings overwrite cmd.Cancel / cmd.WaitDelay on the returned *exec.Cmd before calling Wait.
Types ¶
type Bridge ¶
type Bridge struct {
// contains filtered or unexported fields
}
Bridge mediates I/O between the PTY and a (possibly absent) external endpoint. It is the seam that lets the supervisor run in service mode — the PTY master lives in the supervisor, and an attaching client (e.g. `pyry attach`) can take over input/output on demand.
Lifetime: a single Bridge persists across child restarts. It implements io.ReadWriter so the supervisor can use it as a transparent stand-in for stdin/stdout. Writes (PTY → bridge) forward to the attached output writer or get discarded when no client is attached. Reads (bridge → PTY) block until a client attaches and starts feeding bytes through.
Iteration boundaries: each runOnce iteration calls BeginIteration before launching the input pump and EndIteration after the child exits. Read returns io.EOF when the iteration ends, allowing the input pump to exit cleanly without consuming buffered bytes intended for the next iteration. Bytes already in flight on Read are preserved by Go's select semantics — an unselected channel receive does not remove the value from the channel.
At most one attacher at a time. A second Attach call while another client is already attached returns ErrBridgeBusy.
func NewBridge ¶
NewBridge constructs an empty bridge. No output is attached yet; PTY writes are discarded until the first Attach. log, if nil, falls back to slog.Default — used to surface non-EOF input-pump errors so an abnormally-closed client doesn't disappear silently.
func (*Bridge) Attach ¶
Attach binds a client to the bridge: bytes from `in` flow toward the PTY, PTY output flows toward `out`. Returns a `done` channel that closes when `in` returns EOF or an error (typically: client disconnected). Returns ErrBridgeBusy if another client is currently attached.
Exactly one of (returns done, returns err) is non-nil.
The bridge does NOT close the in/out streams — the caller owns their lifecycle and is responsible for closing them after `done` fires.
func (*Bridge) BeginIteration ¶ added in v0.8.0
func (b *Bridge) BeginIteration()
BeginIteration prepares the bridge for a new ptmx iteration. Resets the per-iteration cancel signal so subsequent Reads block on input again. Idempotent if called repeatedly without EndIteration in between, but runOnce pairs them.
func (*Bridge) EndIteration ¶ added in v0.8.0
func (b *Bridge) EndIteration()
EndIteration signals the current Read to return io.EOF. Buffered chunks in the input channel are preserved for the next iteration.
func (*Bridge) Read ¶
Read implements io.Reader. The supervisor copies from this into the PTY master. Blocks until a buffered chunk is available or EndIteration fires.
Returns io.EOF when the current iteration's cancel signal is closed AND no buffered bytes remain. Critically, when cancel fires concurrently with a chunk arriving, Go's select non-determinism means we may return either the chunk (good) or EOF (also good — the chunk stays in the channel for the next iteration's Read to consume). Either way, no bytes are lost.
func (*Bridge) Resize ¶ added in v0.8.0
Resize applies the given window size to the registered PTY master via pty.Setsize. Returns nil silently when no PTY is registered (between iterations, or in foreground mode where no Bridge exists at all). Errors from pty.Setsize are wrapped and returned for the caller to log; the control plane does not fail the attach on resize errors.
rows-then-cols matches pty.Winsize field order. The wire protocol uses cols-then-rows in AttachPayload; the boundary swap happens at the handleAttach call site.
func (*Bridge) SetOutputObserver ¶ added in v0.11.0
SetOutputObserver registers (or clears, when fn is nil) a callback invoked from Write with each PTY-output chunk before the chunk is forwarded to the attached writer.
The observer runs on the supervisor's PTY-drain goroutine. It MUST NOT block, MUST NOT panic, and MUST NOT retain p past return — the supervisor's io.Copy reuses the buffer for the next read. Production observers must enqueue to a buffered channel and drop on overflow.
func (*Bridge) SetPTY ¶ added in v0.8.0
SetPTY registers (or clears, when f is nil) the PTY master for the current runOnce iteration. Subsequent Resize calls target this fd. runOnce calls SetPTY(ptmx) after pty.Start succeeds and SetPTY(nil) before EndIteration so a Resize racing with iteration teardown sees nil rather than a closed fd.
func (*Bridge) Write ¶
Write implements io.Writer. The supervisor copies from the PTY master into this. Bytes are forwarded to the attached output writer, or discarded if none is attached.
Write NEVER returns an error. This is load-bearing: the supervisor's io.Copy(bridge, ptmx) goroutine must keep draining the PTY for the entire child lifetime — if it returns, the PTY's master read buffer fills, the slave's writes block, and the child wedges. So even when the attached client's conn is mid-disconnect (closed faster than the bridge's input pump cleared b.output to nil), we silently drop the bytes and report success rather than letting the conn error escape to the supervisor.
The discard-on-detach is a minor visible cost — a few bytes of claude output that would have shown on the now-departed client get lost. The alternative (a wedged daemon that needs SIGKILL to recover) is much worse.
type Config ¶
type Config struct {
// ClaudeBin is the path to the claude binary. Defaults to "claude" (found on PATH).
ClaudeBin string
// WorkDir is the working directory for the claude child process.
// Empty means the supervisor's current directory.
WorkDir string
// ResumeLast causes restarts after the first run to pass --continue to
// claude. Claude resumes the most recent session for the working directory,
// so conversation history survives supervisor restarts and crashes.
//
// We use --continue rather than --resume <id> so that if the user runs
// /clear inside claude (which rotates the session ID on disk), the next
// restart picks up the post-clear session rather than reattaching to the
// orphaned pre-clear one. Bare --resume would open claude's interactive
// session picker — usable interactively but wrong for an unattended
// supervisor restart.
ResumeLast bool
// ClaudeArgs are forwarded to the claude binary as positional arguments.
ClaudeArgs []string
// Bridge, if non-nil, mediates PTY I/O instead of bridging to the
// supervisor's own stdin/stdout. Used in service mode (no controlling
// terminal): an attaching client (e.g. `pyry attach`) can take over
// the bridge to interact with the child. When nil, the supervisor
// runs in foreground mode and bridges PTY I/O directly to its own
// stdin/stdout — current behavior.
Bridge *Bridge
// Logger is used for structured logging.
Logger *slog.Logger
// Backoff parameters. Zero values use sensible defaults.
BackoffInitial time.Duration
BackoffMax time.Duration
BackoffReset time.Duration
// ValidateConversation, if non-nil, is invoked by WriteUserTurn before
// any state mutation or PTY write. A non-nil return is propagated
// verbatim — production wiring returns conversations.ErrConversationNotFound
// for unknown ids; the supervisor stays decoupled from that package by
// receiving the sentinel through the closure. When nil, WriteUserTurn
// skips validation (test ergonomics).
ValidateConversation func(id string) error
// contains filtered or unexported fields
}
Config controls a Supervisor instance.
type SpawnConfig ¶ added in v0.12.0
type SpawnConfig struct {
Bin string // executable path; required
Args []string // argv (without argv[0])
WorkDir string // optional; empty means inherit
Env []string // appended to os.Environ()
Logger *slog.Logger // optional; defaults to slog.Default()
}
SpawnConfig is the minimum surface SpawnPTY needs. Mirrors the relevant subset of Config; intentionally separate so callers that do not want a full Supervisor (one-shot agent-run) do not pull in backoff/bridge/state fields.
type State ¶
type State struct {
Phase Phase // current lifecycle phase
ChildPID int // PID of the running child, or 0 when none
StartedAt time.Time // when the supervisor entered Run
RestartCount int // number of times the child has exited
LastUptime time.Duration // uptime of the most recent child, zero if first run
NextBackoff time.Duration // delay scheduled before the next spawn, zero when running
}
State is a snapshot of the supervisor's runtime state. Returned by (*Supervisor).State for the control plane.
type Supervisor ¶
type Supervisor struct {
// contains filtered or unexported fields
}
Supervisor owns a single Claude Code child process and restarts it on exit.
func New ¶
func New(cfg Config) (*Supervisor, error)
New constructs a Supervisor from a Config, applying defaults.
func (*Supervisor) CurrentConversation ¶ added in v0.11.0
func (s *Supervisor) CurrentConversation() string
CurrentConversation returns the most recently written conversation_id, or "" when no WriteUserTurn has been accepted yet. Safe for concurrent use. Survives child restarts; the cursor is in-memory state on the supervisor, not tied to a particular runOnce iteration.
func (*Supervisor) Run ¶
func (s *Supervisor) Run(ctx context.Context) error
Run supervises the claude child until ctx is cancelled. Each iteration spawns claude in a PTY, streams I/O, and waits for exit. On exit it applies exponential backoff before respawning. The backoff counter resets if a child stayed up longer than Config.BackoffReset.
func (*Supervisor) State ¶
func (s *Supervisor) State() State
State returns a snapshot of the current supervisor state. Safe to call from any goroutine.
func (*Supervisor) WaitForPTY ¶ added in v0.13.0
func (s *Supervisor) WaitForPTY(ctx context.Context) error
WaitForPTY blocks until the supervisor has a bound PTY (closed by setPTY on the next runOnce iteration), or ctx is cancelled. Returns nil on readiness, ctx.Err() on cancel. Safe from any goroutine; idempotent on an already-bound PTY (returns immediately).
Session.Activate calls this at the tail of its waiting phase so callers that follow Activate with WriteUserTurn observe a live PTY rather than the ~hundreds-of-ms gap between transitionTo closing activeCh and runOnce binding the new master.
func (*Supervisor) WriteUserTurn ¶ added in v0.11.0
func (s *Supervisor) WriteUserTurn(id string, payload []byte) error
WriteUserTurn delivers a user-turn payload to the supervised claude child, tagged with the caller's conversation_id. The cursor (CurrentConversation) is updated to id on every accepted call — including when no child is currently active (the bytes are dropped silently in that case, matching Bridge.Write's discard-on-unattached behaviour). The cursor is NOT mutated when validation refuses the id.
Validation, when configured via Config.ValidateConversation, runs first. A non-nil validator result is returned verbatim — production wiring returns conversations.ErrConversationNotFound for unknown ids, which the handler maps to a wire-level refusal code.
PTY write failures are wrapped with a stable "supervisor: write user turn:" prefix; the underlying error is preserved for errors.Is checks.