streamsup

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 20 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 streamsup supervises a long-lived headless claude child in stream-json mode: it spawns claude with --input-format stream-json --output-format stream-json --verbose, holds the child's stdin open across many turns, restarts the child on crash with an exponential-backoff-with-stability-reset ladder, resumes with --resume <id> (reusing the same on-disk session id, no fork), and shuts down cleanly (SIGTERM → SIGKILL grace plus a reap of claude's detached descendant Bash process groups).

It is the stream-json sibling of internal/supervisor (the PTY path). Unlike the PTY path it binds no transcript: there is deliberately NO transcript tailing, no fsnotify, and no <uuid>.jsonl path resolved for tailing or binding anywhere in this package — that is the whole point of the stream-json path (it structurally removes the bind-latency race the PTY path fought). The one transcript touch is a by-id EXISTENCE stat, at most one per spawn and only when Config.ClaudeSessionsDir is set: useCreateForm asks whether this session's own transcript is already on disk to pick the spawn's id flag, and reads no bytes from it. The only filesystem canonicalisation done here is resolving WorkDir before spawn (macOS /tmp → /private/tmp symlink hygiene).

This slice owns the process lifecycle only. Turn I/O — the stdin envelope writer and the stdout→turnevent parser — and the turncommit/idle/stall gates are follow-on slices that build on the seams here (Stdin() and Config.Stdout).

Dependency direction: the package must not import github.com/pyrycode/pyrycode/internal/supervisor (the PTY helper) nor any of the internal/agentrun subpackages (streamrunner, trust, …). It imports the internal/agentrun root package (ReapDescendantGroups, ResolveWorkdir, ExitErrIsBenign) — the shared parent, not a sibling. Verify with:

go list -deps ./internal/streamsup/... | grep pyrycode/internal/supervisor

Expected output: empty.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoLiveChild = errors.New("streamsup: no live child")

ErrNoLiveChild is returned by WriteTurn when the child's stdin handle is nil — no claude child is currently live (before the first spawn, between spawns, or mid-restart). Runner.Stdin returns an untyped nil in exactly those windows, which WriteTurn's w == nil check maps to this sentinel. The wiring slice maps it to a retryable "no live child" outcome.

View Source
var ErrUnsupportedContextUsageDetail = errors.New("streamsup: unsupported context usage detail")

ErrUnsupportedContextUsageDetail is returned when a context-usage request names a detail outside the closed vocabulary claude accepts. It is permanent, errors.Is-distinguishable from ErrNoLiveChild, and intentionally omits the rejected value so it cannot reach logs through the error return.

View Source
var ErrUnsupportedPermissionMode = errors.New("streamsup: unsupported permission mode")

ErrUnsupportedPermissionMode is returned by WritePermissionMode when the caller names a mode outside permissionModeAllowed's closed set. It is a permanent refusal, unlike the retryable ErrNoLiveChild, and the two must stay errors.Is-distinguishable: a caller that mistook this for "no live child" would retry a request that can never succeed.

It is returned BARE, never wrapped with the rejected value. Its text is a constant precisely so it cannot echo the mode: Pool.deliverSettingsInBand logs this error verbatim, and #833 keeps settings values out of the daemon log. A mode is a settings value, so the obvious fmt.Errorf("… %q", mode) would leak an operator's value into the log through the error return. The refusal tells an operator THAT a mode was refused; which one is recoverable from the request they sent, not from pyry's log.

Functions

func WriteAppliedSettings added in v0.20.0

func WriteAppliedSettings(w io.Writer, requestID string) error

WriteAppliedSettings writes one get_settings request to the live child's held-open stdin and returns without waiting for its reply. The request id is locally minted; fixed error contexts keep it out of logs.

func WriteCanUseToolAllow

func WriteCanUseToolAllow(w io.Writer, requestID string, updatedInput, updatedPermissions json.RawMessage) error

WriteCanUseToolAllow writes one control_response line onto w, the child's held-open stdin (from Runner.Stdin), approving the can_use_tool request identified by requestID. It mirrors WriteInitialize exactly: nil-check first, marshal, one Write, never close w — the io.Writer type structurally forbids a half-close/EOF forgery, which on a stream-json child would mean "no more input" and take the live session down without killing it.

requestID must be CLAUDE'S OWN id, taken from the CanUseToolRequest being answered, and this is the one Write* in this file where a locally-minted id would be WRONG: the whole point of the echo is that claude matches the answer to its ask. There is no in-repo caller yet — #2284 installs the answerer that becomes one.

A nil w means no live child: ErrNoLiveChild, nothing written (checked first, so no panic and no partial write). A marshal failure — reachable here, unlike in this file's four siblings, when updatedInput or updatedPermissions is not well-formed JSON — and a write failure (e.g. EPIPE when the pipe closed mid-teardown) are returned wrapped, never mis-reported as the retryable ErrNoLiveChild. Both refusals write zero bytes: a half-written envelope on the child's stdin is worse than no answer, because claude would read the fragment as the head of some other line.

No wrap carries the payload. An answerer's updatedInput is a settings-shaped value in the sense #833 draws, and routing it into the daemon log through an error return is the channel ErrUnsupportedPermissionMode's doc exists to close.

func WriteCanUseToolDeny

func WriteCanUseToolDeny(w io.Writer, requestID, message string, interrupt bool) error

WriteCanUseToolDeny writes one control_response line onto w, the child's held-open stdin (from Runner.Stdin), refusing the can_use_tool request identified by requestID. It is WriteCanUseToolAllow's twin in every respect above — the same nil-check-first ordering, the same single Write, the same refusal to close w, the same requirement that requestID be claude's own echoed id.

The one difference is what may be hostile. A marshal failure is not reachable here (two strings and a bool), so the defensive branch stays for symmetry; what this direction carries instead is message, whose untrusted content marshalCanUseToolDeny documents and neutralises by construction.

No wrap carries the message, for WriteCanUseToolAllow's reason and one more: the message may be claude's own prose, and an error return is not a channel any per-attribute log check can see.

func WriteContextUsage

func WriteContextUsage(w io.Writer, requestID, detail string) error

WriteContextUsage writes one validated get_context_usage request to the live child's held-open stdin. Vocabulary refusal precedes the no-child refusal so an unsupported value is permanent regardless of child state. Fixed error contexts keep both the detail and locally minted request ID out of logs.

func WriteInitialize

func WriteInitialize(w io.Writer, requestID string) error

WriteInitialize writes one initialize control_request line onto w, the child's held-open stdin (from Runner.Stdin), asking the live child to report what it knows about itself without a respawn. It mirrors WritePermissionMode minus the allow-list gate (this subtype has no caller-supplied field to gate): nil-check first, marshal, one Write, never close w — the io.Writer type structurally forbids a half-close/EOF forgery, which on a stream-json child would mean "no more input" and take the live session down without killing it.

requestID must be a LOCALLY-MINTED id — Runner.nextControlID is the only source that satisfies this, and (*Runner).RequestInitialize is the only in-repo caller. The structured encoding makes a hostile id non-catastrophic rather than merely unlikely (json.Marshal escapes every metacharacter, so no id can open a second physical line or rewrite the fixed subtype), but the contract is the primary defence and the escaping the backstop.

A nil w means no live child: WriteInitialize returns ErrNoLiveChild and writes nothing (checked first, so no panic and no partial write). A marshal failure (not reachable with fixed literals, defensive) and a write failure (e.g. EPIPE when the pipe closed mid-teardown) are returned wrapped — never mis-reported as the retryable ErrNoLiveChild.

The control_response ack is not read here: this function writes the line and stops. Its ack is not ignored by the daemon, though, and the difference from WritePermissionMode's is worth stating — the parser's noteControlAck sees BOTH acks, off one counter, and refuses this one by id alone. That refusal is the whole reason the two spawn-time writes must never share an id: an initialize ack that matched would open a posture gate it never answered.

func WriteInterrupt

func WriteInterrupt(w io.Writer, requestID string) error

WriteInterrupt writes one interrupt control_request line onto w, the child's held-open stdin (from Runner.Stdin). It mirrors WriteTurn minus the turncommit gate: an interrupt is not a queued turn, so there is nothing to claim or drop.

A nil w means no live child: WriteInterrupt returns ErrNoLiveChild and writes nothing (checked first, so no panic and no partial write — AC2). A marshal failure (not reachable with fixed literals, defensive) and a write failure (e.g. EPIPE when the pipe closed mid-teardown) are returned wrapped; it never closes w — the io.Writer type structurally forbids a half-close/EOF forgery.

func WriteMCPReconnect

func WriteMCPReconnect(w io.Writer, requestID, serverName string) error

WriteMCPReconnect writes one mcp_reconnect request to the live child's held-open stdin and returns without waiting for its reply. Server membership and authorization belong to the caller boundary.

func WriteMCPStatus

func WriteMCPStatus(w io.Writer, requestID string) error

WriteMCPStatus writes one mcp_status request to the live child's held-open stdin and returns without waiting for its reply.

func WriteMCPToggle

func WriteMCPToggle(w io.Writer, requestID, serverName string, enabled bool) error

WriteMCPToggle writes one mcp_toggle request to the live child's held-open stdin and returns without waiting for its reply. Server membership and authorization belong to the caller boundary.

func WriteModel

func WriteModel(w io.Writer, requestID, model string) error

WriteModel writes one set_model request to the held-open child stdin. Model servability is not validated at this layer: the control response cannot report it reliably, and the caller's trust boundary owns syntactic validation.

func WritePermissionMode

func WritePermissionMode(w io.Writer, requestID, mode string) error

WritePermissionMode writes one set_permission_mode control_request line onto w, the child's held-open stdin (from Runner.Stdin), switching the live child's permission posture without killing it. It mirrors WriteInterrupt: refuse, marshal, one Write, never close w — the io.Writer type structurally forbids a half-close/EOF forgery.

It replaced #1603's WriteBypassRevocation, which took no mode and emitted "default" alone. That writer's safety property was "no escalation reachable from this surface", and #2066 ENDS it deliberately rather than eroding it: the allow-list now admits the escalation, because a re-escalation is the transition that ticket routes in band. What this surface still guarantees is narrower and exact — no mode claude will not parse reaches the child, refused by non-membership so every unanticipated spelling is refused with it. Authorisation was never this function's job and is now the only stop the escalation has: see permissionModeAllowed for where it is made.

The two refusals, in the order they are checked:

  • mode outside permissionModeAllowed → ErrUnsupportedPermissionMode, bare.
  • w == nil (no live child) → ErrNoLiveChild.

The allow-list check comes FIRST, and the order is a contract rather than an accident. Both orderings write zero bytes, so this is not about the wire; it is about what the caller is told. Reversed, a caller naming a mode claude cannot parse while no child was bound would get back the RETRYABLE ErrNoLiveChild and could reasonably retry forever against a request that can never succeed. A vocabulary refusal is permanent and must read as permanent whatever the child is doing.

