supervisor

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 14 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 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

Constants

This section is empty.

Variables

View Source
var ErrBridgeBusy = errors.New("supervisor: bridge already has an attached client")

ErrBridgeBusy is returned by Bridge.Attach when another client is already attached.

View Source
var ErrNoLiveSession = errors.New("supervisor: no live session")

ErrNoLiveSession is returned by WriteUserTurn when no claude session is registered at delivery time — the supervisor is between runOnce iterations, has not yet spawned, or is mid-restart. Formerly this was a silent drop (return nil); it is now a loud failure so the relay send_message handler reports it to the phone instead of acking a turn that never reached claude.

View Source
var ErrTurnNotCommitted = errors.New("supervisor: turn not committed")

ErrTurnNotCommitted is returned by WriteUserTurn when DeliverPrompt delivered the turn but could not confirm a commit (DeliverResult.Committed == false) after its bounded recovery — the turn may still be wedged. Like ErrNoLiveSession it maps to a loud failure rather than a false ack.

Functions

func SpawnPTY added in v0.12.0

func SpawnPTY(ctx context.Context, cfg SpawnConfig) (*exec.Cmd, *os.File, error)

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

func NewBridge(log *slog.Logger) *Bridge

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

func (b *Bridge) Attach(in io.Reader, out io.Writer) (done <-chan struct{}, err error)

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

func (b *Bridge) Attached() bool

Attached reports whether a client is currently attached.

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

func (b *Bridge) Read(p []byte) (int, error)

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

func (b *Bridge) Resize(rows, cols uint16) error

Resize forwards the given window size to the registered resize delegate (a tui-driver *Session). Returns nil silently when no delegate is registered (between iterations, or in foreground mode where no Bridge exists at all). The delegate wraps its own error ("tuidriver: resize …"), returned verbatim for the caller to log; the control plane does not fail the attach on resize errors.

rows-then-cols matches Session.Resize and 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

func (b *Bridge) SetOutputObserver(fn func([]byte))

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) SetResizer added in v0.15.0

func (b *Bridge) SetResizer(r resizer)

SetResizer registers (or clears, when r is nil) the resize delegate for the current runOnce iteration. Subsequent Resize calls forward to it. runOnce calls SetResizer(sess) after Spawn succeeds and SetResizer(nil) before EndIteration so a Resize racing iteration teardown forwards to nil (a silent no-op) rather than a closing session.

Pass an untyped nil to clear. A typed nil (e.g. a nil *tuidriver.Session) is a non-nil interface; Resize would then dereference it. runOnce always clears with the untyped nil literal.

func (*Bridge) Write

func (b *Bridge) Write(p []byte) (int, error)

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

	// ResolveTranscript, when non-nil, resolves the newest claude transcript for
	// the supervised workdir: its absolute path and current byte size. ("", 0,
	// nil) means no transcript exists yet (valid — a fresh session that has
	// written no turn). A non-nil error means the dir is unreadable.
	//
	// When set, deliverViaSession uses transcript *growth* as a deterministic
	// commit signal instead of trusting DeliverResult.Committed (tui-driver's
	// chip heuristic, which false-acks short single-line turns lost to a
	// --continue restart race). When nil, the #594 Committed-based behaviour is
	// preserved (foreground mode, tests). Modelled on ValidateConversation:
	// optional, nil-safe, the production-vs-test seam.
	ResolveTranscript func(ctx context.Context) (path string, size int64, err error)
	// contains filtered or unexported fields
}

Config controls a Supervisor instance.

type Phase

type Phase string

Phase describes the supervisor's current lifecycle state.

const (
	PhaseStarting Phase = "starting" // before the first child has been spawned
	PhaseRunning  Phase = "running"  // a child process is alive
	PhaseBackoff  Phase = "backoff"  // waiting before the next restart
	PhaseStopped  Phase = "stopped"  // Run has returned
)

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) AcceptTrust added in v0.15.0

func (s *Supervisor) AcceptTrust() error

AcceptTrust sends claude's trust-folder accept keystroke ("1\r") to the live session. Answer and SendEsc are siblings. These three turn an abstract modal choice into the matching tui-driver keystroke so higher layers (the gated remote answer, cancel, deny-on-timeout legs) can resolve a modal without importing tui-driver or reaching into the child PTY directly. The primitive carries no trust decision — it routes whatever keystroke it is told to; the authorization (per-device gate, nonce validation, idempotency, option_id → choice mapping) lives entirely in the consumer.

Unlike WriteUserTurn, these take no context.Context: a keystroke is a single non-blocking pty.Write with nothing to cancel (WriteUserTurn blocks for seconds on WaitReady + DeliverPrompt). A ctx here would advertise a cancellation contract the method cannot honor, so it is deliberately absent — do not cargo-cult one from WriteUserTurn.

