streamrunner

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 16 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 streamrunner spawns claude with the stream-json input/output formats as a plain subprocess (no PTY), writes one user-turn JSON envelope to its stdin, forwards stdout/stderr to caller-supplied writers, and waits for the child to exit.

`pyry agent-run` uses streamrunner to drive claude in `--input-format stream-json --output-format stream-json` mode from a single shot of stdin; the package owns the spawn, the stdin write, and the wait — nothing else.

The package logs only diagnostic messages and never logs prompt bytes or any substring of the stream-json event stream. It tee-parses stdout for STRUCTURAL fields only — the top-level `type` of each event line, to drive the idle-stall watchdog (see watchdog.go) — and never inspects, retains, or logs event content.

Dependency direction: the package must not import github.com/pyrycode/pyrycode/internal/supervisor (the PTY helper) nor any of the other agentrun subpackages. Verify with:

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

Expected output: empty.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildClaudeArgs added in v0.16.0

func BuildClaudeArgs(p ArgsParams) []string

BuildClaudeArgs assembles the claude argv (excluding argv[0]) for a headless stream-json spawn. It is the single source of that shape, shared by `pyry agent-run` and by the permission self-check that exists to verify the shape enforces what it claims.

That sharing is the point rather than a convenience. The self-check spawns a real claude and proves the settings file blocks a tool that is not on the allowlist. A self-check assembling its own argv would verify a spawn nobody performs, which is how the check ended up attached to a runner production had already stopped using.

Two flag choices are load-bearing and neither is obvious:

  • `--permission-mode dontAsk`, NOT `--dangerously-skip-permissions`. dontAsk is the documented mode for CI and restricted environments: it auto-denies anything not pre-approved and never waits for input. The skip flag looked equivalent and is not, because it outranks every mode including the one the settings file itself asks for. With it present the allowlist enforced nothing at all, which is how every dispatched agent ran unrestricted for two weeks after the 2026-07-25 fleet switch (#1387).
  • `--settings` carries the per-spawn deny-default file and IS the boundary. `--allowed-tools` is still passed because it is harmless and becomes meaningful again if the permission mode changes, but it must never be relied on as the enforcement.

func Run

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

Run spawns claude with cfg.Args, writes one stream-json user-turn envelope to its stdin and closes stdin, forwards stdout/stderr to the configured writers, and waits for the child to exit.

An idle-stall watchdog (see watchdog.go) runs alongside: it tee-parses stdout for structural `type` fields and, if the stream sits silent past cfg.IdleTimeout *while claude owes an assistant turn*, kills claude and makes Run synthesise a distinct, retryable `idle_stall` result line on stdout (claude never emits its own `result` on a watchdog kill).

Return value contract:

  • nil on a clean (exit 0) child termination.
  • nil on operator-shutdown teardown (parent ctx cancel) — success.
  • nil on an idle-stall watchdog kill — the synthetic result line on stdout is the signal; pyry exits clean and the dispatcher retries.
  • nil on a non-zero child exit that still produced a complete result trailer — the trailer is the outcome, and its own is_error / subtype / terminal_reason fields carry the failure the caller acts on. A budget stop is the common case: `--max-turns` emits a good trailer AND exits 1 (pyrycode#1388).
  • *exec.ExitError on non-zero child exit with NO result trailer, and not triggered by a cancel. Here the exit status is the only signal there is.
  • a wrapped error from pre-Start setup (stdin pipe, spawn).

On either cancel (operator shutdown of the parent ctx, or the watchdog cancelling its child ctx) the child receives SIGTERM and is given killGrace to exit before stdlib follows up with SIGKILL — wired via exec.Cmd.Cancel + exec.Cmd.WaitDelay.

Types

type ArgsParams added in v0.16.0

type ArgsParams struct {
	// SystemPromptFile is passed to --append-system-prompt-file. Required by
	// claude even when empty is meant; callers with nothing to append pass
	// /dev/null, a portable 0-byte readable device on both targets.
	SystemPromptFile string

	Model    string
	Effort   string
	MaxTurns int

	// AllowedTools is comma-joined for --allowed-tools. Note this flag is NOT
	// the enforcement — see SettingsPath.
	AllowedTools []string

	// SettingsPath is the per-spawn deny-default settings file, and it is what
	// actually enforces the tool boundary. Omitted from the argv when empty.
	SettingsPath string

	// PermissionArgs replaces the default `--permission-mode dontAsk` pair when
	// non-empty. This is the daemon-approval branch, which routes every tool use
	// through the approval registry instead of auto-denying.
	PermissionArgs []string
}

ArgsParams is the input to BuildClaudeArgs: everything that varies between one headless claude spawn and another.

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

	// Args is the full claude argv (excluding argv[0]). The caller
	// assembles flag shape — Run does not know about claude's flags.
	Args []string

	// PromptBytes is the user-turn prompt text. UTF-8; may contain quotes,
	// newlines, or control characters — Run JSON-encodes it, so embedded
	// metacharacters are safe. May be empty (a valid no-op turn).
	PromptBytes []byte

	// Stdout receives the child's stdout. Required.
	//
	// MUST NOT block — a writer that stalls will deadlock cmd.Wait()
	// because the stdlib's internal forwarder blocks on writing into it
	// while the child is still running.
	Stdout io.Writer

	// Stderr receives the child's stderr. Required. Same non-blocking
	// requirement as Stdout.
	Stderr io.Writer

	// Env is appended to os.Environ() in the child process. Optional;
	// production callers leave it nil. Tests use it to thread
	// TestHelperProcess wiring.
	Env []string

	// Logger is used for the small number of Warn-level diagnostics this
	// package emits (stdin write/close failures, idle-stall watchdog fire).
	// Optional; nil falls back to slog.Default().
	Logger *slog.Logger

	// IdleTimeout overrides the idle-stall watchdog threshold (the silence
	// budget while claude owes an assistant turn). Optional; zero or negative
	// falls back to the idleStall default. Production leaves it unset; tests
	// shrink it so a stall fires in milliseconds.
	IdleTimeout time.Duration
}

Config configures Run. Required fields are validated at entry; zero values for optional fields fall through to documented defaults.

Jump to

Keyboard shortcuts

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