requestID must be a LOCALLY-MINTED id, and Runner.nextControlID is the only source that satisfies it. There are TWO in-repo callers, not one: (*Runner).SetPermissionMode for a live child's posture change, and spawnAndWait for the spawn-time write — both mint off that counter, so the contract holds at each. (The count matters beyond bookkeeping: #2066's argument that the escalation is reachable only from the routing path is an argument about this caller set, so a reader auditing it needs the set to be right.) The structured encoding makes a hostile id non-catastrophic rather than merely unlikely, but the contract is the primary defence and the escaping the backstop.

A marshal failure (not reachable for two strings, defensive) and a write failure (e.g. EPIPE when the pipe closed mid-teardown) are returned wrapped, never mis-reported as either refusal. No wrap carries the mode: an operator's value must not reach the daemon log through an error return (see ErrUnsupportedPermissionMode).

The ack is not read HERE, but it IS read (#2064), and the distinction matters to anyone reasoning about the request_id. This function still writes and returns; the correlation lives one layer up, in the parser's noteControlAck, which matches the id against Runner.PostureGate and either opens the gate or records claude's refusal. Two consequences bind a caller: the id must stay locally minted and unique (see above), and a caller that reuses one would hand a stale ack the power to open a gate it does not belong to. Claude's own per-model refusal of auto (#2041) lands on that same path and is no longer discarded — it is what marks the gate refused.

func WriteTurn

func WriteTurn(ctx context.Context, w io.Writer, prompt []byte) error

WriteTurn writes one user-turn stream-json envelope for prompt onto w, the child's held-open stdin (from Runner.Stdin). It writes exactly once and never closes w — holding stdin open for the next turn is the whole point of this path, and the io.Writer type structurally forbids a half-close/EOF forgery.

ctx carries the turncommit gate on the queue-driven delivery path. WriteTurn claims it after the nil-writer check and before marshalling — mirroring supervisor.deliverViaSession on the PTY path. A false claim means the queued head was dropped during the wait for claude to go ready, so WriteTurn returns turncommit.ErrDropped and writes zero bytes: a dropped turn must never reach the live session. A nil gate (the non-queue paths, e.g. a direct single-turn send) delivers unconditionally.

A nil w means no live child: WriteTurn returns ErrNoLiveChild and writes nothing, and does so BEFORE the gate is claimed — a head that cannot yet be written must stay droppable, so the retryable ErrNoLiveChild wins over a false gate. A write failure (e.g. EPIPE when the pipe closed mid-teardown) is returned wrapped; a closed-pipe write returns an error rather than panicking, so the teardown race (Stdin() captures the handle, teardown closes it, then WriteTurn writes) surfaces as the returned error, never a panic or false ack.

The caller writes turn N+1 by calling WriteTurn(ctx, runner.Stdin(), next) again on the same handle — no re-open, no per-turn stdin lifecycle.

Types

type AppliedSettings added in v0.20.0

type AppliedSettings struct {
	Model  string
	Effort *string
}

AppliedSettings is the bounded subset of Claude's get_settings reply a daemon caller may use. Model and Effort are child-authored display data, not trusted identifiers or authorization input. Effort nil preserves an explicit JSON null; unavailable information is reported by QueryAppliedSettings's bool instead.

No effective setting, source, environment value, path or credential is decoded into this type. Callers must not log a value wholesale merely because it is small.

type CanUseToolRequest

type CanUseToolRequest struct {
	// RequestID is CLAUDE'S OWN correlation id, read off the envelope. An answer must
	// echo it — see WriteCanUseToolAllow — or claude cannot match the two.
	RequestID string `json:"-"`

	ToolName  string `json:"tool_name"`
	ToolUseID string `json:"tool_use_id"`
	// AgentID is set only when the ask comes from inside a subagent.
	AgentID string `json:"agent_id"`

	// Input is the tool's arguments, carried BYTE-VERBATIM so an answerer can hand
	// them straight back as an allow's updatedInput without a re-encode changing a
	// single byte. Nothing here interprets them.
	Input json.RawMessage `json:"input"`
	// PermissionSuggestions is claude's proposed rule changes — what a client's
	// "don't ask again" is built from. Carried opaquely and byte-verbatim for Input's
	// reason; #2286 is the slice that interprets it.
	PermissionSuggestions json.RawMessage `json:"permission_suggestions"`

	// BlockedPath is a path claude reports IT refused. Never opened, stat-ed, joined
	// or canonicalised by anything in this package — it is a string to show, and a
	// consumer that later resolves it inherits the traversal question whole.
	BlockedPath string `json:"blocked_path"`

	// DecisionReason is why claude is asking, and DecisionReasonType classifies it.
	// The reason is json.RawMessage under the typing rule above: the ticket pins the
	// TYPE to one of eleven strings but says nothing about the reason's own shape, and
	// a structured reason beside a classifying enum is at least as likely as prose.
	DecisionReason     json.RawMessage `json:"decision_reason"`
	DecisionReasonType string          `json:"decision_reason_type"`
	// MatchedAskRule is the rule that produced the ask, shape unpinned by the ticket
	// and so carried opaquely under the same rule.
	MatchedAskRule json.RawMessage `json:"matched_ask_rule"`

	ClassifierApprovable    bool `json:"classifier_approvable"`
	SuppressAlwaysAllowRule bool `json:"suppress_always_allow_rule"`
	DefaultToNo             bool `json:"default_to_no"`
	RequiresUserInteraction bool `json:"requires_user_interaction"`

	// The three strings a modal shows. Untrusted like every field here.
	Title       string `json:"title"`
	DisplayName string `json:"display_name"`
	Description string `json:"description"`
}

CanUseToolRequest is one inbound can_use_tool control request, decoded (#2282). claude writes it on the same stdout this parser reads when the child was launched with --permission-prompt-tool stdio, and it is the ask a client modal renders: far more than an approval MCP tool receives, which is the whole reason for reading it here.

EVERY FIELD ON THIS TYPE IS CLAUDE-AUTHORED AND UNTRUSTED. That has to be said out loud because the field names read like daemon-authored UI strings — Title, DisplayName, Description — and a handler that renders one unescaped, or joins BlockedPath onto a filesystem path, is the foreseeable misuse. This type IS the trust boundary's marker: nothing outside the decode below constructs one, so a value of this type in hand means "subprocess bytes". No field is length-capped here, which is deliberate and bounded — see the parser's arm for why the cap belongs to whoever first puts these on the wire (#2286), and defaultMaxParseBuf for what bounds them in the meantime.

FIELD TYPING FOLLOWS ONE RULE, and it is a consequence of provenance. The shapes come from the Agent SDK type definitions the ticket cites rather than from a line a live claude has been sent, and no fixture in this repo can check them. So a field the ticket's own phrasing pins to a scalar is declared as that scalar, and every field whose JSON shape is NOT pinned is json.RawMessage — which accepts any JSON and therefore cannot turn a wrong guess into a failed decode and a LOST PERMISSION ASK. A lost ask is the expensive failure here: claude waits for an answer that never comes.

RequestID is tagged `json:"-"` because it is the ENVELOPE's field, not the inner request's, and canUseToolLine fills it after decoding. Declaring the 18 inner fields once on this type rather than twice across a wrapper and a payload struct is what that tag buys.

DecisionReasonType is carried VERBATIM and is not validated against the eleven spellings the ticket lists. Deciding what an unrecognised reason means belongs to whoever renders or answers the ask; a vocabulary gate here would silently drop an ask on a spelling a later claude adds. The contrast with permissionModeAllowed is exact and worth holding: that gate bounds a value the daemon SENDS, where refusing an unknown spelling is the safe direction. This is a value the daemon RECEIVES, where refusing one throws away news.

type Config

type Config struct {
	// ClaudeBin is the resolved path to the claude executable. Required;
	// New surfaces a not-found error via exec.LookPath.
	ClaudeBin string

	// WorkDir is the child process's working directory. Required. New resolves
	// it via agentrun.ResolveWorkdir (macOS /tmp → /private/tmp, the #989
	// symlink hazard); the resolved path is what cmd.Dir is set to and is the
	// only path canonicalisation this package performs.
	WorkDir string

	// SessionID is the caller-minted claude session id. Required (non-empty
	// check only — the pool owns minting and shape validation). With no
	// ClaudeSessionsDir the first spawn passes --session-id <SessionID> and every
	// respawn passes --resume <SessionID> (reattach, append, no fork); with one
	// set, the by-id transcript probe picks the form per spawn instead (see
	// useCreateForm). Either way the SAME id is passed, so the on-disk id stays
	// stable across a kill-and-restart.
	SessionID string

	// ClaudeSessionsDir is the directory containing claude's <uuid>.jsonl files
	// for this WorkDir. Empty disables the by-id transcript probe, and every
	// spawn's id flag falls back to the Run loop's firstRun latch — byte-identical
	// to pre-#1630 argv. Name and semantics mirror sessions.Config.ClaudeSessionsDir
	// deliberately, so the two read as one concept.
	//
	// It is NEVER derived from WorkDir inside this package.
	// sessions.DefaultClaudeSessionsDir maps a workdir into the real
	// $HOME/.claude/projects/<encoded>, so deriving it here would point every unit
	// test — whose WorkDir is a t.TempDir() — at the developer's actual home. The
	// directory only ever arrives through this field.
	ClaudeSessionsDir string

	// Args is the caller-supplied pass-through argv (e.g. --model <m>). streamsup
	// owns only the fixed stream-json prefix and the id flag; everything else is
	// the caller's, mirroring supervisor.buildClaudeArgs. New clones it.
	Args []string

	// Stdout receives the child's stdout. Optional; nil discards it (a plain
	// exec.Cmd with Stdout == nil sends the child's stdout to /dev/null, so an
	// unconsumed stream never blocks the child). #1088's turnevent parser is the
	// sink that plugs in here.
	Stdout io.Writer

	// ControlParser is the Parser in Stdout's writer path. It binds private
	// control-response correlation when Stdout wraps the parser, for example in a
	// live probe that also observes raw child output. Nil preserves the direct
	// *Parser inference used by the daemon. A non-nil value must be the exact parser
	// Stdout forwards every child byte to.
	ControlParser *Parser

	// Stderr receives the child's stderr. Optional; nil discards it.
	Stderr io.Writer

	// Env is appended to os.Environ() in the child process. Optional; tests use it
	// to thread the fake-child wiring, and production leaves it nil — a value that
	// varies per SPAWN cannot live on a construction-time field, which is why the
	// session identity #2169 puts on the child rides SessionIDEnvVar instead.
	//
	// A non-empty child environment makes the spawn set cmd.Env explicitly instead
	// of inheriting implicitly — the same set of variables either way, since an
	// exec.Cmd with a nil Env already inherits the parent's environment.
	Env []string

	// SessionIDEnvVar names an environment variable each spawn binds to THAT
	// spawn's live session id — the same id its argv carries as --session-id /
	// --resume, composed in beginSpawn from the one snapshot buildArgs reads, so the
	// environment and the argv can never name two different sessions. Empty (the
	// default) binds nothing and leaves the child environment to Env alone.
	//
	// The NAME crosses this seam and not the value, and that is the whole point
	// (#2169). The interactive daemon needs the LIVE id here: cfg.SessionID is the
	// construction-time seed, RestartFresh rotates r.sessionID and respawns, so a
	// value composed by the caller at construction would name the retired session
	// for the entire life of every successor child. The consumer is the pyry_files
	// MCP server claude FORKS, which inherits this environment and forwards the id
	// as the destination of a handed-over file; the daemon refuses an id it has
	// retired rather than misfiling, so a stale value fails closed and stays broken.
	//
	// A /clear rotation is deliberately NOT tracked: it re-keys the pool without
	// respawning, so the running child keeps the environment it was exec'd with
	// until its next spawn. That boundary is stated in #2169's plan under
	// ## Revisions; closing it means reaching a live process's environment, which
	// no operating system here permits.
	SessionIDEnvVar string

	// Logger is used for lifecycle diagnostics. Optional; nil falls back to
	// slog.Default().
	Logger *slog.Logger

	// BackoffInitial, BackoffMax, BackoffReset configure the restart ladder.
	// Zero falls back to the supervisor defaults (500ms / 30s / 60s).
	BackoffInitial time.Duration
	BackoffMax     time.Duration
	BackoffReset   time.Duration

	// OnChildExit is called once per COMPLETED SUPERVISION ITERATION: after the
	// spawn attempt finishes and before Run decides what to do next (shut down,
	// relaunch immediately, or back off). Optional — nil-checked at the fire site
	// and left nil by tests that omit it — but NON-NIL on every production
	// construction path since #1210: the sole tree-wide caller of New installs a
	// per-runner turn-busy clear here, so a conversation whose child dies mid-turn
	// stops being reported busy. Exported, unlike onSpawn, because that consumer
	// lives outside this package.
	//
	// The cardinality is per iteration, NOT per live child: it also fires when
	// the spawn failed during setup and no claude process ever launched
	// (spawnAndWait's started == false). Deliberate — no child existed, so no
	// turn of this runner's can be open, and the intended consumer's clear is
	// idempotent. A caller that needs "a real child died" cannot get it here.
	//
	// It fires on every exit path: a crash (which falls through to the backoff
	// ladder), a deliberate restart (which relaunches immediately), and a
	// shutdown. The shutdown case works because the call sits ABOVE Run's
	// post-spawn ctx.Err() return, which itself sits above the "claude exited"
	// log — a parent cancel fires the callback before Run returns.
	//
	// It runs synchronously on the Run goroutine with NO Runner lock held, so it
	// may call any Runner method (Restart, RestartFresh, Interrupt, Stdin,
	// State), but it must NOT block: the restart ladder is stalled until it
	// returns, delaying the respawn. Slow work belongs on a channel or a
	// goroutine. It must not panic either — there is no recover here (matching
	// onSpawn), so a panic takes the supervise loop down with it.
	//
	// It fires strictly AFTER the child has exited: spawnAndWait returns only
	// past cmd.Wait or a pre-launch error, never while claude is still running,
	// and Stdin() already reports no live child by then. It is NOT a drain
	// barrier, though — it carries no data out of the child, and bytes the dead
	// child already wrote may still be in flight in a downstream sink when it
	// fires. A consumer needing ordering against those events must get it from
	// that sink, not from this callback.
	OnChildExit func()

	// OnSessionRotate is called when RestartFresh ACCEPTS a rotation, with the id
	// it rotated onto. Optional — nil-checked at the fire site and left nil by
	// every construction path but one — and non-nil only on the interactive
	// daemon's, where newStreamRunnerFactory uses it to move the turn-event sink's
	// session tag off the id the runner was constructed with (#1133). Without it
	// that tag stays frozen while the pool rebinds the conversation to the new id,
	// and the drain's active-session gate drops every later event for that
	// conversation until the daemon restarts.
	//
	// Exported for OnChildExit's reason: the consumer lives outside this package.
	//
	// CARDINALITY IS PER ACCEPTED ROTATION, not per RestartFresh call and not per
	// spawn. RestartFresh's empty-id refusal returns ABOVE the fire site, so a
	// consumer's tag can never be emptied by a call the runner itself declined —
	// which matters because an empty tag matches no bound session and would black-
	// hole that conversation's stream for the life of the runner. A respawn that
	// merely re-uses the current id (Restart, or the backoff ladder) fires nothing:
	// this is the ROTATION signal, not a spawn signal.
	//
	// It fires strictly BEFORE the outgoing child is torn down and therefore before
	// the successor is spawned — above both the restart hint and the iteration
	// cancel. That ordering is the point rather than an implementation detail: fired
	// after the cancel, the Run loop could tear down and respawn concurrently, and
	// the successor's first events would carry the id the rotation just replaced,
	// which is the defect this seam exists to remove. The cost is the mirror window
	// — the outgoing child's residual stdout, parsed after this returns, is seen by
	// the consumer under the NEW id. For the sole consumer that is the same runner,
	// conversation and client, so it is a fidelity bound rather than a disclosure
	// one; see the plan's security review for the derivation.
	//
	// It runs synchronously on the CALLER's goroutine (whichever one called
	// RestartFresh — the daemon's new_session dispatch) with NO Runner lock held, so
	// it may call any Runner method. It must NOT block: the teardown of the outgoing
	// child is stalled until it returns. It must not panic either — there is no
	// recover here, matching OnChildExit and onSpawn.
	OnSessionRotate func(newID string)

	// RequestInitializeOnSpawn asks each spawned child, exactly once, to report
	// what the session knows about itself — the model list and the slash-command
	// list — by writing one initialize control_request onto its held-open stdin
	// (see RequestInitialize). Optional; false (the zero value) keeps a runner
	// byte-identical to pre-#1839 behaviour, which is what leaves every
	// construction site other than the interactive daemon's mapStreamsupConfig
	// untouched. Set it only there: the ask is that daemon's policy, not every
	// runner's behaviour.
	//
	// CARDINALITY IS PER SPAWN, and that is the whole of how "exactly once per
	// child" is enforced — there is no counter and no per-child bookkeeping, and
	// none is wanted: spawnAndWait runs once per child, so firing there is once per
	// child by construction, and the count does not grow with the turns that child
	// serves. The trap this rules out is the child's system/init line, which looks
	// like the per-child signal and is not — emitModelAnnounced's doc measures it
	// firing once per TURN, so a trigger there would ask on every turn while
	// staying green in any single-turn test.
	//
	// Unlike OnChildExit it fires only when a child ACTUALLY LAUNCHED: the call
	// sits below cmd.Start, so a spawn-setup failure never reaches it. That is the
	// opposite cardinality to OnChildExit's per-supervision-iteration one, and the
	// two fields sit next to each other, so the contrast is stated rather than left
	// to be inferred.
	//
	// The ask is BEST-EFFORT AND ITS ERROR IS ABSORBED — one Debug record, then the
	// spawn continues. It never becomes spawnAndWait's waitErr, so it cannot enter
	// the backoff ladder, restart a child or fail a spawn.
	//
	// It reads Stdin(), NOT the rotation-gated turnTarget, so an ask is not refused
	// while a new_session rotation is armed and one can land on a child
	// RestartFresh is about to kill. Deliberate rather than tolerated: that ask
	// commits nothing and no queue head rides on it, whereas gating it would leave
	// a child whose rotation was ABORTED (BeginRotation's disarm path) permanently
	// unasked — the state the per-replacement ask exists to prevent.
	RequestInitializeOnSpawn bool

	// MCPStatusConfigPath is the daemon-owned MCP config whose exact presence on
	// one child spawn, together with --strict-mcp-config, permits automatic MCP
	// status collection. Empty makes every child ineligible. The path is compared
	// only with that spawn's completed argv; changing Args for a later spawn does
	// not change the policy already installed for the running child.
	MCPStatusConfigPath string

	// SpawnPermissionMode is the session's stored permission posture, written to
	// every spawned child as a set_permission_mode control request before any user
	// turn can reach it (#2064). Optional; the zero value writes nothing and arms
	// nothing, which is what leaves every construction site other than the
	// interactive daemon's mapStreamsupConfig byte-identical.
	//
	// It is the CONSTRUCTION-TIME seed only. The live value is r.spawnMode, which
	// SetSpawnPermissionMode replaces when the session's stored posture changes —
	// Pool.UpdateSettings rebuilds no runner, so a value read from this field at
	// spawn time would go stale and could assert a posture the operator has already
	// changed. Same relationship SessionID has with r.sessionID.
	//
	// bypassPermissions is REFUSED here, and since #2066 that is a SUBTRACTION rather
	// than the same non-membership WritePermissionMode applies: that ticket admitted
	// the escalation to the writer's allow-list so a LIVE child can be escalated in
	// band, and scoped the widening away from this path with
	// permissionModeSpawnWritable. So a bypass session is still sent nothing at spawn
	// and its turns still flow exactly as they do today — a gate no write can ever
	// release is a bricked session, not a fail-closed one — while re-granting bypass
	// now reaches the running child through SetPermissionMode instead of a respawn.
	// The exclusion costs nothing: since #2065 the launch argv already asserts the
	// escalation, so a bypass child is in the right posture before the write would
	// have run, and nothing has measured claude answering an escalation as the FIRST
	// control request on a fresh stream.
	//
	// THAT REFUSAL IS NOT THE ONLY ONE, because this field cannot see every way a child
	// ends up in bypass. The operator's bootstrap pass-through claude args put
	// --dangerously-skip-permissions in the argv without touching SessionSettings, so
	// this field reads default at a child launched in bypass; spawnAndWait consults
	// Config.OperatorBypass for exactly that case and writes nothing. Read that site
	// before treating this field as the whole decision — a live-claude gate, not a
	// review, found the gap.
	//
	// "Sent nothing" is NOT "gate untouched", and the difference was a defect: the gate
	// outlives the child, so a spawn that writes nothing must still arm the OPEN state
	// or it inherits its predecessor's id. See the arm site in spawnAndWait.
	//
	// Setting it REQUIRES PostureGate; New refuses the pairing otherwise. A posture
	// written with nothing correlating its ack is a line the daemon believes in and
	// has not confirmed, which is the shape #2065 cannot tolerate.
	SpawnPermissionMode string

	// OperatorBypass reports that the escalation on this runner's spawn argv came
	// from the OPERATOR's pass-through claude args rather than from the daemon's own
	// settings composition (#2065). It is sessions.RunnerConfig.OperatorBypass
	// carried across the seam, derived there from the settings-free spawnBase.
	// Optional; the zero value is "the daemon composed whatever is on this argv",
	// which is what leaves every construction site outside the interactive daemon
	// byte-identical.
	//
	// TRUE SUPPRESSES THE SPAWN-TIME POSTURE WRITE. It is the second half of that
	// decision, and it REPLACES the argv read that used to make it: until #2065 this
	// runner asked whether the spawn's own args named the escalation, because that
	// answered the same question. It stopped answering it when
	// sessions.claudeSettingsArgs began appending the flag to every argv — a
	// predicate reading the argv now answers "operator bypass" for every session, so
	// no child is ever sent its stored posture and every child stays in the bypass it
	// launched with. Read spawnAndWait's arm site for the whole derivation.
	//
	// It is a Config field where the argv read was per-spawn, and that is sound
	// rather than a regression: the value it replaced was a property of the assembled
	// argv, which Restart(newArgs) can change, whereas provenance is a property of
	// the session's immutable spawnBase, which nothing can. SetSpawnArgs and Restart
	// install an argv VERBATIM, so a future caller composing one from something other
	// than sessions.Session.spawnArgs owns keeping this bit in step — though both
	// mis-pairings fail safe: a flag with the bit false downgrades a child that IS in
	// bypass, and the bit true with no flag writes nothing at a child that is not.
	OperatorBypass bool

	// PostureGate is the ack signal the spawn-time posture write is held against
	// (#2064): armed with the write's locally-minted request_id before the child's
	// stdin is published, released only by that id's success control_response, and
	// consulted by every WriteUserTurn in between. Optional; nil gates nothing.
	//
	// It is minted by the PARSER — (*Parser).PostureGate — because the parser is
	// built before streamsup.New (newStreamRunnerFactory installs it as Config.Stdout)
	// and the release side is the parser's. Minting it there is what makes it
	// impossible to bind the two halves to different gates, which is
	// newSessionParser's argument for minting a parser and its holds together.
	PostureGate *PostureGate
	// contains filtered or unexported fields
}

Config configures a Runner. Required fields are validated in New; zero values for optional fields fall through to the documented defaults.

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser turns the child's stdout stream-json line stream into neutral turnevent.Event values. It is an io.Writer wired as streamsup Config.Stdout; each Write consumes every complete '\n'-delimited line and emits zero-or-more events per line to the sink, in stream order. A `result` line ends the turn (→ TurnEnd); no transcript file is opened, watched, or resolved (AC4) — the only input is the Write bytes.

Turn-stateless in everything that describes claude's output. The parser holds no turn counter, no awaiting flag and no transcript.

AMENDED 2026-08-09 (#1385): it holds exactly one piece of cross-line state, and the absolute phrasing this paragraph used to carry ("no per-session accumulator") is now false. thinkingSinceEmit is a token COUNTER — not a memory of anything claude said — and it exists because the thinking_tokens mapping is rate-bounded and so cannot be a function of one line alone. Zero cross-turn bleed stays structural, but by the RESET rather than by the absence of state: consumeLine's `result` arm zeroes it unconditionally, both result subtypes go through that arm, and it is the only cross-line state besides the partial-line buffer. No other line type can create, reset, or leak state across a boundary.

AMENDED 2026-09-08 (#2224): there are TWO pieces of cross-line state, and the clause the paragraph above rested on — "remembers nothing any line SAID: every mapping is a pure function of the line it reads" — is now false rather than merely narrower, so it has been struck rather than qualified. assistantErrorCategory holds up to 256 bytes of claude's own text, read off an `assistant` line and published on the `result` line's turn_end. #1385's defence ("a COUNTER, not a memory of anything claude said") does not stretch to cover it and is not asked to.

The RESET is unchanged and still the whole of the cross-turn argument: the same `result` arm clears both, unconditionally, before the emit, and there is still no second reset point. A category read during a turn cannot reach the next turn's turn_end through any completed boundary.

THE RESIDUAL IS WHERE THE TWO FIELDS DIVERGE, and the counter's argument must not be inherited here by resemblance. A child that dies WITHOUT a `result` line leaves a residual on a long-lived parser (cmd/pyry builds one per session, not per turn, and streamsup rebinds the same one across respawns). For the counter that costs at most one event arriving early, bounded by the invariant at its field. For a remembered CATEGORY it would mean reporting one turn's rate_limit on a later turn's turn_end — a wrong claim rather than an early event, and nothing about the field bounds it.

WHAT ANSWERS IT IS THE WRITE, NOT A SECOND RESET. Every `assistant` line writes the field, an absent `error` key writing empty, so the residual survives only until the next assistant line — inside the next turn, and long before its boundary. That is last-writer-wins at the one write site rather than a second boundary to keep correct, which is the property having ONE boundary buys.

The narrowing is not an elimination, and the remainder is accepted rather than unnoticed: a turn that emits NO assistant line at all before its `result` still reports the dead turn's category. TestParser_AssistantErrorCategory_ResidualSurvivesAResultlessTurn pins exactly that, so the day someone adds a child-restart clear, the test that reddens is the notice that this decision moved. The latch's own cost — an error-bearing line followed by a clean one INSIDE one turn drops the category — is the fail-closed direction: a dropped category is precisely today's behaviour, while a stale one is a false statement about the operator's account.

AMENDED 2026-09-08 (#2227): there are THREE pieces of cross-line state. compacting is the open/closed edge of a compaction banner, and it takes NEITHER of the two arguments above by inheritance. It is not a counter, so #1385's defence does not reach it; and #2224's answer — the write launders the residual — has no analogue, because no line writes this field on the way past.

WHAT IS ACTUALLY NEW IS THAT THE RESET BECAME OBSERVABLE. A client MIRRORS this field: the desktop lights a banner on the rising edge and clears it on the falling one. The two fields above could be reset in silence because nothing outside the parser held a copy — for the counter nothing at all, for the category the same emit that published it. Clearing this one in silence would leave the parser and the banner disagreeing with no later line to reconcile them, so the `result` arm emits a falling edge before clearing. THE SINGLE RESET POINT IS UNCHANGED and remains the whole of the cross-turn argument; what moved is that the reset now says so on the wire. Its residual is bounded by that same reset and is argued at the field.

AMENDED 2026-09-08 (#2234): there are FOUR pieces of cross-line state. deniedThisTurn is the set of tool_use_ids that already produced a denial marker from their own line this turn, and it takes none of the three arguments above by inheritance. It is not a counter; no line writes it on the way past, so #2224's laundering has no analogue; and nothing outside the parser mirrors it, so #2227's published reset is not owed.

WHAT IS NEW IS THE DIRECTION ITS RESIDUAL FAILS IN, and that is the one thing this entry exists to say. Every field above fails by SPEAKING — an event early, a wrong category, a banner outliving its cause. A stale id here fails by SILENCE: it suppresses a later turn's genuine marker, which is the defect #2234 fixes, restored in the one case nobody would look. Three things bound it and no second reset is minted. The `result` arm clears the set unconditionally, so only a child that dies without a `result` leaves one at all. claude's tool_use_ids are per-call unique, so a later turn colliding with a stale id is not a shape claude produces. And a collision could only suppress a marker for an id the client has ALREADY seen a denial for, so the loss is a second report of one call, never the only report of one. THE SINGLE RESET POINT IS UNCHANGED and remains the whole of the cross-turn argument.

AMENDED 2026-09-10 (#2250): there are SIX pieces of cross-line state, and this is the entry the chain above exists to make possible. The count jumps from FOUR because #2246's taskProgressToolUses added a fifth field and no entry: it is cleared at the one reset like its neighbours, publishes nothing when it is, and took every argument above by inheritance, so it had nothing to add here. rateLimitNonBenign is the opposite case in the one dimension that matters.

IT IS THE FIRST PIECE OF CROSS-LINE STATE THE SINGLE RESET POINT DOES NOT CLEAR, and that is a departure from the paragraph every entry above rests on rather than an exemption from it. The reason is arithmetic, not preference: claude emits rate_limit_event ONCE PER RUN, so the two readings the field exists to relate are separated by at least one `result` line and usually by a whole child. Cleared at the boundary, the latch would be gone before the reading that would have used it ever arrived — the field would exist and never once fire. So the argument that bounds its residual cannot be the reset, and is not: it is the NEXT READING, which overwrites the latch either way. A child that dies after a non-benign reading costs one extra benign frame describing a window claude has just reported, which is compacting's fail-safe direction reached without a second reset path.

#2227's published-reset question does arise and is answered differently. A client mirrors this state too — it is a banner, exactly as compacting's is — but the clear is not a silent state change needing a frame to announce it: the clearing FRAME IS the state change, carrying claude's own benign reading. There is nothing to publish separately because nothing happens separately.

AMENDED 2026-09-10 (#2263): there are SEVEN pieces of cross-line state. apiRetryOpen records that at least one system/api_retry line has published an active update. It resembles compacting because a client mirrors the boolean and therefore needs an observable clear, but its boundary is wider: the next successfully decoded assistant, user, OR result line closes it before that line's events. Claude emits no explicit retry-end line, and the committed capture reaches assistant before result, so waiting for the one result reset would leave the retry state lit while assistant output had already resumed.

Repeated active lines are never suppressed. Each carries a later attempt counter, so the latch guards only the falling edge. A child that dies while it is set leaves both parser and client in the same active state; the next assistant/user/result after respawn publishes the clear before its own event. That residual is bounded by the next content line rather than by a child-lifecycle reset, preserving one observable answer for the client without coupling parser state to process teardown.

AMENDED 2026-09-11 (#2270): stream-event attribution is one composite eighth piece of cross-line state. A message_start replaces its message id and open-block fields, content-block events advance the open block, and the existing result arm clears the composite. It retains only one id, one block discriminator and scalar routing state; delta text is emitted directly and is never accumulated here.

Single-writer invariant: os/exec drives a non-*os.File Config.Stdout through exactly one internal goroutine (io.Copy of the child's stdout pipe into this writer), so Write — hence buf and the sink calls — is only ever invoked serially from that one goroutine. There is no second reader of parser state, so no mutex is needed. (Contrast streamrunner's streamParser, which locks because its watchdog goroutine reads its state.) If a future slice adds a concurrent reader, it adds the guard then. One Parser serves every child of a runner, and the one other toucher of buf, dropPartialLine, runs on the Run goroutine only after cmd.Wait has returned: Wait joins the stdout copy goroutine, even past WaitDelay, so the dead child's last Write happens-before the drop and the drop happens-before the next child's first Write (#1503).

func NewParser

func NewParser(sink func(turnevent.Event), logger *slog.Logger) *Parser

NewParser returns a Parser that emits events to sink. sink is called serially, in stream order, on the os/exec forwarder goroutine; the consumer owns any synchronization it needs beyond that (the round-trip test's sink pushes to a channel; a real consumer forwards to the relay). logger is used for content-free Debug diagnostics only; nil falls back to slog.Default.

func (*Parser) PostureGate

func (p *Parser) PostureGate() *PostureGate

PostureGate returns the ack signal this parser releases when claude confirms a spawn-time permission-mode write (#2064). The value goes onto streamsup.Config, so the runner arming the gate and the parser releasing it are the same object by construction. Never nil for a parser built by NewParser.

func (*Parser) SetCanUseToolHandler

func (p *Parser) SetCanUseToolHandler(h func(CanUseToolRequest))

SetCanUseToolHandler installs h as the destination for claude's inbound can_use_tool permission asks (#2282). With none installed the parser consumes such a line and drops it silently.

A SETTER RATHER THAN A CONSTRUCTOR PARAMETER because NewParser's signature has nine call sites and none of them answers an ask; the alternative was widening all nine to pass nil. PostureGate's doc makes the same trade in the other direction, for a value that had to exist ahead of both halves.

CALL IT BEFORE THE PARSER IS HANDED TO A RUNNER, and that ordering is a CONTRACT, not advice. h is read on the os/exec forwarder goroutine, so installing one after the parser has started consuming stdout is a data race with no lock to save it. The composition root builds the parser, installs its holds, and only then wires it as Config.Stdout — the same window PostureGate() is read in.

h IS CALLED SYNCHRONOUSLY, in stream order, on that forwarder goroutine — the same contract NewParser states for sink. It must not block: a handler that waits stalls every later line from the child, exactly as a blocking sink does. It must not call back into this parser. Answering the ask from inside it is safe, because the answer travels on the child's STDIN, a different fd from the stdout being drained here, so no write can deadlock against this reader.

h receives untrusted, claude-authored data — see CanUseToolRequest, which says what that means for each field.

func (*Parser) Write

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

Write appends b to the line buffer, consumes every complete '\n'-delimited line (emitting events to the sink), and keeps the partial remainder for the next Write. It always reports (len(b), nil): the parser is the terminal stdout sink, not a tee, so it fully consumes what it is handed and has no downstream short-write to propagate.

type Phase

type Phase string

Phase describes the runner's current lifecycle state. The values mirror supervisor.Phase string-for-string so the cmd/pyry adapter maps one to the other by a plain string conversion.

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 PostureGate

type PostureGate struct {
	// contains filtered or unexported fields
}

PostureGate holds a session's user turns until the child it is armed against has CONFIRMED the permission posture the daemon wrote to it (#2064). It is the first shipped control-ack reader in this package. Writers still return after their write; the parser now also retains an exact echoed mode as separate informational state.

Its state is one string and one bool. armedID == "" is the OPEN state, so a gate nobody armed is open and an ungated runner behaves exactly as it did before this type existed. arm closes it against exactly one locally-minted request_id, release opens it only on an exact match, and ready reports open.

The bool answers "and what happened to the request" for the one closed state that is TERMINAL rather than pending: refuse records that claude answered the armed id with a non-success subtype. It changes no decision — the gate is closed either way — it is what lets the turn path tell an operator "claude refused this posture" instead of repeating "not confirmed yet" forever. Every state change clears it, so the verdict never outlives the request it answers.

A NAK'd gate is not a dead session: retarget points a CLOSED gate at the id of a later in-band posture write, so an operator's mode change is the recovery, and the next spawn arms a fresh id regardless. What no path does is OPEN the gate on a NAK — that would be fail-open, and under #2065 (every child launched in bypass) it would admit turns to a child whose downgrade claude has just refused.

A fresh arm OVERWRITES the previous id rather than clearing a separate flag, and that is not a compression — it is what makes "a replacement child is never released by its predecessor's ack" hold with no bookkeeping. cmd/pyry builds ONE parser per session, not per child, so a dead child's buffered stdout can still be parsed after its successor has armed; the mismatched id refuses it.

WHAT IT PROVES, AND WHAT IT DOES NOT. A released gate means "claude acked the request this daemon minted". It does NOT mean "claude enforces that posture" — an echoed posture is the child's claim about itself, the scope boundary interactive_stream_inband_bypass_revoke_test.go already draws for the ack it reads. A child that lies about its posture defeats this gate, and is also a child that could simply ignore the mode; the gate buys protection against BENIGN failure — an unsupported mode, a dropped line, a child slow to come up — not against a hostile one. Read that limit before treating a released gate as an enforcement guarantee.

Every method is NIL-RECEIVER-SAFE, following sessionModelHold.ModelList's precedent, so neither the runner's turn path nor the parser's ack path needs a nil branch. The mutex is a LEAF: it is never held across a log call, a write, or another lock, and no path in this package holds it together with Runner.mu or Runner.restartMu.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner supervises the claude child lifecycle. Construct with New; drive with Run. The held-open stdin handle is exposed via Stdin.

func New

func New(cfg Config) (*Runner, error)

New validates the required fields, applies defaults, resolves WorkDir, and clones Args. It surfaces a not-found error when ClaudeBin is not on PATH and a wrapped fs.ErrNotExist when WorkDir does not exist (both fail fast).

func (*Runner) AdoptSessionID

func (r *Runner) AdoptSessionID(newID string)

AdoptSessionID installs newID as the live session id the runner's NEXT spawn resumes, and does nothing else (#2136). It exists for claude's OWN announced conversation reset, which the daemon follows rather than orders: the pool registry, the sink tag and the drain's gate all move onto the announced id, and without this the runner keeps the pre-reset one and its next crash-respawn --resumes the conversation the operator just cleared.

It is SetSpawnArgs' mirror image. That method takes restartMu exactly once and writes one field, and its doc names the three it is careful not to touch; this one takes restartMu exactly once and writes the first of those three, sessionID, touching neither rotatePending nor freshSeq nor iterCancel, and sending no restartCh hint. So beginSpawn's #1481 single-acquisition property survives by construction here for the same reason it does there, and the state beginSpawn's doc forbids — defined over the fields this does not write — stays unreachable. Against a racing beginSpawn it serialises wholly before (that spawn resumes the announced id) or wholly after (that spawn keeps the previous id and the next one takes the announced one); both are correct, because the contract is the NEXT spawn and it promises nothing about one already in flight.

What it deliberately is NOT is RestartFresh with the teardown removed. That method rotates to an id the DAEMON minted and re-establishes first-run semantics, so its trio arms a fresh transcript and its cancel makes the successor child bind to it. Here claude has ALREADY reset in-process: the transcript exists, the child running now is the one writing to it, and there is nothing to re-establish and nothing to relaunch. Arming rotatePending would make the next spawn emit --session-id against a live transcript, which claude refuses (ADR 032); bumping freshSeq would authorise a spawn through the rotation gate that succeeded no rotation.

An empty newID is refused at Warn and nothing is written — the same last-resort guard on New's non-empty contract RestartFresh carries, and above the section for the same reason. The provenance argument is NOT RestartFresh's, though the conclusion matches: that method's callers hand it a daemon-minted id, whereas this one's caller hands it a value claude wrote. What makes the guard sufficient rather than a validator is the boundary upstream — the parser's emitConversationReset gates on transcript.ValidStem, an anchored full match over a canonical lowercase UUID stem, so the id can carry no separator, no traversal, no leading dash and no unbounded length by the time it reaches here. Nothing in this package re-derives that shape, and nothing here joins a path with it: the spawn's --session-id / --resume choice stays useCreateForm's, whose StatByID probe runs ValidStem itself before any join.

Like Restart and SetSpawnArgs it drives only Runner-internal state and takes no Pool lock, so the sessions layer can call it after releasing Pool.mu with no lock-order concern. restartMu stays a leaf: no call-out, no second lock, no I/O under the section. Non-blocking and safe from any goroutine.

func (*Runner) BeginRotation

func (r *Runner) BeginRotation() (abort func())

BeginRotation arms the rotation gate: from this call until the next child binds its stdin, every WriteUserTurn refuses with ErrNoLiveChild instead of writing into the child the accompanying RestartFresh is about to kill. It is called strictly BEFORE the pool-side rotate() that re-keys the binding and fires the session_transition{clear}, so no turn accepted on the strength of that clear can reach the outgoing child (#1330, AC1).

It returns the DISARM for the caller's error path — startFreshRunner runs it when rotate() fails, because a gate left armed by a rotation that never happened would refuse every turn until the next respawn, a wedge the rotation never earned. The disarm is LIVE ONLY IF NO LATER ARM HAS LANDED (the rotateGen stamp), mirroring openForDelivery's undo in cmd/pyry: the only way to obtain a disarm is to have placed the matching arm, and a second arm retires the first one's. See rotateGen for the two-frame sequence that needs it.

The arm also captures the RELEASE-side threshold (#1482): the freshSeq value standing when it is placed, against which setStdin measures each binding child. That is why this method takes TWO leaf mutexes where it once took one. They are taken SEQUENTIALLY AND NEVER NESTED — no path in this package holds two locks at once, and that is what keeps the ordering safe. Should nesting ever become unavoidable, the order is restartMu → mu, the sequence established here; a mu → restartMu nesting is the inversion, and recognisable as one.

The restartMu read comes FIRST, and the mu section then publishes rotating, rotateGen and armFreshSeq together. Arming first and stamping second would leave the gate observably armed beside a retired arm's threshold, which a bind landing in between would compare against — a disarm-by-stale-comparison bug.

Residual window, deliberately left open: between the restartMu read and the mu acquisition a DIFFERENT frame's RestartFresh could land and a spawn take its snapshot, and that spawn's later bind would clear the arm being placed here. Closing it needs both leaf mutexes held at once, which the two-mutex charter forbids (see mu and restartMu). It is unreachable from a single new_session frame — startFreshRunner calls BeginRotation and RestartFresh in program order on one goroutine — and needs two concurrent frames to interleave inside a few instructions. The two-frame gap in its documented shape (frame 1's respawn still pending when frame 2 arms) IS closed: frame 2's arm reads the already-bumped counter, so frame 1's successor snapshot is not strictly greater.

Like RestartFresh it drives only Runner-internal state — leaf mutexes, no channel, no call-out — so the sessions layer can call it with no Pool lock held, which startFreshRunner does. Safe from any goroutine.

func (*Runner) BeginTeardown added in v0.19.0

func (r *Runner) BeginTeardown()

BeginTeardown arms the teardown gate: from this call until the next child binds its stdin, every WriteUserTurn refuses with ErrNoLiveChild instead of writing into the child the accompanying kill is about to take down (#1513). Its three callers are in internal/sessions — both eviction arms of Session.runActive and Pool.UpdateSettings' restart branch — and each places it strictly BEFORE the cancel or Restart it pairs with, and before anything that publishes the teardown to clients, which is #1330's placement rule applied to a deliberate kill.

It captures the RELEASE-side threshold in the same acquisition: the childGeneration value standing when the arm is placed, against which setStdin measures each binding child. Because setStdin bumps that counter on every bind, ANY successor child ends this window — including the Restart-driven and crash-off-the-backoff-ladder binds whose freshSeq snapshot reads EQUAL to armFreshSeq and which therefore leave a rotation arm standing (#1482). That difference is why this is a second gate rather than a third caller of BeginRotation: these teardowns END IN exactly the respawns a rotation must survive, so arming rotating here would wedge the session until some later RestartFresh landed.

Unlike BeginRotation it takes ONE leaf mutex, not two: the threshold it needs lives under mu beside the flag, so there is no restartMu read to sequence and the residual window BeginRotation documents between its two acquisitions does not exist here.

It returns NO disarm, deliberately. BeginRotation needs one because its gate can outlive a rotation that never happened, and nothing else would bring it down; this gate is self-clearing at the next bind of any child, so a stray arm costs at most the turns inside one respawn. Both callers are unconditional in any case — cancelSup always runs on the arms that reach it, and Restart returns nothing and cannot fail.

Like BeginRotation it drives only Runner-internal state — one leaf mutex, no channel, no log call, no call-out — so the sessions layer calls it with no Pool lock held and it cannot delay the kill that follows it. Safe from any goroutine.

func (*Runner) ClaudeSessionsDir added in v0.19.0

func (r *Runner) ClaudeSessionsDir() string

ClaudeSessionsDir reports the folder the live spawn inputs name — where claude writes this session's <id>.jsonl, and what the next spawn's create/resume probe will read. "" means no probe is configured.

It exists so cmd/pyry's transcript reader can answer for the directory the session is CURRENTLY spawning in rather than the one it was constructed with: since #1475 a rotation can move that, and a stored copy would report the pre-move folder — the #2423 reading ("Context: 0%") re-introduced for exactly the conversations that moved.

It takes restartMu alone, never mu, so it is safe to call from any goroutine and adds no edge to the daemon's lock order — the treatment liveSessionID already gets for the same reason.

func (*Runner) ConfirmedPermissionMode added in v0.20.0

func (r *Runner) ConfirmedPermissionMode() (string, bool)

ConfirmedPermissionMode reports the last permission mode claude confirmed for this runner's exact current child. The bool is false before a non-empty system/init report, after child exit, and when the runner is not wired to its concrete Parser. It never falls back to spawn intent, argv, or stored settings, and performs no control write or posture-gate transition.

func (*Runner) Interrupt

func (r *Runner) Interrupt() error

Interrupt writes a single interrupt control_request line to the live child's stdin, ending the running turn (claude acks and emits a result with subtype error_during_execution, which the parser maps to a cancelled TurnEnd). The request_id is locally minted (not caller-supplied). When no child is live Stdin() is nil, so Interrupt returns the retryable ErrNoLiveChild without writing and without panicking — the safe no-op refusal.

Interrupt is a concrete method on *Runner, deliberately NOT on sessions.Runner (#1077's placement rule: its dispatch lives in cmd/pyry, which can assert — unlike SetSpawnArgs (#1580), RevokeBypass (#1604) and SetPermissionMode (#2042), whose consumer is inside internal/sessions and which are ON the interface for exactly that reason): #1121's interrupt routing reaches it via its own narrow interface or a type assertion. It mirrors how *supervisor.Supervisor encapsulates SendEsc (#726) without that method being on the interface. Safe from any goroutine.

func (*Runner) QueryAppliedSettings added in v0.20.0

func (r *Runner) QueryAppliedSettings(ctx context.Context) (AppliedSettings, bool)

QueryAppliedSettings asks the exact live child for the settings Claude applied and waits for the response carrying this request's locally minted id. It returns only bounded model and nullable effort copies; every refusal or unavailable outcome is the false arm.

A caller deadline is mandatory. Child exit and replacement retire the query, but a live child can stay silent indefinitely; refusing an unbounded context prevents one such child from retaining a waiter forever. Cancellation is honored before and during the write, while waiting, and after a raced result. Ending the context during a blocked write retires and closes only the captured child generation, which is the interrupt available for an os.Pipe write and keeps a successor untouched.

The ordering matches QueryContextUsage: snapshot the binding under Runner.mu, register outside that leaf lock, then recheck childGeneration before writing.

func (*Runner) QueryContextUsage added in v0.18.0

func (r *Runner) QueryContextUsage(ctx context.Context, detail string) (turnevent.ContextUsage, bool)

QueryContextUsage asks the live child for a context breakdown at detail and waits for the response carrying that request's own id, so a caller answering an inbound request can correlate the reading to it. The parser claims that response before the shared sink, so a reading returned here is NOT also republished as an unsolicited frame. RequestContextUsage remains the fire-and-forget peer for the post-turn cadence.

ONE BOOL COLLAPSES EVERY NOT-ANSWERED OUTCOME — an unsupported detail, no live child, a rotation in flight, a child replaced before answering, a failed write, a caller whose context ended, and an unusable payload alike. That is QueryMCPStatus's contract and actuateMCP's stated decision, and this slice wires no caller above it that could consume a richer one. A caller needing the vocabulary itself learns it from RequestContextUsage's ErrUnsupportedContextUsageDetail.

THE RETURNED READING CARRIES CHILD-AUTHORED STRINGS, memory-file paths from the user's own filesystem among them. It is bounded but not sanitised for diagnostics, so a caller must not log it wholesale. Nothing on this path logs, and no diagnostic may be added here: the values in scope are the detail, the minted id and the writer's error.

mcpStatusEligible is deliberately NOT part of the gate, unlike QueryMCPStatus's: it reports whether argv confines the child to the daemon's one MCP config, which has no bearing on whether a context reading can be asked for. A child that is live and not rotating is askable. rotating and childGeneration are the parts that do carry over.

THE CALLER'S CONTEXT IS THE ONLY BOUND ON THE WAIT when the child stays alive and simply never answers — takeStdin and beginMCPStatusChild cover death and replacement, silence they cannot — so pass a deadline rather than context.Background().

The order below is QueryMCPStatus's, for the reasons actuateMCP records: snapshot the binding under the leaf mutex, register OUTSIDE it, then re-check the generation.

func (*Runner) QueryMCPStatus added in v0.17.0

func (r *Runner) QueryMCPStatus(ctx context.Context) (turnevent.MCPStatus, bool)

QueryMCPStatus asks the exact eligible live child for its current MCP server states and waits for the response carrying that request's id. The parser claims that response before the shared sink; false collapses every unavailable outcome.

func (*Runner) ReconnectMCPServer added in v0.17.0

func (r *Runner) ReconnectMCPServer(ctx context.Context, serverName string) bool

ReconnectMCPServer asks the exact eligible live child to reconnect one MCP server and reports whether that child accepted it. See actuateMCP for the contract both actuations share — notably that the caller's context is the only bound on the wait.

Server membership and authorization belong to the caller boundary, as WriteMCPReconnect's own doc block states; this method adds neither. No wire surface reaches it: it is on the concrete runner and not on sessions.Runner, so nothing outside the daemon can actuate a configuration change until #2419 lands a forwarder together with its gate.

func (*Runner) RequestContextUsage

func (r *Runner) RequestContextUsage(detail string) error

RequestContextUsage asks the live child for its summary or full context breakdown. The detail vocabulary is checked before child lookup and ID minting; WriteContextUsage repeats the same boundary for direct callers. The request ID comes from the runner-wide control sequence, and this method does not decode the response. When Stdout is the runner's Parser, the id is registered before the write and removed again on a write failure; only that parser can consume the successful registration.

func (*Runner) RequestInitialize

func (r *Runner) RequestInitialize() error

RequestInitialize writes a single initialize control_request line to the live child's stdin, asking it to report what the session knows about itself — the model list (identifiers, display names, supported reasoning-effort levels) and the slash-command list — without a respawn. The request_id is locally minted from the same counter Interrupt and RevokeBypass draw on. When no child is live Stdin() is nil, so RequestInitialize returns the retryable ErrNoLiveChild without writing and without panicking.

It writes the line and stops: the control_response is NOT read here, exactly as RevokeBypass writes without reading its ack. The minted id is deliberately not returned either — the reader slice that correlates the ack is the first thing that needs it, and a return value with no reader is a seam with nothing on the far side of it.

The name is RequestInitialize, not Initialize: on a type that already has New, a bare Initialize() reads as "initialize the runner", which is the opposite of what it does — it asks the CHILD to initialize.

Like Interrupt and unlike RevokeBypass it is NOT on sessions.Runner, and the placement rule is the same one in both directions: the interface carries a method when its consumer sits inside internal/sessions, where a structural type assertion would fail open (RevokeBypass's does — Pool.UpdateSettings). This subtype has no consumer at all yet — the trigger lands with the publishing slice — so an interface method here would be a seam with nothing on the far side of it, and it would pull every fake runner under internal/sessions into the diff. Stdin() releases r.mu before returning, so the potentially-blocking write never holds it. Safe from any goroutine.

func (*Runner) RequestMCPStatus

func (r *Runner) RequestMCPStatus() error

RequestMCPStatus asks the live child for its current MCP server states. The parser's per-child policy is the sole automatic caller; direct writers remain available through WriteMCPStatus. The request id shares the runner-wide control sequence with every other subtype.

func (*Runner) Restart

func (r *Runner) Restart(args []string)

Restart swaps the live spawn base argv and, if a child is currently running, forces it to exit so the Run loop relaunches with the new args (resuming via --resume, since firstRun is already false after the first spawn). When no child is running it only swaps the args — they take effect on the next spawn. Non-blocking, fire-and-forget: the forever-retry Run loop guarantees the relaunch. Safe from any goroutine. Mirrors supervisor.Restart.

It drives only Runner-internal state (restartMu, a ctx cancel, a buffered channel); it never touches Pool.mu or Session.lcMu, so the sessions layer can call it after releasing Pool.mu with no lock-order concern.

The restartCh hint is always sent (non-blocking): a restart during a run makes the post-spawn drain skip backoff, and a restart during backoff (no live child to cancel) breaks the backoff wait. Coalescing is correct — two rapid restarts overwrite args with the newest value and collapse to the single buffered token, forcing one relaunch with the latest args.

The argv install runs through setArgsLocked INSIDE this one section, not by calling SetSpawnArgs: the exported swap-only method takes restartMu itself, so calling it here would split Restart into two acquisitions and reopen the #1481 window beginSpawn's doc closes. See SetSpawnArgs for the swap without the kill.

func (*Runner) RestartFresh

func (r *Runner) RestartFresh(newID string)

RestartFresh rotates the runner's persistent session id to newID and forces the next spawn to use --session-id <newID> (a fresh transcript, no fork), re-establishing first-run semantics. A subsequent crash-respawn then --resumes newID — never the pre-rotation id. If a child is live it is cancelled so Run relaunches immediately (skipping backoff, exactly like Restart); with no live child the rotation takes effect on the next spawn. Non-blocking, fire-and-forget, safe from any goroutine.

An empty newID is a no-op (logged at Warn): the runner never emits --session-id "". This is a deterministic last-resort guard upholding New's non-empty contract — the validating boundary is the pool/routing layer (#1125), per the "caller-supplied id validation at the primitive boundary" convention. The early return sits above the section below, so a no-op does NOT bump freshSeq: the rotation gate's release authorisation counts rotations that landed, and no production path pairs an arm with an empty-id call (startFreshRunner passes only rotate()'s success value, and RotateForNewSession returns ("", err) on every failure). If a pool bug ever minted an empty id the arm would outlive it until the next rotation — the conservative side, since the alternative authorises a spawn that succeeded no rotation at all.

Unlike Restart it leaves r.args untouched: new_session rotates the id, not the model/flags — args stay owned by Restart/UpdateSettings. Like Restart it drives only Runner-internal state (restartMu, a ctx cancel, restartCh) and never a Pool lock, so the sessions layer can call it after releasing Pool.mu.

func (*Runner) RevokeBypass

func (r *Runner) RevokeBypass() error

RevokeBypass drops the live child's bypass posture by asking for the default mode. It is SetPermissionMode's named revoke shorthand, kept because it has a production caller — Pool.deliverSettingsInBand — whose delivered bytes must not change while the mode-carrying method is introduced beside it. #2043 rewrites that caller to send an operator-chosen mode, which is the slice where this method loses its last caller and can go: a method is deleted alongside the consumer that held it, not in the slice whose contract is that the consumer is untouched.

It cannot name anything but permissionModeDefault, so the revocation line is byte-identical to the one #1595 measured and #1604 has been sending since. Its no-live-child contract is SetPermissionMode's, unchanged.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context) error

Run supervises the claude child until ctx is cancelled. Each iteration spawns claude, holds its stdin open, and waits for exit. On a crash it applies the exponential backoff before respawning with --resume; the backoff resets after a child that stayed up longer than BackoffReset.

Each iteration runs on a derived ctx (iterCtx) so a Restart can cancel a single child without tearing Run down. Shutdown is therefore detected from the parent ctx (ctx.Err()), not from the child-exit error: an iterCtx-only cancel (a settings restart) falls through to relaunch with the swapped args, while a parent cancel returns ctx.Err() cleanly. A deliberate restart skips backoff (it is not a crash). Mirrors supervisor.Run.

func (*Runner) SetMCPServerEnabled added in v0.17.0

func (r *Runner) SetMCPServerEnabled(ctx context.Context, serverName string, enabled bool) bool

SetMCPServerEnabled enables or disables one MCP server on the exact eligible live child and reports whether that child accepted it. enabled is passed through to the write in both directions rather than one value being fixed or derived from a state this package does not hold; marshalMCPToggleEnvelope's pointer field is what keeps a false explicit on the wire.

Named for the flag rather than the wire's `mcp_toggle` subtype deliberately: the request carries the value, so a Toggle spelling would invite a caller to expect a flip of whatever the current state is. Membership, authorization and the absence of any wire surface are as ReconnectMCPServer states.

func (*Runner) SetModel

func (r *Runner) SetModel(model string) error

SetModel changes the live child's model without creating a user turn. It mints from the runner-wide control sequence but deliberately does not touch the permission posture gate: model acknowledgement is not a turn-admission gate.

func (*Runner) SetPermissionMode

func (r *Runner) SetPermissionMode(mode string) error

SetPermissionMode writes a single set_permission_mode control_request line to the live child's stdin, switching its permission posture WITHOUT killing it. #1595 measured the default switch live against claude 2.1.220 and #2041 measured acceptEdits, dontAsk, plan and auto against 2.1.239 — each acked success with the next turn's init.permissionMode echoing the new mode, no respawn. The request_id is locally minted from the counter Interrupt and RequestInitialize share.

mode is refused unless it is in WritePermissionMode's closed allow-list, which since #2066 has SIX members and the escalation among them: re-granting bypass arrives HERE now, not on the respawn path, because #2065 put the launch flag on every argv and #2060 measured claude accepting the re-escalation on such a child at 2.1.239. What the allow-list still refuses, by NON-MEMBERSHIP, is every mode claude will not parse, near misses of the escalation included. The refusal (ErrUnsupportedPermissionMode) is permanent and stays errors.Is-distinguishable from the retryable ErrNoLiveChild, which is what a caller gets when no child is live — Stdin() is nil then, so nothing is written and nothing panics.

A runner wired to its concrete Parser snapshots the live child's writer and generation before registering the request id and requested mode, then rechecks that generation before writing. A call begun between children therefore cannot drift onto a successor. ConfirmedPermissionMode changes only after the write succeeds and a success response carries both that exact id and an equal echoed mode. The method still returns after the write rather than waiting for that response.

Like RevokeBypass and unlike Interrupt it IS on sessions.Runner, and the contrast is the rule rather than an exception: Interrupt's dispatch lives in cmd/pyry, which can type-assert, whereas this method's consumers sit inside internal/sessions, with no such dispatch site. A structural assertion there would fail OPEN — its unmatched arm is a silent no-op, leaving the child in the wrong posture while the update reports success — so the interface method makes a runner that cannot switch a build failure instead.

A SUCCESSFUL write RETARGETS the posture gate when that gate is closed (#2064), and this is the recovery path for a spawn-time write claude NAK'd. The gate's only other opener is a spawn, so without this a NAK'd child stays healthy and refuses every turn until the daemon restarts — and the operator's remedy would not reach it, since a corrective mode change is in-band-deliverable and so never restarts anything. An OPEN gate is left open: see retarget for why gating in-band changes would drop deliverSettingsInBand's own follow-on sends.

The retarget is deliberately AFTER the write and skipped on error, including the allow-list refusal. A line that never reached the child will never be acked, so pointing the gate at its id would replace a pending spawn id that still might be acked with one that cannot be.

Stdin() releases r.mu before returning, so the potentially-blocking write never holds it. Safe from any goroutine.

func (*Runner) SetSpawnArgs

func (r *Runner) SetSpawnArgs(args []string)

SetSpawnArgs installs the base argv the NEXT spawn will use and leaves any live child running — it is Restart's swap half without the kill: no restartCh hint, no iterCancel call. It exists for a caller that needs to change what the session will run next without ending what it is running now; declining to call Restart is not that path, since it loses the swap outright and the next spawn (a crash-respawn, or an evict then Activate) silently re-execs the stale argv. Non-blocking, fire-and-forget, safe from any goroutine.

The two do NOT converge when no child is live. Restart still sends its hint in that case, and the token is observable twice over: it satisfies Run's restartCh case in the backoff select, cutting an in-progress backoff wait short, and with no wait in flight it persists in the buffered channel so the NEXT child exit skips backoff entirely — RestartCount never increments and PhaseBackoff is never set. SetSpawnArgs sends nothing, so a runner already backing off stays backing off and the swap simply lands on the spawn that wait was going to make anyway.

It takes restartMu exactly once and writes only args — never sessionID, rotatePending or iterCancel — so it preserves the #1481 single-acquisition property by construction, and cannot reach the forbidden state beginSpawn's doc names (that state is defined over the three fields it does not touch). Against a racing beginSpawn it serialises wholly before (that spawn observes the swap) or wholly after (that spawn keeps the old argv and the next one takes the new). Both are correct: the contract is the NEXT spawn, and it promises nothing about a spawn already in flight. Like Restart it drives only Runner-internal state and touches neither Pool.mu nor Session.lcMu, so the sessions layer can call it after releasing Pool.mu with no lock-order concern.

The argv is installed VERBATIM — no validation, no shaping. That boundary is deliberate: composition and validation live upstream in the sessions layer (Session.spawnArgs, where claudeSettingsArgs enforces the yolo fail-safe in one place), and duplicating them here would give two places to keep in sync. Two consequences the caller owns, both inherited from Restart rather than introduced here: cmd/pyry's construction-time argv shaping is NOT reapplied on any post-construction install path (stripSessionIDFlags runs in mapStreamsupConfig and withApprovalArgs in newStreamRunnerFactory, both construction-only), and Run logs the composed argv at Info ("spawning claude"), so anything installed here reaches the daemon log.

Must never be called with restartMu already held — the mutex is not reentrant. A caller already inside a section installs through setArgsLocked instead.

func (*Runner) SetSpawnPermissionMode

func (r *Runner) SetSpawnPermissionMode(mode string)

SetSpawnPermissionMode installs the posture EVERY LATER SPAWN asserts, without touching the running child (#2064). It is SetPermissionMode's per-spawn twin and the contrast is the point: that method changes the live child's posture and writes nothing durable, this one changes what the next child is told and writes nothing at all.

It exists because Pool.UpdateSettings REBUILDS NO RUNNER — both its branches install a recomposed argv onto the live runner and neither reconstructs it — so a posture read from the construction-time Config at spawn time goes stale the moment an operator changes the session's settings. A crash-respawn would then assert the posture the session had at daemon start, which can LOOSEN one the operator has since tightened. That is why the pool calls this on the line above its branch split, where its own comment already reads "Both branches install newArgs".

Two cheaper shapes do not cover it, and are recorded so they are not re-proposed:

  • Piggybacking the install on SetPermissionMode, which the in-band branch already calls. #2066's reason for rejecting it is gone — an escalation now IS in-band-deliverable and does reach that method — but the verdict stands on the branch that remains: a Model or Effort cleared to "" still takes Pool.UpdateSettings' restart branch, which never calls SetPermissionMode, so a piggybacked install would miss every such change and let a crash-respawn re-assert a stale posture. An install on the line ABOVE the branch split is the only shape that covers both.
  • Deriving the posture from the installed argv. Exact today and dead on arrival under #2065, which takes the mode out of the launch argv entirely.

mode is stored VERBATIM AND UNVALIDATED, including bypassPermissions and including the empty string. This is a normalisation-free install of an already-canonical stored value, not an operator-input path: the vocabulary gate that matters runs at the SPAWN, where permissionModeSpawnWritable decides whether anything is written at all, and duplicating it here would be two copies of one defence rather than a second one.

That predicate and not permissionModeAllowed is #2066's carve-out, and the one mode they disagree on is the one this paragraph installs verbatim. The writer's allow-list admits the escalation now, so a LIVE child can be walked back up to it; the spawn is still sent nothing for it, because since #2065 the launch argv already asserts it — there is nothing to walk a fresh child TO — and arming the posture gate on a control request nothing has measured as a fresh stream's first would be the bricked-session shape #2064 rejected.

It takes restartMu alone — never mu, never a Pool lock — so the sessions layer can call it after releasing Pool.mu with no lock-order concern, exactly as SetSpawnArgs can. Safe from any goroutine; non-blocking.

func (*Runner) SetSpawnWorkDir added in v0.19.0

func (r *Runner) SetSpawnWorkDir(workDir, claudeSessionsDir string) error

SetSpawnWorkDir installs the directory the NEXT spawn chdirs into, together with the transcript folder that spawn's create/resume probe reads. It does NOT restart: a live child keeps running where it is, and the swap lands on whatever spawn happens next — the crash-respawn the loop was going to make anyway, or the one a following RestartFresh orders. #1475's consumer pairs it with RestartFresh for exactly that reason.

It is SetSpawnArgs' sibling. One restartMu acquisition, writing only the directory pair — never sessionID, rotatePending, freshSeq, iterCancel or args — so it preserves the #1481 single-acquisition property by construction and cannot reach the forbidden state beginSpawn's doc names (that state is defined over fields it does not touch). Against a racing beginSpawn it serialises wholly before (that spawn observes the swap) or wholly after (that spawn keeps the old directory and the next one takes the new); both are correct, because the contract is the NEXT spawn and it promises nothing about a spawn already in flight. Like Restart it drives only Runner-internal state and touches neither Pool.mu nor Session.lcMu, so the sessions layer can call it after releasing Pool.mu with no lock-order concern.

THE RESOLVE SITS ABOVE THE LOCK, and both halves of that placement are load-bearing. Above, because restartMu is a leaf — nothing under it may take another lock or do synchronous I/O, the invariant setArgsLocked states — and ResolveWorkdir stats the path and resolves symlinks. Present at all, because New applies the same function to cfg.WorkDir: skipping it would break workDir's "resolved absolute path" invariant and, worse, desynchronise the pair — the caller derives claudeSessionsDir through ResolveWorkdir too, including the canonicalCase step resolveSpawnDir does not apply, so a raw workDir here would name a directory whose transcript folder is the resolved one's.

A resolve failure writes NEITHER field: the pair is fail-closed on the directory the runner already had, never half-applied. That is the same direction the whole #1475 reject set takes — a workspace that cannot be resolved leaves the successor where it was rather than moving it somewhere unvalidated.

An empty workDir is a no-op (logged at Warn): the runner never chdirs into "". This is the deterministic last-resort guard RestartFresh's empty-id early return already models — the validating boundary is the caller (cmd/pyry's resolveSpawnDir, which answers "" for "no recorded workspace" and never asks for an install), and this upholds New's non-empty contract regardless.

Must never be called with restartMu already held — the mutex is not reentrant.

func (*Runner) State

func (r *Runner) State() State

State returns a snapshot of the current runner state. Safe to call from any goroutine. Mirrors supervisor.State().

func (*Runner) Stdin

func (r *Runner) Stdin() io.Writer

Stdin returns the live child's stdin (the write end of its StdinPipe), or nil when no child is live (before the first spawn, between spawns, and mid-restart). The return type is io.Writer, not io.WriteCloser, so a consumer cannot close a handle the runner owns. This is the held-open-stdin seam; #1088's writer marshals a turn envelope and writes here, treating nil as a "no live child" refusal.

func (*Runner) WaitForPTY

func (r *Runner) WaitForPTY(ctx context.Context) error

WaitForPTY returns cleanly: the stream-json path has no PTY to await. The session lifecycle calls it at the end of Activate so PTY-backed runners can block until their master is bound; on the stream path there is no such readiness gate, and the no-live-child window is handled per-turn by WriteTurn's retryable ErrNoLiveChild. Mirrors the seam that supervisor.WaitForPTY fills.

func (*Runner) WriteUserTurn

func (r *Runner) WriteUserTurn(ctx context.Context, conversationID string, payload []byte) error

WriteUserTurn writes the user envelope to the live child's stdin and claims the turncommit gate, wrapping the reviewed WriteTurn free function (#1088). It is the delivery path the session pool dispatches through (send_message → Session.WriteUserTurn → here). A nil target yields ErrNoLiveChild without writing, the retryable no-live-child refusal, and there are THREE ways to get one: no live child, a rotation armed by BeginRotation (#1330), and a permission posture this child has not confirmed (#2064, whose own two states — awaiting an ack, and refused by claude — refuse identically and are told apart only by the record). A turncommit gate deny yields turncommit.ErrDropped with zero bytes written. All of it is WriteTurn's verbatim contract, so no new envelope construction is introduced.

The rotation refusal deliberately reuses ErrNoLiveChild rather than minting a sentinel: that is already the retryable classification msgqueue and cmd/pyry agree on, and the e2e asserts as a contract check that stream WriteUserTurn returns only ErrNoLiveChild, turncommit.ErrDropped or nil (`TestRelayV2_StreamNewSessionRotatesAndRestartsFresh`). The discriminator an operator needs — "refused by the rotation gate" vs "no child yet" — is carried by the record below instead. Cost of refusing rather than blocking: the turn lands up to one msgqueue retry interval (1 s) later, against a give-up bound of 2 m.

conversationID is accepted for interface conformance (sessions.Runner) and future outbound-cursor wiring (T4/T7); this slice does not yet track a cursor, so it is intentionally unused here — and it MUST NOT be logged: conversation ids are resolved daemon-side and stamped on the wire, never logged (cmd/pyry's stream_turn_busy.go, session_transition_v2.go), and streamsup logs none today. Neither may payload bytes be.

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 runner entered Run
	RestartCount int           // number of times the child has crashed and backed off
	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 runner's runtime state, the stream-json analogue of supervisor.State. It mirrors that type field-for-field: the cmd/pyry adapter maps it to supervisor.State (this package must not import internal/supervisor), and the control plane's status builder reads all six fields, so all six are kept faithful by the Run loop's instrumentation.

type Watchdog

type Watchdog struct {
	// contains filtered or unexported fields
}

Watchdog is the receive-side idle watchdog. It owns a stallTracker (wired as Config.Stdout via Writer) and a single poll goroutine that, while claude owes an assistant turn, emits a stall signal when the stream sits silent past the threshold.

DIVERGENCE from streamrunner's one-shot watchdog, which KILLS on idle stall: this watchdog EMITS and NEVER kills. A pending permission approval is unbounded owed-silence (T1 spike #1075: claude blocks synchronously until the approval tool answers), so killing on awaiting && idle would destroy a legitimately blocked turn. Emit-not-kill is enforced STRUCTURALLY, not just by convention: the Watchdog holds no context.CancelFunc and no process handle, so it has no way to kill — WatchdogConfig has no cancel field to wire one, and no synthetic `result` trailer is composed.

SECOND DIVERGENCE from streamrunner (#1504): that runner *is* the send side, so it may assume an owed turn the moment its parser is constructed. This watchdog is constructed away from the send side and cannot, so the owed-turn fact is supplied by UserTurnSent and ChildExited rather than assumed. The asymmetry is unavoidable rather than stylistic: claude does not echo the delivered prompt back as a `user` line on this surface (measured — see the streamsup feature doc), so the stdout stream alone can never tell the watchdog that a turn was sent, and a tracker left to arm from stdout would turn today's false positive into a silent false negative on the wedge this component exists to catch.

func NewWatchdog

func NewWatchdog(cfg WatchdogConfig) *Watchdog

NewWatchdog constructs a Watchdog. Compose Writer() into Config.Stdout, then call Start(ctx) once and Wait() at teardown.

func (*Watchdog) ChildExited

func (w *Watchdog) ChildExited()

ChildExited tells the watchdog that the child it was watching is gone: whatever that child owed is void, so a turn abandoned by a crash mid-turn cannot make the respawned child's healthy silence look like a wedge. The respawned child is met in the state a freshly constructed tracker has — not awaiting, idle clock restarted — which is the whole of the reset.

The watchdog itself survives the respawn: one watchdog per runner, not one per child, because Config.Stdout is fixed when the Runner is built and the supervise loop never re-wires it, so a per-child watchdog could not reach the new child's stdout. That also keeps exactly one poll goroutine and one Start/Wait pair for the runner's life, which is the contract Start documents.

Same locking properties as UserTurnSent: leaf mutex only, safe from any goroutine.

func (*Watchdog) Start

func (w *Watchdog) Start(ctx context.Context)

Start launches the single poll goroutine. Call exactly once. The goroutine ticks at watchdogTickFor(Idle); on each tick it snapshots the tracker and, on the rising edge of a stall (edge-triggered — latched once per episode, re-arms when activity or an awaiting flip clears the condition), evaluates the pending-permission hook, logs a content-free Warn, and calls OnStall. It never kills and never returns early after firing — it keeps polling until ctx is cancelled, which is what lets it tolerate an unbounded pending-permission window. On ctx.Done it returns and closes done; Wait joins.

func (*Watchdog) UserTurnSent

func (w *Watchdog) UserTurnSent()

UserTurnSent tells the watchdog that a user turn's bytes reached the child's stdin: claude owes an assistant turn, and the idle threshold counts from this call rather than from the child's last output (which on an idle session is arbitrarily stale).

It means bytes actually DELIVERED, so call it only after a Runner.WriteUserTurn that returned nil. That method's two refusals write zero bytes — ErrNoLiveChild (no live child, or a BeginRotation gate) and turncommit.ErrDropped (gate deny) — and a refused turn owes nothing, so arming on one reintroduces the same false stall by another route. The method takes no argument and returns nothing precisely so that decision stays at the one call site that can see the error value.

Control requests do NOT arm it. Runner.Interrupt and Runner.RevokeBypass write `control_request` lines that claude acks in ~40ms (#1075/#1595) and that are not user turns; no wedge has been observed on that path. The trigger is "a user turn was delivered", not "a write happened".

Call it on the writing goroutine after the write returns. Arming first and unwinding on error would leave an armed tracker behind every error path — the failure this signal removes. Arming after opens a nanosecond-width reorder in which claude's first output could clear awaiting before this sets it; that is bounded (microseconds after the write syscall, against claude's tens of milliseconds to first output) and self-healing (the next `assistant` or `result` line clears awaiting again), so it is named here rather than mechanised.

Safe from any goroutine: it takes only the tracker's leaf mutex, never logs and never calls out, so a caller may hold its own locks across it.

func (*Watchdog) Wait

func (w *Watchdog) Wait()

Wait blocks until the poll goroutine has exited (after Start's ctx is cancelled). Call after Start.

func (*Watchdog) Writer

func (w *Watchdog) Writer() io.Writer

Writer returns the stallTracker for Config.Stdout composition. The caller fans the child's stdout to both the #1088 Parser and this writer with io.MultiWriter (deferred to the wiring slice).

type WatchdogConfig

type WatchdogConfig struct {
	// Idle is the stall threshold: how long the stream may sit silent while
	// claude owes an assistant turn before a stall is emitted. Zero → idleStall
	// (240s).
	Idle time.Duration

	// PendingPermission is the content-free timing hook: it reports whether a
	// permission approval is currently outstanding. The watchdog consults it at
	// fire time and carries its value on the emitted signal — it does NOT gate
	// whether the stall is emitted (both a genuine wedge and an approval-wait
	// emit; the distinction lives in the argument). Nil → treated as always-false
	// (no permission pending — the genuine-wedge path). The hook's producer (the
	// approval flow) is out of scope for this slice (#1079/#1080).
	PendingPermission func() bool

	// OnStall is the stall signal, called on the rising edge of a stall episode
	// (once per episode, on the poll goroutine) with the pending-permission value
	// at fire time. Nil → no-op guard. The watchdog makes no promise beyond
	// "called serially, on the poll goroutine, once per stall episode"; the
	// consumer owns any synchronization it needs. It NEVER kills — this callback
	// is the entire effect of a fire.
	OnStall func(pendingPermission bool)

	// Logger is used for content-free diagnostics only (idle_seconds, the
	// pending_permission bool, byte counts). Nil → slog.Default.
	Logger *slog.Logger
	// contains filtered or unexported fields
}

WatchdogConfig configures a Watchdog. The zero value is usable except that a real watchdog supplies OnStall (a nil OnStall degrades to detection-only).

Jump to

Keyboard shortcuts

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