supervisor

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: MIT Imports: 13 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.

Functions

This section is empty.

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 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) SetPTY added in v0.8.0

func (b *Bridge) SetPTY(f *os.File)

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

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

Jump to

Keyboard shortcuts

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