ptyrunner

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 17 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 ptyrunner spawns claude as an interactive TUI under a PTY (via github.com/pyrycode/tui-driver), waits for the TUI to reach idle, submits one user prompt through a bracketed-paste sequence, tails the per-session JSONL output, re-emits each event as stream-json on cfg.Stdout, and tears the session down cleanly after the deterministic end-of-turn fires.

`pyry agent-run` will use ptyrunner (post-#470 cutover) to drive claude on the interactive surface Anthropic's 2026-06-15 billing policy explicitly names as subscription-eligible, replacing the stream-json subprocess path in internal/agentrun/streamrunner. The package owns the spawn, the idle-wait, the modal/banner safety check, the prompt write, the JSONL tail + stream-json emit, and the shutdown — nothing else.

This slice composes the pyry-side max-turns budget Counter (from internal/agentrun/budget) and the tui-driver watchdog Tracker (PTY-heartbeat + spinner-freeze) on top of the JSONL tail + stream-json emit from #478; the cmd/pyry/agent_run.go cutover is #470.

The package logs only error messages and never logs PromptBytes content or any substring of the rolling TUI buffer — writers are opaque and the buffer is inspected only via tui-driver's pure-function detectors. The tuidriver.TailJSONL channel drain and the streamjson emitter inherit the same discipline — neither logs entry content; ptyrunner does not add any log call that would either. The wired budget Counter and the watchdog goroutine inherit the same discipline — the Counter logs only count + max_turns numerics and the watchdog goroutine logs only the tuidriver-generated watchdog error string; neither logs entry content.

Dependency direction: the package must not import github.com/pyrycode/pyrycode/internal/supervisor (the PTY helper for the long-lived claude wrapper). The sibling agentrun subpackages (budget, streamjson) are wired here. Verify with:

go list -deps ./internal/agentrun/ptyrunner/... | grep pyrycode/internal/supervisor

Expected output: empty.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrTrustModalDetected fires when the trust-folder modal renders at
	// idle. Remediation lives in #469 (MarkWorkdirTrusted pre-write).
	ErrTrustModalDetected = errors.New("ptyrunner: trust-folder modal detected; pre-write trust via #469's MarkWorkdirTrusted before invoking Run")

	// ErrMcpFailureBanner fires when claude's "N MCP server failed"
	// status banner is present at idle.
	ErrMcpFailureBanner = errors.New("ptyrunner: MCP failure banner detected; check claude's MCP server config")

	// ErrNetworkFailure fires when tui-driver's network-failure detector
	// (tuidriver.HasNetworkFailure) reports the claude API unreachable at idle.
	// The screen-literal anchor it keys on is owned by tui-driver, not named
	// here — pyrycode carries no claude-TUI substrate string.
	ErrNetworkFailure = errors.New("ptyrunner: network failure detected; claude API unreachable")
)