Returns ErrNoLiveSession (wrapped) when no claude child is attached, and writes no keystroke in that case. A PTY write error from a session torn down mid-write surfaces as a loud wrapped error, never a crash (see sendModalKey).

func (*Supervisor) Answer added in v0.15.0

func (s *Supervisor) Answer(choice string) error

Answer sends modal choice (the literal option token claude renders, e.g. "1", "2", "y") followed by the commit. See AcceptTrust for the shared contract.

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) ScreenSnapshot added in v0.15.0

func (s *Supervisor) ScreenSnapshot() (text string, live bool)

ScreenSnapshot renders the current claude screen to plain text. live is false when no claude child is attached (between restarts, mid-spawn, or idle- evicted); text is "" then. Safe for concurrent use and non-blocking: it captures the live Session under sessMu (a pointer read), releases the lock, then does a bounded in-memory VT100 render — no I/O, no channel ops — so it never wedges the caller. It backs the relay's on-demand request_snapshot (ADR 025 § Safe degradation), the parser-independent live-view escape hatch.

SECURITY: the raw bytes from sess.Snapshot() are consumed by tuidriver.Render in the same expression and are never named or stored in pyrycode, so no claude-screen literal enters this package (cmd/substrate-guard stays green). The render runs inside the tui-driver seal; pyrycode forwards only the opaque rendered text. 0,0 selects tui-driver's default grid, matching the daemon PTY's allocation, so the render is 1:1 in headless mode.

func (*Supervisor) SendEsc added in v0.15.0

func (s *Supervisor) SendEsc() error

SendEsc sends a single ESC to dismiss a modal or cancel an in-flight turn. See AcceptTrust for the shared contract.

func (*Supervisor) Session added in v0.15.0

func (s *Supervisor) Session() *tuidriver.Session

Session returns the currently-hosted tui-driver Session, or nil when no claude child is attached (between restarts, mid-spawn, or idle-evicted). Safe for concurrent use; captures the pointer under sessMu, mirroring ScreenSnapshot's capture. The event-stream producer (internal/turnbridge) subscribes to the returned session's Events() stream.

SECURITY: returning *tuidriver.Session does not breach the substrate seal. The supervisor already holds and uses this pointer; the producer only calls sess.Events() (typed events) — never MirrorOutput()/Snapshot() (raw bytes) — so no claude-screen literal enters pyrycode (cmd/substrate-guard stays green).

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 live Session (registered by setSession 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-live Session (returns immediately).

Session.Activate calls this at the tail of its waiting phase so callers that follow Activate with WriteUserTurn observe a live Session rather than the ~hundreds-of-ms gap between transitionTo closing activeCh and runOnce hosting the new Session.

func (*Supervisor) WorkDir added in v0.15.0

func (s *Supervisor) WorkDir() string

WorkDir returns the working directory the supervised claude was spawned in (Config.WorkDir, immutable post-New, so no lock — unlike State which guards mutable state). Empty when the supervisor was built with no WorkDir (inherits the process cwd). The turn bridge derives a conversation's per-Cwd transcript directory from it: claude writes <session-id>.jsonl under ~/.claude/projects/<encoded-WorkDir>/, so this is the authoritative, byte-exact spawn cwd to encode (#686).

func (*Supervisor) WriteUserTurn added in v0.11.0

func (s *Supervisor) WriteUserTurn(ctx context.Context, id string, payload []byte) error

WriteUserTurn delivers a user-turn payload to the supervised claude child, tagged with the caller's conversation_id, and returns nil only when claude confirms the turn committed. It is the delivery path for untrusted, phone-originated turns (relay send_message → here → live claude); a turn that cannot be confirmed delivered is a loud failure, never a silent ack.

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. The cursor (CurrentConversation) is stamped to id before delivery on every validated call — including when delivery then fails — but is NOT mutated when validation refuses the id.

Delivery captures the live Session under sessMu, releases the lock, then delivers on the captured pointer (WaitReady + DeliverPrompt can run for seconds; holding sessMu that long would block runOnce's teardown). A concurrent setSession(nil)+Close racing the captured pointer is safe: it lands in tui-driver's teardown-safe PTY-error path (no panic), so a session torn down mid-delivery surfaces here as a loud failure, never a crash or a false ack. This relaxes — without breaking — runOnce's setSession(nil)- before-Close ordering: a racing WriteUserTurn may now deliver against a closing session, but only into that error path.

Failure modes — no live session (ErrNoLiveSession), claude not idle within the caller's ctx, an uncommitted/wedged turn (ErrTurnNotCommitted), or a PTY write error — all return non-nil, wrapped with the stable "supervisor: write user turn:" prefix. The underlying error is preserved for errors.Is checks (including context.DeadlineExceeded / context.Canceled through WaitReady).

Jump to

Keyboard shortcuts

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