Sentinel-shape errors surfaced when a modal or failure banner is detected at idle. Each one names the failing detector and points to the remediation; consumers (#470's cmd cutover) match with errors.Is to distinguish the trust-modal case from the others for surfacing a hint.

Functions

func Run

func Run(ctx context.Context, cfg Config) (err error)

Run spawns claude under tui-driver with the argv shape buildArgs produces, waits for the TUI to reach idle and classifies the post-idle trust / mcp-failure / network-failure conditions via Session.WaitReady, submits cfg.PromptBytes via Session.DeliverPrompt, drains the per-session JSONL AND polls PTY-state transitions via tuidriver.Session.Events, re-emits each entry as stream-json on cfg.Stdout via streamjson.Emitter, and returns once end-of-turn fires or the context is cancelled.

Return value contract:

  • nil on a clean spawn → idle → deliver → events-to-end-of-turn cycle.
  • nil on operator-shutdown collapse: any ctx-cancel / deadline-exceeded error from Spawn / WaitUntil / WaitForSessionJSONL / Session.Events, and any in-flight emit failure observed during teardown, collapses to nil when ctx.Err() is set (same contract streamrunner uses).
  • errors.New("ptyrunner: <field> required") on missing required fields.
  • fmt.Errorf("ptyrunner: spawn: %w", err) on Spawn failure.
  • fmt.Errorf("ptyrunner: wait idle: %w", err) on a non-ctx WaitUntil error (defensive — WaitUntil only returns ctx.Cause today).
  • ErrTrustModalDetected / ErrMcpFailureBanner / ErrNetworkFailure on the corresponding post-idle one-shot detection OR on a mid-run EventKindPty{ModalShown(trust-folder),McpFailureShown,NetworkFailureShown} transition surfaced on the Session.Events stream. The detection cadence is tui-driver's DefaultPollInterval (50 ms).
  • fmt.Errorf("ptyrunner: deliver prompt: %w", err) on a DeliverPrompt PTY-write failure.
  • fmt.Errorf("ptyrunner: emitter: %w", err) on streamjson.New failure (defensive — Writer is validated upstream and SessionID is required).
  • fmt.Errorf("ptyrunner: home dir: %w", err) when cfg.HomeDir is empty and os.UserHomeDir() fails.
  • fmt.Errorf("ptyrunner: wait jsonl: %w", err) on a non-ctx WaitForSessionJSONL failure (e.g. permission denied on stat).
  • fmt.Errorf("ptyrunner: events: %w", err) on Session.Events synchronous open / seek failure (non-ctx).
  • fmt.Errorf("ptyrunner: emit: %w", err) on the first sticky Emit failure captured during the inline drain (e.g. broken pipe on cfg.Stdout). Prioritised over a clean drain because the emit failure is operator-actionable.

Cleanup ordering — defer LIFO produces:

cancel() → wg.Wait() → counter.Stop() → emitter.Close() → sess.Close() → finalizeRecording()

Each step is load-bearing: cancel() signals the watchdog goroutine (and the tuidriver.Session.Events merge goroutine) to exit; wg.Wait() drains the watchdog so no further SetExitReason(ExitReasonError) races with emitter.Close; counter.Stop() cancels the budget's SIGKILL grace timer; emitter.Close writes the `result` trailer to cfg.Stdout BEFORE sess.Close()'s SIGTERM races with claude's last PTY writes. The tuidriver.Session.Events channel is drained inline by Run's own goroutine, so wg tracks only the watchdog. finalizeRecording() (only registered when PYRY_RECORD_DIR is set) is the strict tail: it renames the .cast recording only after sess.Close() has joined tui-driver's PTY reader goroutine AND closed the RecordTo file (tui-driver owns that file end to end), so the rename cannot race a PTY write or an open handle. Re-ordering these defers silently breaks the invariant — keep them in this LIFO sequence.

Run returns a named err so the recording-finalize defer can read it at fire time; the defer also reads the emitter's resolved ExitReason (the real wedge signal — Run returns nil on a watchdog-fire collapse) to tag -ok / -err by the run's true outcome. No existing defer assigns to err.

Types

type Config

type Config struct {
	// ClaudeBin is the resolved path to the claude executable. Required.
	ClaudeBin string

	// WorkDir is the child process's working directory. Required.
	WorkDir string

	// SessionID is the pyry-minted UUID passed to claude --session-id.
	// Required.
	SessionID string

	// SettingsPath is the path to the deny-default settings JSON produced
	// by #469. Passed via claude --settings. Required.
	SettingsPath string

	// SystemPrompt is the path to the system-prompt file passed via
	// claude --append-system-prompt-file. Required.
	SystemPrompt string

	// Model is the model identifier passed via claude --model. Required.
	Model string

	// Effort is the reasoning-effort selector passed via claude --effort.
	// Required.
	Effort string

	// AllowedTools is the human-readable tool allowlist stamped into the
	// leading `system/init` envelope's `tools` field (via streamjson.New).
	// Required (non-nil; empty slice OK). The runtime enforcement is the
	// deny-default settings file at SettingsPath; this list is the
	// wire-shape mirror of those names, kept caller-synchronised at the
	// runAgentRunPty wiring site.
	AllowedTools []string

	// MaxTurns is the assistant-entry cap enforced by the pyry-side budget
	// Counter (internal/agentrun/budget). Required; must be > 0. The
	// interactive-TUI claude path intentionally omits --max-turns from argv
	// because interactive claude does not honor it; this field is the
	// load-bearing enforcement point. On budget hit the run is terminated
	// with ExitReasonMaxTurns set on the streamjson emitter.
	MaxTurns int

	// PromptBytes is the user-turn prompt text submitted via
	// tuidriver.Session.DeliverPrompt. Required (must be non-empty; an empty
	// paste has no semantics in the TUI).
	//
	// PromptBytes content MUST NOT appear in any log line or in any
	// wrapped error message — the package's logging discipline forbids
	// it.
	PromptBytes []byte

	// Stdout is where the streamjson.Emitter writes per-event stream-json
	// lines and the trailing `type:"result"` trailer. Required.
	// Production callers pass os.Stdout; tests pass a bytes.Buffer or a
	// failing writer.
	Stdout io.Writer

	// Stderr receives the child's stderr. Required. (The interactive-TUI
	// claude writes stderr separately from the PTY-mirrored stdout —
	// tui-driver does not multiplex them.)
	Stderr io.Writer

	// HomeDir is an optional test seam. When non-empty, it overrides the
	// home directory used to resolve the per-session JSONL path
	// (~/.claude/projects/<encoded-workdir>/<session-id>.jsonl).
	// Production callers leave it empty; os.UserHomeDir() is consulted in
	// that case. Tests use a t.TempDir() value so each test gets an
	// isolated ~/.claude/projects tree.
	HomeDir string

	// Env is appended to os.Environ() in the child process. Optional;
	// production callers leave it nil. Tests use it to thread
	// TestHelperProcess wiring. EnsureClaudeEnv (called after this
	// package wires cmd.Env) sets TERM=xterm-256color.
	Env []string

	// WatchdogTick is the cadence at which the watchdog goroutine polls
	// the rolling buffer + spinner state. Optional; zero defaults to 1
	// second (matches the tui-driver spike binaries). Tests typically set
	// 50ms to keep wall-clock low.
	WatchdogTick time.Duration

	// WatchdogTrackerOpts is forwarded verbatim to tuidriver.NewTracker.
	// Optional; zero values pick the tuidriver-package defaults
	// (PTYQuietLimit = 30s, SpinnerFreezeLimit = 30s). Tests use short
	// values (~200ms) to fire the watchdog within the test deadline.
	WatchdogTrackerOpts tuidriver.TrackerOpts

	// PromptCommitTimeout bounds how long each delivery attempt waits for a
	// freshly-delivered prompt to commit (spinner up or session JSONL written)
	// before treating the paste as corrupted/uncommitted and re-delivering.
	// Forwarded verbatim to tuidriver.DeliverPrompt as DeliverOpts.CommitTimeout;
	// zero picks tui-driver's DefaultPromptCommitTimeout. Tests set a short value
	// to keep the retry budget well inside the deadline.
	PromptCommitTimeout time.Duration

	// Logger is used for the small number of Warn-level diagnostics this
	// package emits (spawn / close / modal-detected). Optional; nil
	// falls back to slog.Default().
	Logger *slog.Logger
}

Config configures Run. Required fields are validated at entry; optional fields are documented below.

Jump to

Keyboard shortcuts

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