sessions

package
v0.39.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 22 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 sessions owns the set of supervised claude instances managed by one pyry process. Phase 1.0 constructs exactly one entry — the bootstrap session — at startup; Phase 1.1+ will add multi-session routing on top of the same Pool/Session shape.

Index

Constants

View Source
const HarnessClaude = "claude"

HarnessClaude is the harness of a session claude runs, and the meaning of an empty harness anywhere one is read (#2593). It is the only harness any path mints today.

View Source
const MaxHandoffNoteBytes = 16 << 10

MaxHandoffNoteBytes bounds one handoff note on disk. UTF-8 BYTES, NOT RUNES, matching every bound in internal/protocol.

An over-bound note is TRUNCATED, not refused — the opposite of admissibleClientField, and deliberately so. A refused client name costs a section of a system prompt; a refused handoff note costs the successor session everything its predecessor knew, and a wrap-up reply that ran long is exactly the case where the note matters most. The head of a long note is still a usable handoff.

Exported because #2455 composes a prompt around a bounded value and should be able to name the bound rather than re-derive it.

View Source
const PermissionModeBypass = permissionModeBypass

PermissionModeBypass is the escalation's one spelling, exported for cmd/pyry's withApprovalArgs — the only consumer outside this package that has to tell a session which STAYS in bypass from one the daemon walks back in-band (#2065). It is an alias of permissionModeBypass rather than a second literal, so the vocabulary still lives in exactly one place.

Nothing here decides authorisation from it. It answers "will this child keep the posture it launched with?", and cmd/pyry pairs it with the provenance bit (RunnerConfig.OperatorBypass) because the stored posture alone cannot answer that — the operator's pass-through claude args put the escalation on an argv without ever touching SessionSettings.

Variables

View Source
var (
	ErrDaemonInstructionsTooLong     = errors.New("sessions: daemon instructions exceed the maximum byte length")
	ErrDaemonInstructionsInvalidUTF8 = errors.New("sessions: daemon instructions are not valid UTF-8")
)
View Source
var ErrAmbiguousSessionID = errors.New("sessions: ambiguous session id")

ErrAmbiguousSessionID is returned by Pool.ResolveID when a non-empty, non-full-UUID arg matches the prefix of two or more sessions. The wrapped error's Error() lists each match as `<uuid> (<label>)` on its own line so a CLI consumer can print it verbatim. Matchable via errors.Is.

View Source
var ErrCannotRemoveBootstrap = errors.New("sessions: cannot remove bootstrap session")

ErrCannotRemoveBootstrap is returned by Pool.Remove for the bootstrap session. The bootstrap is a per-process invariant, not an operator resource — removing it would leave the pool in a state Pool.Lookup("") can't satisfy. Matchable via errors.Is.

View Source
var ErrDormantPostureUnsupported = errors.New("sessions: dormant session cannot store a permission posture")

ErrDormantPostureUnsupported is returned by Pool.UpdateDormantSettings for an update naming YOLO or PermissionMode. A dormant entry's persisted posture is read by nothing — a revive builds the default structurally from model and effort (#1487) — so storing one would report success for a change the next read contradicts. See Pool.UpdateDormantSettings for the whole decision.

DISTINCT FROM ErrSessionNotFound on purpose, even though cmd/pyry's settingsUpdaterAdapter maps both to the same wire code. That adapter composes the live write and the dormant one, and reads the live write's ErrSessionNotFound as "try the other half"; one shared sentinel would mean that and "refuse" one line apart. It would also have this method reporting "not found" about an id it did find. Matchable via errors.Is.

View Source
var ErrHandoffNotesDisabled = errors.New("sessions: handoff notes need a data dir; persistence is disabled")

ErrHandoffNotesDisabled is returned by Pool.WriteHandoffNote when persistence is disabled — the test-only mode Pool.dataDir reports as "". A sentinel so a caller can recognise the condition: a failed handoff note must never fail the reset it was written for, so #2455 is expected to log and continue rather than propagate.

View Source
var ErrInvalidSessionID = errors.New("sessions: invalid session id")

ErrInvalidSessionID is returned by Pool.GetOrCreate when the supplied id is not a canonical UUIDv4-shaped string. Empty id also returns this. Matchable via errors.Is.

View Source
var ErrPermissionModeConflict = errors.New("sessions: permission mode contradicts yolo")

ErrPermissionModeConflict is returned by Pool.UpdateSettings when one frame carries a permission mode and a YOLO bit that contradict each other — a bypassPermissions mode with yolo:false, or any other mode with yolo:true. Nothing is persisted.

Rejection rather than a precedence rule, because neither precedence is fail-safe in both directions: letting the mode win downgrades an escalation silently, letting YOLO win GRANTS one from a frame that said false. A contradictory update has no correct reading. Bare, for ErrUnsupportedPermissionMode's reason.

View Source
var ErrPoolNotRunning = errors.New("sessions: pool not running")

ErrPoolNotRunning is returned by supervise when called before Pool.Run has wired the supervisor handle, or after Run has cleared it. Callers must invoke supervise only while Pool.Run is active.

View Source
var ErrSessionIDTaken = errors.New("sessions: session id already in use")

ErrSessionIDTaken means an announced destination belongs to another session.

View Source
var ErrSessionNotFound = errors.New("sessions: session not found")

ErrSessionNotFound is returned by Pool.Lookup for a non-empty unknown id.

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

ErrUnsupportedPermissionMode is returned by Pool.UpdateSettings when the update names a permission mode this daemon does not recognise. Nothing is persisted and no live child is touched, so an unrecognised value can never reach a spawn argv or the child.

Bare: it does NOT echo the rejected mode. A caller may therefore log it verbatim — #833 keeps settings values out of the daemon log and a permission mode is a settings value. It is the in-package twin of the seam's own streamsup.ErrUnsupportedPermissionMode, which this package must not import (that would invert the Runner seam).

Functions

func AdmitClientVersion added in v0.25.0

func AdmitClientVersion(v string) string

AdmitClientVersion returns v verbatim when admissibleClientField admits it as a client version (maxClientVersionBytes), and "" otherwise. It is admitClient's version rule, exported so the device registry's persisted version (#2577) passes the one copy of the filter rather than a second one. A refusal is silent, as in admitClient.

func ClaudeSettingsModel added in v0.38.0

func ClaudeSettingsModel(workDir string) string

ClaudeSettingsModel answers the model claude would start on in workDir when its argv names none, which is Config.DefaultModel's contract. The first source that names a model wins, in Claude Code's documented precedence:

  1. ANTHROPIC_MODEL in the environment, which every child inherits.
  2. "model" in <workDir>/.claude/settings.local.json.
  3. "model" in <workDir>/.claude/settings.json.
  4. "model" in the user's settings.json, under $CLAUDE_CONFIG_DIR when set and ~/.claude otherwise.

"" when none names one. An empty workDir reads the project files relative to the daemon's own directory, which is where such a child starts.

Two sources are left out on purpose: managed settings, which no pyry host uses, and an ANTHROPIC_MODEL set through a settings file's env block. Missing either can only leave a pinned default unresolved, which is the behaviour before this existed, never a wrong model. A file that is absent, unreadable, oversized or not JSON is skipped.

The answer is never placed on an argv as it is. composeSpawnArgs names only its modelfamily.Alias rewrite, whose output is a bare family of letters plus at most one bounded variant group, so nothing in these files can reach claude as a flag.

func DefaultClaudeSessionsDir

func DefaultClaudeSessionsDir(workdir string) string

DefaultClaudeSessionsDir returns the directory where claude writes <uuid>.jsonl files for the given workdir. Returns "" if workdir is empty or $HOME is unresolvable; callers treat "" as "reconciliation disabled".

The workdir is symlink-resolved before encoding (#989): claude encodes its RESOLVED cwd into the projects folder name, so on macOS a workdir under /var/folders/... (a symlink to /private/var/...) writes transcripts under -private-var-folders-.... Encoding the literal form pointed every by-id resolver at a folder claude never writes; the old fd-probe path masked this because its confidentiality guard compared symlink-resolved paths on both sides. Production paths under /Users carry no symlink, which is why only tmpdir-based test environments ever saw the mismatch. Resolution failure (workdir vanished, permission) falls back to the literal form — same best-effort shape as the resolvers' own EvalSymlinks fallbacks.

func FencedHandoffNote added in v0.19.0

func FencedHandoffNote(note string) (string, bool)

FencedHandoffNote renders note between the two markers, or ("", false) when admissibleHandoffNote refuses it. It is the fence WITHOUT any lead: the structural half of the trust boundary, separated from the sentence that governs how the note is read.

It admits its own input rather than trusting the caller to have done it, which is clientSection's rule and keeps every caller total over hostile values, the tests included.

The ONE byte this adds that the note did not supply is a trailing newline when the note lacks one. That is framing, not repair: without it the end marker would be glued to the note's last line, and a marker line partly composed of note bytes is precisely what the fence exists to prevent. The note's own trailing newlines, however many, are left alone.

EXPORTED FOR A SECOND DESTINATION, not for reuse in general. #2477 composes the wrap-up prompt in cmd/pyry — a user turn to the OUTGOING child, carrying the previous note so the writer can prune it — and that prompt needs this fence and these refusals but not handoffNoteLead, whose sentence is written for a system prompt ("consult it when the user refers to earlier work") and is wrong for a turn asking the reader to rewrite the note. Cutting the seam below the lead is what keeps ONE predicate and ONE fence across both destinations: a second predicate over the same untrusted bytes is how the two drift apart, and a hand-spelled marker in the other package would leave admissibleHandoffNote's refusals guarding a shape that composition no longer has.

The BOOL rather than a bare "" is for that caller: cmd/pyry composes a prompt around the answer and has to choose between two shapes, where this package's own caller below only has to choose whether to emit a section.

func ValidID added in v0.9.0

func ValidID(s string) bool

ValidID reports whether s is a canonical UUIDv4 string of the shape NewID produces: 36 chars, lowercase hex, dashes at positions 8/13/18/23, version-4 nibble (0x4_) at position 14, and RFC 4122 variant (0x8/0x9/0xa/0xb) at position 19. Empty input returns false.

The version + variant checks are belt-and-suspenders for callers that accept caller-supplied IDs (Pool.GetOrCreate). The SDK-produced UUIDs are uuidv4 by construction, so the cost is nil and a future contributor mistakenly trying to register a v3/v5 id gets a clean error.

Types

type ClientIdentity added in v0.16.0

type ClientIdentity struct {
	Name     string
	Version  string
	Features string
}

ClientIdentity is one attached client's self-reported identity: the device_name, client_version and client_features it put in its own hello.

ALL THREE FIELDS ARE REMOTE-AUTHORED AND UNVALIDATED. Nothing between the wire and admitClient inspects them — internal/relay retains them verbatim on purpose, because validating there would bind a wire type to a rendering decision it does not own (the argument composeSystemPrompt makes for leaving #2149's Registry.SetSystemPrompt the single door for operator bytes). A holder of this type holds untrusted text until admitClient has passed it.

Any field may be empty: neither client sends a product name today (pyrycode-desktop reports a hostname, pyrycode-mobile a device model), and a client is free to report nothing at all.

type ClientIdentityResolver added in v0.16.0

type ClientIdentityResolver func(ctx context.Context) []ClientIdentity

ClientIdentityResolver answers which clients are attached right now. It is the seam by which internal/sessions learns something only internal/relay knows, without importing it — TransitionObserver's shape, pointing the other way.

The implementation MUST respect ctx and MUST NOT block indefinitely: the production one funnels a request onto the relay manager's Run goroutine and waits for the reply, and it is called immediately before a claude spawn. Returning nil is always a valid answer and is what every failure collapses to; there is deliberately no error return, so nothing here can fail a spawn.

type Config

type Config struct {
	Bootstrap SessionConfig
	Logger    *slog.Logger

	// BootstrapEvicted, when true, constructs the bootstrap session in
	// stateEvicted instead of the default stateActive, so Pool.Run parks it in
	// runEvicted and it spawns no claude. The zero value (false) is
	// byte-identical to today's eager-bootstrap behaviour.
	//
	// This exists for embedded hosts that map each caller session onto its own
	// Pool.Create'd claude and must not run a second, unaddressed bootstrap
	// claude (pyry acp / divergence 6, #761). It is sound only when the
	// bootstrap is never Activated and its evicted state is never persisted: the
	// pool keeps it as a dormant Default()/Lookup("") placeholder until Run's
	// ctx cancels. Do NOT pair it with a RegistryPath that would persist
	// "evicted" for the bootstrap and later wake it with no attach client to
	// drive Activate (the #202 hang the New warm-start branch guards against).
	BootstrapEvicted bool

	// RegistryPath is the on-disk path of the sessions.json registry. Empty
	// disables persistence (test-only). In production this is always
	// ~/.pyry/<sanitized-name>/sessions.json — see cmd/pyry resolveRegistryPath.
	RegistryPath string

	// ClaudeSessionsDir is the directory containing claude's <uuid>.jsonl
	// files for this WorkDir. Empty disables startup reconciliation (test
	// default, and the production fallback when $HOME is unresolvable).
	// Production callers in cmd/pyry resolve this via
	// DefaultClaudeSessionsDir from cfg.Bootstrap.WorkDir.
	ClaudeSessionsDir string

	// ConversationsRegistry, when non-nil, enables the periodic auto-archive
	// sweep goroutine inside Pool.Run. The registry must already be Loaded
	// by the caller (cmd/pyry handles the conversations.Load call so the
	// sessions package stays path-agnostic about conversations.json — see
	// docs/knowledge/features/conversations-registry.md).
	//
	// nil disables the sweep goroutine entirely (test default; existing
	// pool tests construct Config without this field and remain unchanged).
	ConversationsRegistry *conversations.Registry

	// ConversationsRegistryPath is the on-disk path of conversations.json
	// — passed to RunSweepLoop's Save call after each non-empty tick. In
	// production this is always ~/.pyry/<sanitized-name>/conversations.json
	// — see cmd/pyry resolveConversationsRegistryPath.
	//
	// Required when ConversationsRegistry is non-nil; ignored when nil.
	ConversationsRegistryPath string

	// ReadFolders are the folders the file reader serves besides a
	// conversation's workspace (#2710), as cmd/pyry's resolveReadFolders
	// returned them: only the entries that resolved, never a skipped one. Every
	// appended system prompt names them in one sentence after systemPromptText
	// (#2711). Nil, the zero value, composes every prompt byte for byte as before.
	ReadFolders []string

	// DefaultModel answers the model claude starts on, for a child spawned in
	// workDir, when its argv names none: Claude Code's own model setting. A
	// session with no model of its own would otherwise run whatever that setting
	// pins. When the answer is a pinned Claude id, the argv names its family
	// instead (composeSpawnArgs), so such a session still follows the latest model
	// of a family. cmd/pyry wires ClaudeSettingsModel. Nil, the zero value,
	// resolves nothing and composes every argv as before; every test pool leaves
	// it nil so the host's own settings file cannot reach a test's argv.
	DefaultModel func(workDir string) string

	// SweepInterval, when > 0, overrides the conversations sweep tick
	// interval Pool.Run passes to conversations.RunSweepLoop. Zero (the
	// default) means use conversations.SweepInterval (one hour). Production
	// callers leave this zero; the cmd/pyry -pyry-conv-sweep-interval flag
	// (intended for e2e tests) plumbs a small duration here so the sweep
	// loop can be exercised without waiting an hour.
	//
	// Ignored when ConversationsRegistry is nil (the sweep goroutine
	// doesn't run at all in that case).
	SweepInterval time.Duration

	// IdleTimeout is the default per-session idle eviction window. A
	// SessionConfig with IdleTimeout==0 inherits this value at New().
	// Zero here means "never evict". cmd/pyry passes the -pyry-idle-timeout
	// flag, which also defaults to 0, so idle eviction is off unless the
	// operator sets the flag.
	IdleTimeout time.Duration

	// TurnBusy, when non-nil, reports whether the given session has a turn
	// open. An idle-timer fire that finds its session busy re-arms instead of
	// evicting, so a long turn is not killed mid-stream (#1486). It is called
	// on the session's lifecycle goroutine with no pool or session lock held,
	// and must not block. nil means no signal: the timer evicts on fire. One
	// bool per session is all that crosses here — cmd/pyry resolves the
	// session to its conversation on its own side of the seam.
	TurnBusy func(SessionID) bool

	// OnRunnerStopped, when non-nil, observes each completed Runner.Run call,
	// after the producer returns and before eviction completion or reactivation.
	// Called without pool/session locks; it must not block. Unlike the transition
	// observer's early eviction signal, this is a producer shutdown boundary.
	OnRunnerStopped func(SessionID)

	// ActiveCap is the maximum number of concurrently active claude
	// processes this Pool will run. Zero (the unset default) means
	// uncapped — preserves Phase 1.2c-A's idle-only behaviour
	// byte-for-byte (no LRU bookkeeping cost on the hot path).
	//
	// When set (>= 1), an Activate that would push the count past the
	// cap first evicts the least-recently-active currently-active peer
	// via Session.Evict. The evicted session transitions to `evicted`
	// exactly as it would from an idle timeout — same on-disk state
	// change, same registry write.
	//
	// Idle eviction (1.2c-A) and cap eviction compose: same Evict
	// mechanism, different victim picker. The idle timer runs per
	// session and picks itself; the cap path runs at Pool.Activate's
	// entry and picks the LRU peer.
	//
	// Values <= 0 are treated as unset.
	ActiveCap int

	// RunnerFactory is the injection seam for the supervised child, invoked at
	// every construction site (bootstrap in New and per-session in
	// buildSession). It is required: New returns an error on a nil factory.
	// Before #1348 nil selected the terminal supervisor, which no longer exists;
	// the daemon passes the stream-json runner's factory.
	RunnerFactory RunnerFactory
}

Config is what cmd/pyry hands to sessions.New.

type JSONLPolicy

type JSONLPolicy uint8

JSONLPolicy controls how Pool.Remove handles a session's on-disk JSONL transcript file. The zero value (JSONLLeave) preserves the 1.1d-A1 (#94) behaviour: the JSONL is untouched.

const (
	// JSONLLeave leaves the JSONL on disk untouched. Default (zero value).
	JSONLLeave JSONLPolicy = iota
	// JSONLArchive moves the JSONL to <pyry-data-dir>/archived-sessions/<uuid>.jsonl.
	JSONLArchive
	// JSONLPurge deletes the JSONL.
	JSONLPurge
)

type LifecycleCause added in v0.38.0

type LifecycleCause string

LifecycleCause distinguishes the internal facts behind legacy delimiters. The zero value means unknown; workspace change currently has no producer.

const (
	CauseOperatorReset    LifecycleCause = "operator_reset"
	CauseClaudeClear      LifecycleCause = "claude_clear"
	CauseAgentSwitch      LifecycleCause = "agent_switch"
	CauseRecovery         LifecycleCause = "recovery"
	CauseWorkspaceChange  LifecycleCause = "workspace_change"
	CauseIdleSleep        LifecycleCause = "idle_sleep"
	CauseCapacityEviction LifecycleCause = "capacity_eviction"
)

type Phase added in v0.16.0

type Phase string

Phase describes a runner's current lifecycle state.

This and the two types below moved out of internal/supervisor when #1348 deleted it. They were never supervisor-specific: the stream runner has always had to mint a Phase on every State() call and be constructed from a Config, so the whole surface travelled through a package named for the one runner that no longer exists.

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 Pool

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

Pool owns the set of sessions managed by one pyry process. Phase 1.0 constructs exactly one entry — the bootstrap session — at New().

func New

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

New constructs a Pool. If a registry exists at cfg.RegistryPath, the bootstrap session reuses the persisted UUID and metadata; otherwise a fresh UUID is minted and the registry is written before New returns. Returns an error if cfg.RunnerFactory is nil, or if the rng, the runner factory, registry load, or registry save fails — all are fatal-at-startup conditions.

func (*Pool) Activate

func (p *Pool) Activate(ctx context.Context, id SessionID) error

Activate is the spawn-path entry: resolves an id and calls Session.Activate, enforcing the concurrent-active cap (Config.ActiveCap) along the way.

When the cap is unset (activeCap <= 0), this is a thin wrapper around Session.Activate — byte-identical to Phase 1.2c-A's behaviour, no LRU bookkeeping cost on the hot path.

When the cap is set, capMu serializes the cap-check + victim-eviction + new-spawn sequence. Two concurrent Activates against the same Pool can't both observe active < cap and both proceed. If the target is already active, lastActiveAt is bumped (LRU touch) and the call returns. Otherwise, when activating one more would exceed the cap, the LRU peer is evicted via Session.Evict before this Activate proceeds.

Until #2137 this was also where the rotation watcher's freshly-allocated skip-set was primed: claude opening <id>.jsonl looked like a /clear rotation to the watcher, so the spawn had to announce its own id as not-a-rotation, and #2085 moved that prime here from mint time because the TTL only covered a spawn that followed within milliseconds. The watcher is gone and the skip-set with it, so the prime is gone too — this is once again a plain spawn entry.

Lock discipline: the Lookup above takes and releases p.mu.RLock before p.capMu is acquired below. The documented capMu → mu → lcMu order is not inverted, because no goroutine ever holds p.mu while acquiring p.capMu.

func (*Pool) AdoptAnnouncedID added in v0.16.0

func (p *Pool) AdoptAnnouncedID(oldID, newID SessionID) error

AdoptAnnouncedID follows Claude's validated reset announcement without minting. Missing/colliding IDs refuse mutation and equal IDs are silent no-ops. The destination check and rekey share Pool.mu to prevent swallowing another session. Upstream transcript stem validation guards the subprocess trust boundary. Persistence is best effort; successful in-memory changes always notify.

func (*Pool) BootstrapID added in v0.16.0

func (p *Pool) BootstrapID() SessionID

BootstrapID returns the pool's current bootstrap session id under p.mu (RLock). It resolves p.bootstrap fresh on each call — mirroring Default/DefaultSettings — so it stays correct across a /clear rotation: RotateID flips p.bootstrap under the write lock, so the next spawn's ResolveSessionID provider (which calls this) resolves the rotated id (#839).

Concurrency: reads p.bootstrap (a p.mu-guarded SessionID value), deliberately NOT Default().ID()/sess.id. Reading p.bootstrap keeps the spawn path on the Pool.mu-guarded value and avoids taking Session.lcMu — which now guards sess.id alongside Pool.mu (#866) — while introducing no new sess.id reader. The RLock is race-clean against RotateID's Lock.

func (*Pool) Create

func (p *Pool) Create(ctx context.Context, label string) (SessionID, error)

Create mints a fresh session, persists it, and brings it up under the cap-aware spawn path. Returns the new SessionID and an error.

The returned id is empty only when the failure happened before (or during) the persist step — in that case nothing is on disk and nothing in memory changed. A non-empty id means the registry entry is on disk; the caller uses errors.Is to decide whether the failure was ErrPoolNotRunning (no lifecycle goroutine yet — fix and retry by calling Run + Activate) or an Activate error (lifecycle goroutine is running and may transition to active anyway — see ctx-cancellation note below).

Sequence: NewID → build *Session in stateEvicted → register under p.mu and persist (rollback the in-memory entry on save failure) → schedule sess.Run on Pool.Run's errgroup via supervise → call Pool.Activate (cap-aware) to wake the lifecycle goroutine. Everything up to and including supervise is Pool.Mint; this is that plus the Activate.

We persist BEFORE activating: a save failure with claude already running would leave an unsupervised orphan whose JSONL has no on-disk record. A registry-only entry that didn't activate is benign — the same shape as a session that ran and then idled out, recoverable on next Activate.

Concurrency: safe for concurrent use. Each call serialises through Pool.mu briefly (registration + persist), then runs supervise/Activate off-lock under the cap path's existing capMu serialisation.

Note: if ctx is cancelled after supervise succeeded but before Activate returns, the lifecycle goroutine still observes the buffered activate signal and may transition to active anyway. The lifecycle goroutine respects the pool's run-context, not the caller's. Tests should not assume "Activate returned ctx.Err → claude is not running."

func (*Pool) CreateIn added in v0.15.0

func (p *Pool) CreateIn(ctx context.Context, label, spawnDir string) (SessionID, error)

CreateIn is Create with an explicit per-session spawn working directory. spawnDir == "" spawns in the shared template workdir (tpl.WorkDir), byte-identical to Create. A non-empty spawnDir is used verbatim and is NOT validated, canonicalised, or trust-checked by the pool — callers supply a pre-resolved path (see #685). An inaccessible directory surfaces at spawn time via the supervisor's existing chdir-failure path, not here.

Otherwise identical to Create: see its docstring for the full create sequence, concurrency, and error semantics. The register-and-supervise half lives in Mint; this is that plus the cap-aware Activate, and the split is what lets the relay's per-conversation mint defer the spawn to the first message while the control plane's `sessions new` verb keeps bringing its session up (#2085).

func (*Pool) DaemonInstructions added in v0.32.0

func (p *Pool) DaemonInstructions() string

DaemonInstructions returns the current instructions shared by conversations.

func (*Pool) Default

func (p *Pool) Default() *Session

Default returns the bootstrap session. Equivalent to Lookup("") today; kept as an explicit accessor because cmd/pyry will need the bootstrap entry at startup (Child B).

func (*Pool) DefaultDaemonInstructions added in v0.32.0

func (p *Pool) DefaultDaemonInstructions() string

DefaultDaemonInstructions returns the exact text a caller can write to reset.

func (*Pool) DefaultSettings added in v0.16.0

func (p *Pool) DefaultSettings() (SessionSettings, bool)

DefaultSettings returns the bootstrap session's currently-persisted SessionSettings (model, effort, YOLO) plus whether a bootstrap session exists to read from. When none exists (the embedded evicted-bootstrap host, or a zero-value &Pool{} map-miss) it returns (SessionSettings{}, false) so a consumer falls back to the daemon defaults; there is no error path.

It resolves p.bootstrap fresh on each call — mirroring Default — so it stays correct across a session-id rotation (RotateID flips p.bootstrap under the write lock). SessionSettings is a value type, so the return is a snapshot copy with no aliasing of the pool's live field.

Concurrency: reads sess.settings under p.mu (RLock); does NOT take Session.lcMu — settings is a p.mu-guarded field (the writer UpdateSettings holds p.mu write; the other reader saveLocked holds p.mu), so there is no torn read. This accessor is unavoidable: settings is a private field read only under Pool.mu, so a consumer outside internal/sessions cannot reach it (SessionInfo/List does not carry it).

func (*Pool) DormantSettingsFor added in v0.19.0

func (p *Pool) DormantSettingsFor(id SessionID) (SessionSettings, error)

DormantSettingsFor returns the SessionSettings a Revive of id would materialise — the model and effort id's own persisted entry carries, and the default posture — or ErrSessionNotFound if this pool holds no dormant entry under that id. It is SettingsFor's dormant half: the two partition the ids the daemon has a record of, because materialise retires the entry it takes over and Remove drops the one it deletes (see Pool.dormant).

It exists so request_session_settings can answer a conversation bound to a session this daemon has not materialised (#2449). Pool.New materialises only the bootstrap, so after a restart that is EVERY conversation until its first message revives it, and the reply's every field sat at its zero: a client's model and effort menus went inert and its model label resolved the daemon's default row — a model the channel is not on.

A SECOND READ rather than a fallback inside SettingsFor, deliberately. Folding it in would change what "not found" means for every other caller of the live read, several of which use exactly that answer to decide a session is not addressable. Here the two meanings are kept apart and the caller composes them.

NOT Pool.revivedSettings, which is the same map read and cannot be reused as it stands: it collapses "no entry" into the zero SessionSettings, which is correct for a revive (an id with no record revives to claude's defaults) and wrong for a reader, which would then report an unknown bound id beside empty settings. The miss is this method's own.

THE POSTURE IS BUILT, NOT CLEARED. The literal names Model and Effort only and is then canonicalised, so YOLO false and the default mode are structural: mintSettings' and revivedSettings' recorded reason, which is that a clearing statement is something a later edit can delete, and that a field added to registryEntry is not inherited until someone opts it in. Two things follow that a caller depends on. A restart stays a revocation point for a phone-granted permission bypass (#1487): a persisted yolo or permission_mode cannot reach this reply however the entry was written. And the reported posture is the one Revive will actually materialise, because canonicalSettings here is the same function buildSession applies to what Revive hands it — an agreement by construction rather than by two places spelling the same constant.

Concurrency: MUST be called with p.mu unheld — one RLock acquisition, no delegation to another locking accessor. Go's RWMutex is not reentrant, so a call from inside a critical section self-deadlocks as soon as a writer queues; this is the hazard SettingsFor and mintSettings already record. The returned value is a snapshot copy, not a lease: SessionSettings is a value type and registryEntry is stored by value in p.dormant.

No id validation and no logging, SettingsFor's posture verbatim: the id names no file and never leaves the map lookup, so a malformed id is a map miss — already the correct answer — and the error is returned bare rather than wrapped with it, so a hostile id cannot be reflected into a log line or a wire frame a consumer builds from the error.

func (*Pool) DormantStoredPostureFor added in v0.29.0

func (p *Pool) DormantStoredPostureFor(id SessionID) (string, error)

DormantStoredPostureFor reads the persisted posture for an agent switch. DormantSettingsFor intentionally reports Revive's revoked default posture; the switch instead carries a stored non-bypass mode to the new session.

func (*Pool) EverActivated added in v0.21.0

func (p *Pool) EverActivated(id SessionID) bool

EverActivated reports whether the session named by id has ever been activated — the durable, restart-surviving answer to "has this conversation ever run?" (#2521). It is what lets the named new_session path tell a conversation created but never messaged, which must stay inert, from a previously-used session that merely has no child at this instant, which must be resettable.

It answers from ONE predicate over TWO sources, which is the whole point: the live session's lastActiveAt against its createdAt when the pool holds it, and the persisted entry's when it does not. That second arm is DormantSettingsFor's shape and exists for the same reason (#2448/#2449) — after a daemon restart New materialises only the bootstrap, so every per-conversation session is a persisted entry with no *Session behind it, and a reader that consulted p.sessions alone would answer "never run" for every channel the daemon holds a record of.

THE TIMESTAMP PAIR IS AN EXACT READING, not a tolerance. buildSession stamps createdAt and lastActiveAt from one now value, so a never-activated session has them equal to the nanosecond; and every writer of lastActiveAt afterwards — Session.transitionTo, Session.touchLastActive, Session.beginEvict and rekeyLocked — fires only on an activation, an eviction or a rotation, none of which a minted-and-untouched session reaches. Both fields are already in registryEntry, so nothing here is a schema change and no migration exists: a channel that ran before this method did already carries the distinguishing pair.

THE READING SURVIVES A MATERIALISATION, and only because materialise carries a retired dormant entry's created_at/last_active_at onto the session it registers. That dependency is worth stating rather than leaving to be re-derived, because buildSession stamps a FRESH equal pair: without the carry a revived-but-not-yet- activated session answers false here while its own retired entry said true, and the retirement has already taken the dormant arm's fallback with it. /clear reaches this method in precisely that state — its route revives for binding validation before the intercept raises the reset — so a future edit that drops the carry does not merely lose an age field, it re-opens #2521 on that route.

ITS ONE BLIND SPOT, named rather than papered over: the bootstrap session warm-starts in stateActive straight from its persisted row without a transition, so a bootstrap whose timestamps still read equal answers false even while its child is up. Every caller today asks only about a session with NO LIVE CHILD, where that reading is the right one anyway; a caller that wants "is it running" wants State().ChildPID, which is a different question.

The empty id is refused BEFORE either map read. That is the #678 isolation point resolveBoundSession documents: Pool.Lookup("") resolves to the BOOTSTRAP session, and a reader that let the empty id through would answer a question about the daemon's shared child instead of the caller's. No id validation beyond that and no logging, SettingsFor's and DormantSettingsFor's posture verbatim — a malformed id is a map miss, which is already the correct answer, and nothing about it reaches a log line.

Concurrency: safe from any goroutine. Lock order Pool.mu (read) → Session.lcMu, the order List, saveLocked and pickLRUVictim already keep; no new edge.

func (*Pool) GetOrCreate added in v0.9.0

func (p *Pool) GetOrCreate(ctx context.Context, id SessionID, label string) (SessionID, error)

GetOrCreate is the take-or-create entry point: returns the canonical SessionID of the session keyed by id, creating one if none is registered. The returned SessionID is exactly id on success.

id MUST be a canonical UUIDv4 string (matches NewID's output shape). Empty id and malformed strings return ErrInvalidSessionID.

The "exists" path is a constant-time map lookup that returns without activating the session. Subsequent Activate is the caller's responsibility.

The "create" path is byte-equivalent to Pool.Create except the caller's id is used in place of NewID's output, and the register+persist+supervise sequence is held under p.mu. Two concurrent calls for the same id produce exactly one registry entry — the loser observes the winner's entry under p.mu and returns the canonical id with no error. The lifecycle goroutine for the new session is scheduled before the winner's GetOrCreate returns; the loser's later Activate is therefore safe.

Concurrency: safe for concurrent use. Concurrent calls for different ids serialise only briefly through p.mu.

Returns:

  • id, nil — session is registered (existed before, or this call created it)
  • "", ErrInvalidSessionID — id is empty / not a canonical UUIDv4
  • "", ErrPoolNotRunning — no errgroup wired (Pool.Run has not started or has exited)
  • "", <other> — supervisor.New, saveLocked, or Activate error (creation path)

On the create path, an Activate failure returns id (the entry is registered and lifecycle goroutine is scheduled) plus the underlying error — same shape as Pool.Create.

func (*Pool) GetOrCreateIn added in v0.15.0

func (p *Pool) GetOrCreateIn(ctx context.Context, id SessionID, label, spawnDir string) (SessionID, error)

GetOrCreateIn is GetOrCreate with an explicit per-session spawn working directory, applied only on the *create* path. On the take path (session already registered) spawnDir is ignored — the existing session keeps its own workdir, mirroring how the take path already drops the caller's label (see below). spawnDir == "" spawns in the shared template workdir, byte-identical to GetOrCreate; a non-empty spawnDir is used verbatim and is NOT validated, canonicalised, or trust-checked by the pool (see #685).

Otherwise identical to GetOrCreate: see its docstring for the full take/create semantics, concurrency, and return shapes.

func (*Pool) HandoffNote added in v0.19.0

func (p *Pool) HandoffNote(id conversations.ConversationID) (string, error)

HandoffNote returns the handoff note of the conversation id names, or "" when there is none.

It is TOTAL over absence, conversationPrompt's posture: the first reset of any conversation has no predecessor, and that is an ordinary state rather than an error. An absent note and an empty one are therefore indistinguishable here, which is correct for the reading consumer — both compose the same wrap-up prompt — and Pool.HandoffNotePath is where the existence question is asked. Persistence disabled likewise returns "": no store, so no note. A read that fails for any OTHER reason IS an error; a caller asking for the note is entitled to know the disk refused.

THE RETURNED TEXT IS UNTRUSTED. It is claude-authored, it crossed the subprocess boundary, and this store judged its SIZE and its MODE and nothing else — no UTF-8 repair, no control-character filter, no trimming. That is deliberate: what may appear in a composed prompt belongs to the composing site, and validating here as well would put a second opinion in a second place (composeSystemPrompt's argument for operator bytes). The obligation is therefore the caller's, and it is not theoretical: a composing site must place these bytes the way clientSection places a client's, and admissibleClientField is the precedent for what that costs. The string type carries none of this, which is why the doc does.

The read is bounded at MaxHandoffNoteBytes+1 and passed through the same truncation as the write, so a file larger than the cap — one this store did not write — yields a bounded, rune-safe answer instead of an allocation sized by corruption or by whoever planted it.

Concurrency: reads immutable registryPath; the atomic rename prevents partial reads.

func (*Pool) HandoffNotePath added in v0.19.0

func (p *Pool) HandoffNotePath(id conversations.ConversationID) (string, bool, error)

HandoffNotePath reports where the conversation's handoff note would be and whether one is there, WITHOUT reading the text. It is #2468's method: the pointer line it composes names the path and is omitted entirely when there is no note, so it needs both answers and neither requires the bytes.

The path is returned even when nothing is there, because it is derivable either way and an absent note is not an error — that is what lets the caller branch on exists rather than on err. Persistence disabled is the one case that yields no path, since without a data dir there is nowhere a note could be.

It answers os.LSTAT and reports anything that is not a regular file as ABSENT. That is the correct predicate for the question rather than an added defence: a symlink is not a note this store wrote, and os.Stat would follow one — a link planted at this path would otherwise report a note and hand the caller a path it then names to claude, which has file-read tools. What actually bounds that is the 0700 note directory, since planting the link requires the daemon's own uid; using Lstat costs one call and removes the need to rely on it alone. The read path deliberately does not grow O_NOFOLLOW, which is syscall-level and platform-dependent for a boundary the directory mode already holds.

The answer is a point-in-time one, and nothing in the design removes a note, so a caller may name the path it got. A future reaper would invalidate that.

Concurrency: reads immutable registryPath; the atomic rename prevents partial reads.

func (*Pool) HarnessFor added in v0.27.0

func (p *Pool) HarnessFor(id SessionID) (string, error)

HarnessFor returns the coding agent the session id runs — the live session's own harness, else its dormant entry's, canonical in both cases so an entry with no key answers HarnessClaude — or ErrSessionNotFound when this pool holds id in neither half (#2629). The settings gate reads it to check a model and an effort against the entries of that agent rather than of claude alone.

Live first, under one read lock, so the two halves are consulted as one partition rather than across a revive window. The harness itself cannot change under a caller: it is construction-fixed on a Session and carried from the entry by a revive. The empty id is a miss, not the bootstrap — both maps are read by exact key, unlike Lookup. No id validation and no logging, and the error is returned bare: DormantSettingsFor's posture.

func (*Pool) List

func (p *Pool) List() []SessionInfo

List returns a snapshot of every session in the pool — bootstrap and minted alike — sorted by LastActiveAt descending (most recent first). Ties break on SessionID ascending for deterministic ordering. The returned slice and its elements are deep-copied: callers may mutate freely without affecting pool or registry state.

The bootstrap entry's Label field is the synthetic string "bootstrap" when the on-disk label is empty; the on-disk registry entry is NOT mutated by this substitution. Non-empty bootstrap labels (operator-set) pass through verbatim.

Read-only: this method does not bump LastActiveAt, transition lifecycle state, or persist anything. Safe for concurrent use; takes Pool.mu (read) and each Session.lcMu briefly.

Lock order: Pool.mu (RLock) → Session.lcMu (Lock). Same order as Pool.saveLocked and Pool.pickLRUVictim — no new lock-order edges.

func (*Pool) Lookup

func (p *Pool) Lookup(id SessionID) (*Session, error)

Lookup resolves a SessionID to a Session. An empty id resolves to the default (bootstrap) entry — this is the mechanism that lets the Phase 1.0 control plane (after Child B) call Lookup(req.SessionID) with the currently-empty field, and Phase 1.1 populates the field with no handler diff. A non-empty unknown id returns ErrSessionNotFound.

func (*Pool) MarkHandoffNoteStale added in v0.38.0

func (p *Pool) MarkHandoffNoteStale(id conversations.ConversationID) error

MarkHandoffNoteStale invalidates the previous note before a reset attempts wrap-up, without changing its bytes. Persistence-disabled operation is inert. Errors carry paths and must not be logged by the caller.

func (*Pool) Mint added in v0.16.0

func (p *Pool) Mint(label, spawnDir string) (SessionID, error)

Mint registers a fresh session — mint an id, build it, persist it, schedule its lifecycle goroutine — WITHOUT spawning claude. The returned session is in the evicted state with its goroutine parked on the activate signal, which is byte-for-byte the shape an idle-evicted session has, so the child comes up on the caller's first Pool.Activate through the existing lazy-respawn path. It adds no lifecycle path; it only stops one step short of Create's.

The absent context.Context is the API signal for that, as it is on Revive: Mint does no blocking work and cannot spawn.

It exists because create_conversation must bind a session id to a fresh conversation without starting a process for a discussion nobody has spoken in — and, the load-bearing half, so that every per-session setting chosen before the first message is simply what the child launches with, instead of an in-band correction applied to an already-running child (#2085).

spawnDir is the per-session spawn working directory, used verbatim and NOT validated, canonicalised, or trust-checked by the pool — callers supply a pre-resolved, $HOME-confined realpath, exactly as CreateIn, GetOrCreateIn and Revive require (#685/#696). spawnDir == "" spawns in the shared template workdir. SECURITY: it is a phone-influenced workspace path, so it must never be logged (the #741 precedent for session ids and conversation ids); nothing here logs, and nothing added here should.

A minted session carries mintSettings — the operator's configured model and effort, never the bypass (#1575). That is the one thing separating it from Revive, which inherits nothing.

Returns:

  • id, nil — registered, persisted, and scheduled
  • "", err — the failure was at or before the persist; nothing is on disk and nothing in memory changed
  • id, ErrPoolNotRunning — the registry entry IS on disk but no lifecycle goroutine was scheduled (fix and retry by calling Run + Activate)

Concurrency: safe for concurrent use. Each call serialises through Pool.mu briefly (registration + persist), then supervises off-lock.

It mints a claude session; MintAs is the same for any harness.

func (*Pool) MintAs added in v0.27.0

func (p *Pool) MintAs(label, spawnDir, harness string) (SessionID, error)

MintAs is Mint for a given harness (#2647), which buildSessionAs carries onto the session and saveLocked persists on its registry entry, so a restart revives it as the same agent. The pool does not validate the harness: the injected factory decides which harnesses have a runner, and refusing one fails the mint as an ordinary runner-construction error with nothing registered.

Only a claude session starts from mintSettings. The operator's configured model and effort are claude's, so any other harness starts with none and runs at its own defaults.

func (*Pool) MintDefaults added in v0.28.0

func (p *Pool) MintDefaults(harness string) SessionSettings

MintDefaults answers the settings MintAs starts a session of harness on: a claude session starts at the operator's configured model and effort (#1575), any other harness at its own defaults (#2647). It is the one definition of what a mint gives, read by MintAs and by a caller composing settings for MintWith (#2665), so the two cannot drift. Posture is never included — see mintSettings.

Since #2492 mintSettings is an already-locked reader, so the RLock is taken here rather than inside it, and released before any build, which must stay off p.mu. The window that leaves — a concurrent Pool.UpdateSettings on the BOOTSTRAP between this read and a mint's registration — is the pre-existing, benign one every lock-releasing settings accessor carries: it changes what a new session inherits, never what an existing one holds.

func (*Pool) MintWith added in v0.28.0

func (p *Pool) MintWith(label, spawnDir, harness string, settings SessionSettings) (SessionID, error)

MintWith is MintAs starting the session on settings, used verbatim (#2665): create_conversation's requested model and effort are the session's stored settings from the mint, so its first turn carries them with no second write that a refusal could leave half done. Callers pass no posture — a mint is never a bypass grant — which the one caller outside this package guarantees by copying only Model and Effort.

This entry point does NOT go through materialise and needs none of its #2492 machinery: id comes fresh from NewID, so it can name no dormant entry and no dormant write can race it.

func (*Pool) PublishSwitchTransition added in v0.29.0

func (p *Pool) PublishSwitchTransition(oldID, newID SessionID, metadata ...SwitchTransitionMetadata)

PublishSwitchTransition publishes one committed switch after inactive reset status, without rebinding or persisting again. Metadata is optional for existing callers. The dedicated publisher may wait with daemon cancellation; ordinary observers remain nonblocking. Empty/equal pairs describe no session change.

func (*Pool) Ready added in v0.16.0

func (p *Pool) Ready() <-chan struct{}

Ready returns a channel closed once Pool.Run has wired its supervisor handle and supervised the bootstrap — i.e. once Pool.Create will schedule the new session instead of returning ErrPoolNotRunning. Before Run is ever called the channel is open (never ready). Closed exactly once; safe to select on repeatedly and from multiple goroutines.

func (*Pool) Remove

func (p *Pool) Remove(ctx context.Context, id SessionID, opts RemoveOptions) error

Remove terminates the named session's claude process (if running), drops its registry entry, and applies opts.JSONL to the on-disk transcript file.

opts.JSONL == JSONLLeave (zero value): JSONL untouched (1.1d-A1 behaviour). opts.JSONL == JSONLArchive: mv <claudeSessionsDir>/<uuid>.jsonl into

<pyry-data-dir>/archived-sessions/<uuid>.jsonl. Subdir is auto-created.
Errors (wrapping fs.ErrExist) if the destination already exists.
Source-absent is a no-op.

opts.JSONL == JSONLPurge: rm <claudeSessionsDir>/<uuid>.jsonl. Source-absent

is a no-op (per AC: intent is "ensure the file is gone").

Returns ErrSessionNotFound for an unknown id, ErrCannotRemoveBootstrap for the bootstrap entry, or ctx.Err() if termination is cancelled. On any of those error paths, the in-memory pool, on-disk sessions.json, and the JSONL on disk are byte-identical to their prior state — the disposition policy is applied AFTER the registry-remove + persist completes successfully.

Returns only after the child has exited (modulo ctx cancellation).

Ordering — delete-then-dispose-then-evict. Pool.mu is taken (write) for the in-memory delete + saveLocked + JSONL disposition (single critical section, single observable transition), then released BEFORE calling sess.Evict. The alternative (holding p.mu across Evict) deadlocks: Session.transitionTo calls Pool.persist, which reacquires p.mu.

On saveLocked failure, the in-memory delete is rolled back so the disk and memory remain consistent (mirrors Pool.Rename); JSONL is untouched and the child is not terminated. On disposition failure, the registry entry stays removed (already persisted), the disposition error is returned, and the child is still terminated via Evict. If both disposition and Evict fail, the disposition error wins (it is the new failure mode this signature introduces, and the more actionable one).

Lifecycle goroutine after Remove: close(sess.removedCh) signals the session's Run loop to exit promptly. Once Evict drives active→evicted (or the session is already evicted), Run parks in runEvicted, observes the closed removedCh, and returns nil — never through the shared errgroup, so no other session or the relay leg is torn down. The goroutine and everything it captures are released at Remove time rather than surviving until pool shutdown (the bounded-cost note from #94 no longer applies).

func (*Pool) Rename

func (p *Pool) Rename(id SessionID, newLabel string) error

Rename updates the named session's label and persists the change to the registry. Empty newLabel is permitted and clears the on-disk label to ""; Pool.List's synthetic "bootstrap" substitution continues to apply when the bootstrap's on-disk label is empty.

Returns ErrSessionNotFound when id is not present in the pool. On the not-found path the in-memory registry and the on-disk sessions.json are byte-identical to their prior state — saveLocked is not invoked. A no-op rename (newLabel equals the current label) also skips saveLocked, keeping the registry mtime stable.

Concurrency: takes p.mu (write) for the read-modify-write and holds it across the persisted file write, matching the RotateID/saveLocked invariant. Concurrent Pool.List/Lookup/Snapshot calls block on Pool.mu briefly; nothing else needs synchronisation.

Lock order: Pool.mu (write). Does not take Session.lcMu — Session.label is guarded by Pool.mu (the only other readers are List and saveLocked, both under Pool.mu).

func (*Pool) ResolveID

func (p *Pool) ResolveID(arg string) (SessionID, error)

ResolveID maps a user-supplied UUID-or-prefix string to the canonical SessionID of a session in the pool. Empty arg returns the bootstrap session's id (same seam as Pool.Lookup("")).

Resolution order:

  1. arg == "" → bootstrap id, no error.
  2. arg is an exact key in the in-memory session map → that id, no error. This short-circuit is a single map lookup; it never falls through to the prefix scan, so an exact full-UUID match wins even if the same string would also be a HasPrefix hit on the same session.
  3. otherwise, scan the in-memory map and collect every session whose SessionID has arg as a prefix (strings.HasPrefix). Exactly one match → that id, no error. Zero matches → ErrSessionNotFound. Two or more → ErrAmbiguousSessionID with a list of matches in the wrapped message.

No minimum prefix length is enforced. A one-character prefix is accepted when it is unique; refusing short prefixes is a CLI-layer policy concern, not a pool invariant.

Concurrency: takes p.mu (RLock) for the entire resolution. The in-memory map is the source of truth — sessions.json is not re-read. Concurrent Pool.List/Lookup/Snapshot share the read lock; concurrent writers (Rename/Create/Remove/RotateID/saveLocked) serialise behind the write lock as today.

Lock order: Pool.mu (RLock) only. Does not take Session.lcMu — `id` and `label` are guarded by Pool.mu (RotateID and Rename mutate them under Pool.mu write), so no torn reads.

func (*Pool) Revive added in v0.16.0

func (p *Pool) Revive(id SessionID, label, spawnDir string) (*Session, error)

Revive materialises a persisted-but-dropped session back into the pool WITHOUT spawning claude. Pool.New builds exactly one *Session from sessions.json — the bootstrap — so a conversation bound to a minted session points at an id the pool does not have after a daemon restart; this is the entry point that puts that id back (#1487).

The returned Session is in the evicted state with its lifecycle goroutine scheduled and parked, which is byte-for-byte the shape an idle-evicted session has. It therefore respawns on the next Pool.Activate through the existing lazy-respawn path — reviving adds no new lifecycle path, and the caller must Activate to bring claude up.

The absent context.Context is the API signal for that: Revive does no blocking work and cannot spawn. Everything else — id validation, the register + persist + rollback critical section, the ErrPoolNotRunning guard — is shared verbatim with GetOrCreateIn via materialise, whose docstring carries the concurrency contract.

spawnDir is the revived session's spawn working directory, used verbatim and NOT validated, canonicalised, or trust-checked by the pool — the caller supplies a pre-resolved, $HOME-confined realpath, exactly as CreateIn and GetOrCreateIn require (#685/#696). spawnDir == "" spawns in the shared template workdir. SECURITY: it is a phone-influenced workspace path, so it must never be logged (the #741 precedent for session ids and conversation ids); nothing here logs, and nothing added here should.

A revived session also carries its dropped entry's CREATED_AT and LAST_ACTIVE_AT, through the same materialise critical section that retires the entry (#2521). The pair is what Pool.EverActivated reads, so a revive that restamped it to now would answer "never run" for a channel whose own record said otherwise — and the entry holding the truth is gone by then. It also keeps a session's age stable across a restart, which the pre-#2521 restamp silently reset.

A revived session carries the MODEL AND EFFORT its own dropped entry persisted, and NO POSTURE (#2448). Pool.revivedSettings reads the two fields off p.dormant; a persisted yolo or permission_mode is not read at all, so it cannot reach the revived session however the entry was written. An id with no persisted entry yields the zero value, i.e. exactly what every revive got before.

The split is deliberate and is the amendment to ADR 035, which decided the revived session carries zero settings outright. A restart stays a natural revocation point for a permission bypass and re-granting is one settings verb away (#1487) — but model and effort carry no privilege, and dropping them only made the next turn after a restart run under claude's defaults instead of the settings the channel was visibly set to. Nothing new carries them to the child: buildSession already composes claudeSettingsArgs(settings) into the spawn argv, so --model (as the family alias, #2447) and --effort are on the first spawn the caller's Activate brings up.

Since #2065 the posture's revocation is a DOWNGRADE rather than an omission, and the distinction is worth reading. canonicalSettings turns the unset mode into the default posture, and claudeSettingsArgs puts --dangerously-skip-permissions on every argv, so the revived child LAUNCHES in bypass and is walked back to default in-band before any user turn can reach it (internal/streamsup's spawn-time write, held behind its posture gate). The #1487 property is unchanged — a revived session is not escalated — but what enforces it moved from "the flag is absent from the argv" to "the write was confirmed".

Returns:

  • sess, nil — id is registered (existed before, or this call registered it)
  • nil, ErrInvalidSessionID — id is empty / not a canonical UUIDv4
  • nil, ErrPoolNotRunning — no errgroup wired (Pool.Run has not started or has exited)
  • nil, <other> — buildSession or saveLocked failed; nothing is registered

On the take path (id already in the pool) the existing *Session is returned unchanged and label/spawnDir are dropped, mirroring GetOrCreateIn — a revive racing a live session must never replace it.

Concurrency: safe for concurrent use. Two callers racing the same id both receive the same *Session; exactly one registration happens.

func (*Pool) RotateBootstrapForSelfHeal added in v0.16.0

func (p *Pool) RotateBootstrapForSelfHeal() (SessionID, error)

RotateBootstrapForSelfHeal rekeys the current bootstrap onto a minted ID, captures/rebinds its owner and emits an internal recovery fact off-lock. It has no production caller or automatic recovery policy. Recovery has no legacy reason, so it creates no client delimiter or legacy history boundary. Persistence is best effort; missing bootstrap entries emit nothing.

func (*Pool) RotateForNewSession added in v0.16.0

func (p *Pool) RotateForNewSession(oldID SessionID) (SessionID, error)

RotateForNewSession rekeys a session onto a freshly minted ID, rebinds its owner, recomposes its prompt before return/fan-out, and emits an operator reset. The signature remains usable as the daemon's existing rotation callback.

func (*Pool) RotateForNewSessionWithHandoff added in v0.38.0

func (p *Pool) RotateForNewSessionWithHandoff(oldID SessionID, outcome *string) (SessionID, error)

RotateForNewSessionWithHandoff optionally captures a caller-supplied outcome. Absent IDs and mint failures emit nothing; Save errors retain the in-memory mutation and notify. No daemon handoff outcome source is wired here.

func (*Pool) RotateID

func (p *Pool) RotateID(oldID, newID SessionID) error

RotateID atomically replaces the in-memory entry keyed by oldID with one keyed by newID, updates the bootstrap pointer if oldID was the bootstrap, and persists. p.mu is held (write) across the whole operation, matching the 1.2a saveLocked invariant.

Returns ErrSessionNotFound if oldID is unknown. Returns the save error verbatim if persistence fails — the in-memory rotation is already applied at that point; callers decide whether to treat the save error as fatal. RotateID(x, x) is a no-op.

Invariant: sess.id is guarded by two locks — the write below holds BOTH Pool.mu (W, via the function-level defer) and Session.lcMu; a read is race-clean while holding either one. Lifecycle goroutines read it via currentID() (Session.lcMu); Pool.mu-holders (List, ResolveID, Snapshot, saveLocked, Activate) read it directly. The old "no concurrent reader exists" claim went stale in #839 and MUST NOT be restored now that #2137 has retired the rotation watcher that made it stale: a re-key still races the lifecycle goroutines, only from a different goroutine. AdoptAnnouncedID — the sibling that carries the announced-reset rotation — re-keys from the follower's decorator on the runner's parse goroutine, which runs concurrently with the per-session lifecycle goroutines exactly as the watcher's did. lastActiveAt shares the same lcMu section. Lock order remains Pool.mu → Session.lcMu.

No production caller remains since #2137 (the watcher was the last one). RotateID is kept deliberately: it predates the watcher, is exported, and is the seam ~40 test references across five files drive. Removing it is a separate call, not a side effect of retiring its last caller.

func (*Pool) Run

func (p *Pool) Run(ctx context.Context) error

Run blocks until ctx is cancelled, supervising every session in the pool and running the conversations auto-archive sweep loop (when ConversationsRegistry is set) alongside it. errgroup ties the goroutines together: cancellation propagates, and Wait returns the first non-nil error.

Until #2137 this also ran an fsnotify rotation watcher over ClaudeSessionsDir, which guessed at which session had rotated by asking the OS which transcript each tracked pid held open. claude announces the fact directly now (conversation_reset, #2134/#2135/#2136), so the guess and its goroutine are gone; AdoptAnnouncedID carries the rotation instead.

Phase 1.1+ extends the fan-out to one supervisor.Run goroutine per session — the errgroup wrapper introduced here is the extension point.

func (*Pool) SetClientIdentityResolver added in v0.16.0

func (p *Pool) SetClientIdentityResolver(r ClientIdentityResolver)

SetClientIdentityResolver installs the pool's client-identity resolver; a nil resolver (the zero value, or an explicit nil) disables client naming, which is the shape foreground mode, v1, and almost every test in this package run in.

The value is held in an atomic rather than a plain field, which is where this departs from SetTransitionObserver's otherwise identical pre-Run contract. The reason is concrete: the install happens inside startRelayV2, and the relay manager's own Run goroutine is ALREADY started by then. Run creates a per-conn appFrameWorker on every handshake, and that worker is one of the goroutines that reaches Pool.Activate — so a conn completing its handshake in the window between mgr.Run and this call would read the field concurrently with this write. The window is narrow and the race is real; an atomic closes it for four lines and removes the need to reason about the ordering at all. Do not "simplify" it back to a plain field.

func (*Pool) SetDaemonInstructions added in v0.32.0

func (p *Pool) SetDaemonInstructions(text string) error

SetDaemonInstructions preserves valid text verbatim, including an empty clear. Persistence completes before memory publication. It never touches a session or its prompt file; edits apply at the next composition/start. It takes no p.mu.

func (*Pool) SetSwitchTransitionPublisher added in v0.37.0

func (p *Pool) SetSwitchTransitionPublisher(publish func(SessionTransition))

SetSwitchTransitionPublisher installs the switch-only delivery owner before Run. It receives the observer's signal, which must not also enqueue switch wire outcomes. The callback may wait but must honor daemon cancellation.

func (*Pool) SetTransitionObserver added in v0.15.0

func (p *Pool) SetTransitionObserver(obs TransitionObserver)

SetTransitionObserver installs the observer before Pool.Run. Its readers are Run's descendant goroutines; the field must remain read-only after Run starts.

func (*Pool) SettingsFor added in v0.16.0

func (p *Pool) SettingsFor(id SessionID) (SessionSettings, error)

SettingsFor returns the named session's currently-persisted SessionSettings (model, effort, YOLO), or ErrSessionNotFound if the pool holds no session under that id. It is the read half matching UpdateSettings' per-session write: before it, an outside caller could change any session's settings but could read only the bootstrap's, via DefaultSettings.

SessionSettings is a value type, so the return is a snapshot copy and not a lease on pool state — no caller can mutate a session through it, and the copy may be one concurrent UpdateSettings stale by the time it is read. That staleness is inherent to any lock-releasing accessor and is the contract DefaultSettings and mintSettings already carry.

The empty id is deliberately NOT special-cased: it misses p.sessions like any other unknown id and gets ErrSessionNotFound. That puts this method on UpdateSettings' side of an in-package disagreement and declines Lookup's convention, where "" resolves to the bootstrap. Read and write must agree, or a caller passing "" reads the bootstrap's settings and writes nowhere. The bootstrap is registered under a real UUID, so "" is never a key.

No id validation: unlike writeMCPSettings, the id here names no file and never leaves the map lookup, so a malformed id is a map miss — already the correct answer. The error is returned bare rather than wrapped with the caller's id (as UpdateSettings returns it, and unlike ambiguousError, which echoes only ids already resident in the pool), so a hostile or malformed id cannot be reflected into a log line or wire frame a consumer builds from the error.

Read-modify-write warning for consumers: a caller that reads this triple and then calls UpdateSettings must send only the fields it intends to change. Echoing the whole snapshot back re-asserts a YOLO posture an operator may have cleared in the interval — SettingsUpdate's pointer-per-field presence contract makes sending one field the easy path, and this is the trap mintSettings avoids by rebuilding its literal field by field.

Concurrency: MUST be called with p.mu unheld — one RLock acquisition per call, with no second lock and no delegation to DefaultSettings, whose own RLock would double-acquire. Go's RWMutex is not reentrant, so either shape self-deadlocks as soon as a writer queues between the two acquisitions; this is the hazard mintSettings' docstring already records. Reads sess.settings under p.mu (RLock) and deliberately NOT Session.lcMu — settings is a p.mu-guarded field (writer UpdateSettings holds p.mu write; the other reader saveLocked holds p.mu), so there is no torn read.

DefaultSettings is not made redundant by this and must not be rewritten to call it: SettingsFor(p.BootstrapID()) is TWO acquisitions with a rotation window between them — RotateID can flip p.bootstrap under the write lock after the first returns — so the composed form can read a session that is no longer the bootstrap. DefaultSettings resolves p.bootstrap and reads settings under a single acquisition and stays the atomic way to ask for the bootstrap's settings.

func (*Pool) Snapshot

func (p *Pool) Snapshot() []SnapshotEntry

Snapshot returns one entry per session, capturing the current supervisor.State().ChildPID. PID == 0 means no live child. Safe for concurrent use; takes RLock only.

func (*Pool) SystemPromptFor added in v0.16.0

func (p *Pool) SystemPromptFor(id SessionID) (string, error)

SystemPromptFor returns the operator-set system prompt bytes the named session was actually spawned with — what a later slice compares against the stored value to tell an operator that a running session predates their edit (#2152).

It reports the OPERATOR half, not the composed text: composing is this package's business, and returning the whole would make the caller strip a constant it does not own in order to compare. "" means the session was spawned with no appended operator text, which is both of #2149's no-bytes states.

Deliberately in-process and unexported to the wire: #2150 adds no control-plane verb and no frame. #2152 is the ticket that puts this on the wire.

Concurrency: MUST be called with p.mu unheld — one RLock acquisition, the same shape and the same non-reentrancy hazard SettingsFor documents.

func (*Pool) UpdateDormantSettings added in v0.19.0

func (p *Pool) UpdateDormantSettings(id SessionID, update SettingsUpdate) error

UpdateDormantSettings merges update's Model and Effort into id's dormant registry entry and persists it, or returns ErrSessionNotFound if this pool holds no dormant entry under that id. It is UpdateSettings' dormant half: the two partition the ids the daemon has a record of, on the same basis DormantSettingsFor and SettingsFor partition them.

It exists so set_session_settings can land on a conversation this daemon has not materialised (#2463). Pool.New materialises only the bootstrap, so after a restart that is EVERY conversation until its first message revives it, and a model or effort chosen before that message was refused with session.not_found while the menus the client had just rendered said otherwise (#2449 fixed the read and made this reachable).

A SECOND WRITE rather than a fallback folded into UpdateSettings, for the reason DormantSettingsFor records one layer up and one more of its own. Folding it in would change what ErrSessionNotFound means for every other caller of the live write, several of which use exactly that answer to decide a session is not addressable. And UpdateSettings' body past its persist is entirely about a live session — the recomposed argv, the posture install, the in-band delivery, the supervisor capture — none of which has a dormant analogue.

IT MATERIALISES NOTHING, deliberately, and that is a contract rather than an implementation detail. #2449 AC 3 made the settings READ materialise nothing so that N channel activations cannot become N sessions; the write rides the same frame family on the same restart edge, and a client that re-asserts its footer state on activation would otherwise wake every channel it touched. Reviving here is also not available on its own terms: Pool.Revive needs a spawn directory to re-validate through the caller's $HOME confinement, this seam is keyed by SESSION rather than by conversation, and a session no conversation binds has no Cwd at all.

THE POSTURE IS REFUSED, NOT PERSISTED, and the refusal is honesty rather than caution. Both readers of p.dormant build the posture structurally from Model and Effort alone — revivedSettings never looks at the entry's yolo or permission_mode, and DormantSettingsFor derives the default from the same two fields — so a persisted posture is invisible to both, and accepting one would report success for a change the very next read contradicts. Making it visible instead would mean teaching the revive to read a persisted posture back, and the disk cannot tell a posture granted after a restart from one granted before it, so that would resurrect exactly the bypass a restart revokes (#1487, ADR 035 as amended by #2448). Carrying a NON-ESCALATING mode across a revive is a real option and a security decision of its own; it is not this method's.

The exclusion is doubled rather than singled: the refusal below returns before any mutation, AND the merge names Model and Effort literally, so a posture could not reach the entry even if the guard were deleted. That is mintSettings' and revivedSettings' recorded discipline — a field added to registryEntry later is not carried until someone opts it in — applied to a write.

VALIDATING THE VALUES IS NOT THIS METHOD'S JOB, exactly as it is not UpdateSettings'. It operates on operator-trusted input. The relay handler owns the charset and length shape check for Model and the closed enum for Effort, and for a non-empty model cmd/pyry's settingsUpdaterAdapter then owns the membership check against the retained published vocabulary before this method can write anything. A written Model becomes the revived child's --model, so a caller that skips that gate is handing an unvalidated value to an argv sink.

Carried over from UpdateSettings' shape: a no-op returns success without rewriting the registry (compared on the two scalar fields rather than on the whole entry, which embeds time.Time values whose == compares representation rather than instant), and a failed save restores the previous entry.

Concurrency: MUST be called with p.mu unheld — one Lock acquisition, no delegation to another locking accessor, UpdateSettings' contract verbatim. The lookup, the merge and the save all run inside that one critical section, so there is no check-then-mutate gap of this method's own. Never takes Session.lcMu; p.dormant is a p.mu-guarded field like sessions and label.

ONE WINDOW OUTSIDE IT, bounded by p.dormant only ever shrinking: a caller composing this after a live write (settingsUpdaterAdapter) can have a revive land between the two. The id can only move live-ward, so this method finds a CLEAN MISS rather than a torn entry, and answers ErrSessionNotFound. That refusal is correct rather than merely safe: the settings were applied to nothing. No retry is attempted — the operator's next pick reaches the now-live session through the live write.

The SECOND window this doc used to name is closed (#2492). Pool.Revive evaluated revivedSettings as an ARGUMENT to materialise, so that read's RLock was released before materialise took the write lock and retired the entry, and a write landing in the gap was acknowledged and then dropped — the session materialised under the value read before it. materialise now takes its settings as a source and evaluates it inside the critical section that retires the entry, so a write reaching this method before that section is CARRIED by the revived session and one reaching it after gets ErrSessionNotFound above. Those were always the two outcomes this seam's docstrings reasoned about; what is gone is the third.

No id validation and no logging, DormantSettingsFor's posture verbatim: the id names no file and never leaves the map lookup, so a malformed id is a map miss — already the correct answer — and both errors are returned bare rather than wrapped with it, so a hostile id cannot be reflected into a log line or a wire frame a consumer builds from the error.

func (*Pool) UpdateSettings added in v0.16.0

func (p *Pool) UpdateSettings(id SessionID, update SettingsUpdate) error

UpdateSettings merges the fields marked present in update into the stored settings of session id and re-persists, taking p.mu (write) exactly as Rename does for label. A nil field in update leaves the stored value untouched; a non-nil field overwrites it (including "" for Model/Effort and false for YOLO). An absent (nil) YOLO can never enable bypass — only an explicit non-nil *true does. Returns ErrSessionNotFound for an unknown id, creating no entry. A no-op update (every present field already equal to the stored value, or every field nil) writes nothing to disk, keeping the registry mtime stable. On a saveLocked failure the in-memory settings are rolled back so memory stays consistent with disk.

The permission posture is stored as TWO fields that can never disagree (#2043). validatePermissionUpdate rejects an unrecognised mode (ErrUnsupportedPermissionMode) and a mode contradicting a YOLO in the same frame (ErrPermissionModeConflict) before anything is mutated; what survives derives both fields together:

update carries                          stored mode        stored YOLO
yolo:true                               bypassPermissions  true
yolo:false, stored mode is bypass       default            false
yolo:false, stored mode is anything else unchanged         false
mode bypassPermissions                  bypassPermissions  true
any other known mode                    that mode          false

Row three is the one to read twice: a yolo:false must not drag an operator out of plan and into default as a side effect of naming a field it was not asked about.

After a successful persist of a real change the change is also LIVE-APPLIED to the session's supervisor, by one of two mechanisms picked on what the update carried — which fields, and for the posture its value too (inBandDeliverable):

  • A change claude accepts on the stream the daemon already holds open is delivered IN-BAND (#1581, #1604, #2043, #2066, #2280): model through set_model, effort through an ordinary /effort user turn, and ANY of the six storable postures as a set_permission_mode control request, so the child is neither terminated nor respawned and its transcript survives. That branch still installs the recomposed argv, via SetSpawnArgs — Restart's swap half — because skipping the install would let the operator's change silently revert on the next crash-respawn or evict → Activate. Fire-and-forget; see deliverSettingsInBand.
  • Every other change keeps the live restart (#842): the argv is recomposed from the persisted settings and, if a child is running, that child is killed so the supervisor relaunches it — resuming the conversation — under the new settings. Since #2066 this is the path a model or effort cleared back to claude's own default takes, and nothing else.

The posture split is on the POSTURE ASKED FOR, not on presence, and it is measured rather than assumed. #1595 and #2041 measured the five non-escalating modes on a held-open stream; #2060 measured the ESCALATION the same way, on a child launched with --dangerously-skip-permissions, which #2065 made every child. So all six now apply to the running child with no respawn. Before #2066 the escalation was the exception, because claude refused it in words on a child launched without the flag and only a relaunch under a recomposed argv could grant it; that asymmetry is what this ticket removed, and every caller that modelled it can stop.

For an evicted session neither mechanism finds a child; the argv install alone applies on the next Activate, and the caller still sees success. Both branches run OUTSIDE p.mu (every installer is non-blocking and drives only supervisor-internal state, so the Pool.mu → Session.lcMu order is untouched) and only on a real change: an unknown id, a no-op update, and a persist failure all skip them, so a still-correct running child is never disturbed.

Lock order: release p.mu after persistence, then take sess.spawnArgsMu before re-reading prompt suppression under p.mu. Keep spawnArgsMu through either argv install, with p.mu released before runner calls, and release it before in-band delivery. Does not take Session.lcMu; spawnBase and sup are immutable.

func (*Pool) WriteHandoffNote added in v0.19.0

func (p *Pool) WriteHandoffNote(id conversations.ConversationID, text string) (string, error)

WriteHandoffNote stores text as the handoff note of the conversation id names and returns the absolute path written, REPLACING any previous note for that conversation. text over MaxHandoffNoteBytes is truncated, never refused.

The note is keyed by CONVERSATION, not by session, because it must outlive the session that produced it: a reset replaces the session and the note is for its successor. That is also why nothing removes it — not Pool.Remove, not the `/clear` rotation, not Pool.Run's shutdown defer, and not Pool.New's startup purge, which clears session-prompts wholesale and would take the note with it if the note lived there. Reaping a note whose conversation was deleted is deliberately unbuilt; a note is retained until something is written to do it.

Persistence disabled returns ErrHandoffNotesDisabled. There is no honest success to report there and a silent no-op would claim one; see handoffNotePathFor on why the temp-file fallback its neighbours take does not transfer.

The store LOGS NOTHING — it holds no logger and takes none, so no fragment of a claude-authored note can reach a log line by construction rather than by discipline. Errors name paths and wrap OS errors; none carries note bytes.

Concurrency: serialized by handoffMu, without acquiring lifecycle locks.

type RemoveOptions

type RemoveOptions struct {
	// JSONL selects the on-disk JSONL disposition policy. Zero value is
	// JSONLLeave.
	JSONL JSONLPolicy
}

RemoveOptions extends Pool.Remove with disposition policy. The zero value behaves identically to the 1.1d-A1 (#94) Pool.Remove: terminate the child, drop the registry entry, leave the JSONL on disk.

type Runner added in v0.16.0

type Runner interface {
	State() State
	WriteUserTurn(ctx context.Context, conversationID string, payload []byte) error
	WaitForPTY(ctx context.Context) error
	Run(ctx context.Context) error
	Restart(args []string)
	// SetSpawnArgs installs the argv the runner's NEXT spawn will use WITHOUT
	// terminating a running child — Restart's swap half on its own (#1580), for a
	// caller that needs to change what the session runs next without ending what it
	// is running now. Declining to call Restart is not that path: it loses the swap
	// outright, so the next spawn re-execs the stale argv. Pool.UpdateSettings is
	// its one caller: the in-band branch installs through it and delivers the live
	// change as set_model, /effort, or set_permission_mode instead of a respawn.
	// See (*streamsup.Runner).SetSpawnArgs for the full contract —
	// notably that the argv is installed verbatim, with validation staying upstream
	// in Session.spawnArgs.
	SetSpawnArgs(args []string)
	// SetModel switches the LIVE child's model without killing it and without
	// creating a user turn. The implementation writes one set_model control
	// request to the held-open stream. Model validation belongs to the caller's
	// trust boundary; errors must not echo the model value.
	//
	// It is on this interface because its consumer is deliverSettingsInBand. A
	// capability assertion there would fail open and report a persisted update as
	// live-applied even when the runner could not send it.
	SetModel(model string) error
	// SetSpawnPermissionMode installs the posture the runner's NEXT and every later
	// spawn asserts to its child in-band, without touching the running one (#2064).
	// It is SetSpawnArgs' posture twin and stands in the same relation to
	// SetPermissionMode below that SetSpawnArgs stands in to Restart: one changes
	// what runs next, the other changes what is running now.
	//
	// Pool.UpdateSettings is its one caller, and it calls it on the line ABOVE its
	// branch split — the single point both branches pass through — because neither
	// branch rebuilds the runner. Without it a runner keeps asserting the posture it
	// was CONSTRUCTED with, so a crash-respawn after an operator's change would
	// re-assert the startup posture and can LOOSEN one that was since tightened.
	//
	// The two shapes that look sufficient and are not. Piggybacking the install on
	// SetPermissionMode misses every update that takes the RESTART branch, which
	// never calls that method — since #2066 that is a Model or Effort cleared to ""
	// rather than an escalation, because the escalation now is in-band-deliverable
	// and does reach it; the miss moved, it did not go away, and a piggybacked
	// install would still let a crash-respawn re-assert a stale posture. Deriving the
	// posture from the installed argv was exact until #2065, which takes the mode out
	// of the launch argv entirely.
	//
	// mode is installed VERBATIM AND UNVALIDATED — bypassPermissions included, the
	// empty string included. This is not an operator-input path: callers pass an
	// already-canonical stored posture, and the vocabulary gate that matters runs at
	// the SPAWN, where a mode outside the runner's allow-list means nothing is written
	// and nothing is gated. It returns nothing and cannot fail; it is non-blocking and
	// takes no lock the sessions layer holds.
	//
	// It is ON this interface for SetPermissionMode's reason exactly, and the stakes
	// are higher here: its consumer sits inside internal/sessions, where a structural
	// assertion fails OPEN, and failing open means a respawned child silently
	// asserting a posture the operator has already changed.
	SetSpawnPermissionMode(mode string)
	// SetPermissionMode switches the LIVE child's permission posture without
	// killing it, by writing one set_permission_mode control request carrying mode
	// on the stream the daemon already holds open (#2042 widened #1603's writer;
	// #1595 and #2041 measured the switch live). It is the generalisation of
	// #1604's revoke-only RevokeBypass, which this interface carried until #2043
	// rewrote Pool.deliverSettingsInBand to send an operator-chosen mode: the same
	// line, the same no-respawn delivery, with the mode as a parameter. Leaving
	// both on the seam would have let one revocation emit two identical control
	// requests, since the posture derivation makes a yolo:false update carry a
	// non-bypass mode of its own. (*streamsup.Runner) keeps its own RevokeBypass
	// and its package-level coverage; nothing outside that package calls it.
	//
	// mode is refused unless it is in the runner's closed allow-list — since #2066
	// "default", "acceptEdits", "plan", "auto", "dontAsk" AND "bypassPermissions".
	// Re-granting bypass arrives HERE now rather than on the respawn path: claude used
	// to gate the escalation on the launch argv, #2065 put that flag on every argv,
	// and #2060 measured claude accepting the re-escalation on such a child at
	// 2.1.239. What the list still refuses, by NON-MEMBERSHIP rather than by a
	// deny-list entry, is every mode claude will not parse — near misses of the
	// escalation included.
	//
	// A SUCCESSFUL write retargets the runner's posture gate, so a posture the child
	// NAKs holds that session's turns until another in-band change retargets it. That
	// window has applied to every in-band posture change since #2064; the escalation
	// joined the class rather than creating it, and the operator's remedy — naming any
	// other mode — reaches this same method.
	//
	// The refusal is a distinct, PERMANENT error, and a caller must not treat it as
	// the retryable no-live-child error: the two are errors.Is-distinguishable and a
	// refused mode can never succeed on retry. Neither error carries the rejected
	// mode string, so a caller may log them verbatim — #833 keeps settings values
	// out of the daemon log and a permission mode is a settings value.
	//
	// The allow-list is a VOCABULARY gate, not an authorisation one: it answers
	// whether claude will parse the mode, never whether this caller may change this
	// session's posture. Three of its members loosen a child launched in the
	// daemon's default approval posture, and claude accepts them in-band. A caller
	// taking a mode from a wire frame owns that decision itself.
	//
	// It is ON this interface for SetSpawnArgs' reason exactly — its consumer sits
	// inside internal/sessions, where a structural assertion would fail open: an
	// unmatched arm is a silent no-op, leaving the child in the wrong posture
	// while UpdateSettings reports success, which is the exact regression the
	// in-band delivery exists to prevent. The interface method makes a runner that
	// cannot switch posture a build failure instead.
	//
	// Returns the runner's retryable no-live-child error when nothing is bound.
	// Safe from any goroutine.
	SetPermissionMode(mode string) error
	// BeginTeardown arms the runner's write-refusal gate for a DELIBERATE KILL this
	// package is about to perform (#1513): from the call until the next child binds,
	// every WriteUserTurn is refused with the runner's retryable no-live-child error
	// instead of being written into the child that is about to die. Without it the
	// write lands in the doomed child's stdin pipe and RETURNS NIL, msgqueue reads
	// nil as a confirmed commit and drops the queue head, and the message dies
	// unread — no retry, no session_error, and queue_state reporting it delivered.
	//
	// Three callers, each arming strictly BEFORE the kill it pairs with and before
	// anything that publishes the teardown to clients: both eviction arms of
	// Session.runActive (the idle timer, and the cap/force evictCh that Pool.Remove
	// drives through Session.Evict), and Pool.UpdateSettings' restart branch — the
	// in-band branch beside it MUST NOT call this, since it tears no child down and
	// an arm there would refuse turns for a delivery that kills nothing.
	//
	// It is the deliberate-teardown twin of the runner's own new_session rotation
	// arm, NOT a second caller of it, and the difference is the release rule: a
	// rotation arm must survive a Restart-driven or crash respawn, while these
	// teardowns END IN exactly such a respawn and must be released by it. The
	// implementation owns that distinction; this seam only promises that any
	// successor child ends the window, so a stray arm cannot wedge a session.
	//
	// It returns nothing and cannot fail. It is non-blocking, takes no lock this
	// package holds, and makes no call-out — so it cannot delay the kill that
	// follows it — and it is safe from any goroutine.
	//
	// It is ON this interface for SetSpawnPermissionMode's reason exactly, and the
	// stakes are the same shape: its consumers sit inside internal/sessions, which
	// must not import internal/streamsup (see Pool.deliverSettingsInBand), and a
	// structural assertion there fails OPEN. An unmatched arm would be a silent
	// no-op leaving the teardown ungated while every layer reported success — which
	// is precisely the silent loss this method exists to close. The interface method
	// makes a runner that cannot arm a build failure instead.
	BeginTeardown()
	// Interrupt ends the live child's running turn without killing the child. It
	// returns the runner's retryable no-live-child error when nothing is bound, and
	// callers tolerate its errors: the v2.interrupt route logs and drops them, and
	// the reset wrap-up logs and waits for idle anyway. Safe from any goroutine.
	Interrupt() error
	// RestartFresh rotates the runner's persistent session id to newID and
	// respawns, so the successor starts a fresh transcript under newID rather
	// than resuming or forking the old one. The caller mints newID through the
	// pool's rotation first; this method never chooses an id of its own.
	RestartFresh(newID string)
	// BeginRotation arms the runner's rotation write-refusal gate ahead of a
	// new_session rotation (#1330) and returns the disarm, which is never nil.
	// While armed, WriteUserTurn returns the retryable no-live-child error instead
	// of writing into the outgoing child. The caller disarms only when the
	// rotation fails; a successful rotation's successor child releases the gate.
	// Unlike BeginTeardown's arm, this one must survive the respawn RestartFresh
	// triggers until the successor binds; the implementation owns that rule.
	BeginRotation() func()
}

Runner is the narrow interface internal/sessions dispatches through to drive a supervised claude child (Session.sup). It covers exactly the methods the session lifecycle invokes on that field — no more — so the Streamrunner Interactive work (T4/T7) can inject an alternative runner behind the same lifecycle without widening the seam.

There is exactly ONE production implementation: cmd/pyry's streamRunner adapter, wrapping *streamsup.Runner. The adapter exists because Go has no covariant return on interface satisfaction and the concrete runner's State returns streamsup.State, not sessions.State — see streamRunner's own doc. The compile-time proof lives with it (var _ sessions.Runner = streamRunner{} in cmd/pyry); this file declares no assertion, because the type it would assert about is not in this package. The PTY supervisor this doc used to name is gone — #1348 deleted internal/supervisor — and the only other implementations are the package's test doubles.

Config.RunnerFactory has no default: it is REQUIRED, and a nil factory is a construction error out of New (see RunnerFactory). There is no implicit implementation to fall back to.

Interrupt, RestartFresh and BeginRotation are on this interface although their consumers (cmd/pyry's interrupt, new_session and reset wiring) sit outside this package (#2592). With one implementation they were reached by type assertion, and an unmatched assertion was a silent inert arm. A second runner (Codex) makes that arm reachable: a runner lacking the method would drop an interrupt or a fresh restart while every layer reported success. The interface makes it a build failure instead. Capabilities whose absence is harmless (ModelList, SetSpawnWorkDir and the other cmd/pyry-only reads) stay optional assertions off Session.Runner().

type RunnerConfig added in v0.16.0

type RunnerConfig struct {
	// ClaudeBin is the path to the claude binary. Defaults to "claude" (found on PATH).
	ClaudeBin string

	// WorkDir is the working directory for the claude child process. Empty means
	// the current directory.
	WorkDir string

	// SessionID is the session this runner drives. The stream runner reads it
	// three times: once for the config it builds, and twice to bind the
	// turn-event sink and the exit channel for that session.
	SessionID string

	// AdoptAnnouncedReset re-keys this runner's session onto an id claude
	// announced a reset to, and draws the client's session delimiter (#2135). The
	// pool sets it to a closure over Pool.AdoptAnnouncedID at both RunnerConfig
	// construction sites; a runner built without one (a test pool, or any factory
	// that does not observe resets) gets nil and the caller skips the call.
	//
	// IT TAKES BOTH IDS, and that is what lets it live on a per-session config at
	// all. SessionID above is construction-fixed and, as its own doc says, does not
	// mirror a rotation — so a closure capturing it would be correct for exactly one
	// reset and fail-closed on every one after that. Carrying no identity of its own,
	// this callback stays correct for the session's whole life and the CALLER supplies
	// the live id (cmd/pyry reads it off the runner's streamSessionTag).
	//
	// It is invoked SYNCHRONOUSLY from the goroutine forwarding claude's stdout, so
	// it must not block for long: it takes Pool.mu and fans out to the transition
	// observer, whose own contract already forbids blocking. It is not a place to do
	// I/O beyond the registry save the re-key already implies.
	AdoptAnnouncedReset func(oldID, newID string) error

	// ClaudeArgs is the extra argv passed through to claude.
	ClaudeArgs []string

	// Harness names the coding agent this session runs (#2593), and the factory
	// selects the runner by it. Both pool construction sites set it canonical, so
	// it is never empty from the pool: HarnessClaude for the bootstrap and every
	// minted session, and a dormant entry's own persisted value for a revive. The
	// sessions package carries the value without validating it; the factory is the
	// one place that decides which harnesses have a runner, and refusing one is an
	// ordinary construction error.
	Harness string

	// ThreadID is the harness thread this session resumes, for a harness that
	// mints its own conversation ids (codex, #2622); empty means start one. Only
	// Pool.buildSessionAs sets it, from the dormant entry a revive materialises.
	ThreadID string

	// RecordThread persists a thread the runner STARTED onto the session's
	// registry entry (#2622). Like AdoptAnnouncedReset it carries no identity of
	// its own: the caller passes the live session id, so the callback stays
	// correct across rotations, and an id the pool no longer holds is
	// ErrSessionNotFound. Set by Pool.buildSessionAs; nil elsewhere, and the
	// caller skips it. It takes Pool.mu and writes the registry, so it must not
	// be called with a runner lock held.
	RecordThread func(sessionID, threadID string) error

	// PermissionMode is the session's stored permission posture, written to every
	// spawned child in-band and confirmed before any user turn reaches it (#2064).
	// Both construction sites set it from settings.PermissionMode below a
	// canonicalSettings call, so it is always a real mode and never the empty one.
	//
	// It is the CONSTRUCTION-TIME value only, and it goes stale: Pool.UpdateSettings
	// rebuilds no runner, so a posture changed after startup reaches the runner
	// through Runner.SetSpawnPermissionMode instead. This field seeds; that method
	// updates.
	//
	// bypassPermissions travels here like any other mode, and the stream runner still
	// writes nothing for it AT SPAWN — so a bypass session is sent nothing and its
	// turns are never gated. What changed with #2066 is the mechanism, not the
	// outcome: the runner's writer allow-list admits the escalation now, and the spawn
	// path subtracts it back out (permissionModeSpawnWritable) because the launch argv
	// already asserts the escalation on every child since #2065 and nothing has
	// measured claude answering one as a fresh stream's first control request.
	// Re-granting bypass on a RUNNING child no longer waits for a respawn: it goes
	// in-band through Runner.SetPermissionMode.
	PermissionMode string

	// OperatorBypass reports that the escalation reached this spawn's argv from the
	// OPERATOR's pass-through claude args rather than from this package's own
	// settings composition (#2065). Derived at construction by operatorBypass over
	// the session's settings-free base (Session.spawnBase), which is where the
	// pass-through lands verbatim.
	//
	// It is the PROVENANCE signal, and it exists because #2065 made
	// claudeSettingsArgs append --dangerously-skip-permissions to every argv. Both
	// of the daemon's permission fail-safes used to read that flag off the assembled
	// argv, and both invert into their permissive arms the moment the flag is
	// universally present:
	//
	//   - cmd/pyry's withApprovalArgs skipped the approval-flag injection when the
	//     flag was present, so a universally-present flag deletes the daemon's
	//     approval gate for every session.
	//   - internal/streamsup's spawnAndWait suppressed the spawn-time posture write
	//     when the flag was present, so a universally-present flag leaves every child
	//     in bypass and every posture gate open — the exact inverse of #2065.
	//
	// TRUE means the daemon may NOT walk this child back: asserting a stored mode at
	// a child the operator launched in bypass revokes that escalation in-band and
	// unanswerably, which a live-claude gate caught reddening four specs before the
	// interlock existed. FALSE means every escalation on this session's argv is one
	// this package composed, so the stored PermissionMode above decides the posture.
	//
	// It is CONSTRUCTION-FIXED and, unlike PermissionMode, cannot go stale: spawnBase
	// is immutable post-construction, and every post-construction argv install
	// (Pool.UpdateSettings → Session.spawnArgs → Runner.Restart / SetSpawnArgs)
	// recomposes from that same base. A future caller that installs an argv composed
	// from something other than 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 was not.
	//
	// Nothing a remote client controls can set it. SessionConfig.ClaudeArgs is
	// written at one production site, cmd/pyry's daemon composition from the
	// operator's CLI; Pool.Create, Pool.CreateIn, Pool.GetOrCreateIn and Pool.Revive
	// take only a label and a spawn dir.
	OperatorBypass bool

	// Logger is used for the runner's diagnostics. Optional; nil falls back to
	// the package default.
	Logger *slog.Logger

	// Backoff bounds for the respawn ladder.
	BackoffInitial time.Duration
	BackoffMax     time.Duration
	BackoffReset   time.Duration
}

RunnerConfig controls a runner instance. It is what RunnerFactory receives.

It carries only the fields the stream runner actually reads. The supervisor's Config carried nine more — resume behaviour, a session-id resolver, a bridge, a conversation validator, a transcript resolver, a record directory, two fast-crash thresholds and a self-heal hook — every one of which the stream factory silently dropped on the floor. Keeping them would have advertised behaviour nothing implements.

Two of those dropped fields represent real behaviour the stream path does not have, and they are recorded here rather than quietly lost:

  • SelfHeal, the #1165 fast-crash recovery that minted a fresh pinned session id when a child crash-looped on an existing transcript.
  • ValidateConversation, the unknown-conversation refusal at session build.

Neither has a stream-path equivalent today. If either is wanted back it is a feature on the stream runner, not a field to re-add here.

type RunnerFactory added in v0.16.0

type RunnerFactory func(cfg RunnerConfig) (Runner, error)

RunnerFactory constructs a Runner from a RunnerConfig. It is the injection seam on Config and it is MANDATORY: a nil Config.RunnerFactory is a construction error ("sessions: Config.RunnerFactory is required") out of New, not a fall-back to some default implementation. The PTY default this doc used to describe went away with internal/supervisor (#1348); production supplies cmd/pyry's newStreamRunnerFactory, and the tests supply their own doubles.

The factory is invoked at every construction site (bootstrap in Pool.New and per-session in Pool.buildSession). A returned error propagates through each site's own wrap — "sessions: bootstrap runner: %w" in New, "sessions: create runner: %w" in buildSession. Neither says "supervisor": the shared "sessions: … supervisor: %w" this doc used to quote went away with internal/supervisor (#1348), same as the claims above.

type Session

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

Session is one supervised claude instance plus the bridge that mediates its I/O in service mode. As of 1.2c-A each Session owns a lifecycle goroutine (the body of Run) that drives the active↔evicted state machine.

func (*Session) Activate

func (s *Session) Activate(ctx context.Context) error

Activate moves the session into stateActive if it is currently evicted, blocking until the lifecycle goroutine has started the supervisor AND the post-transition registry persist has completed AND the supervisor has bound its PTY (or ctx is cancelled). Safe from any goroutine; idempotent under concurrent calls.

No early-return for "already active" — callers always wait on activeCh. When the session is fully active and persisted, activeCh is already closed and the receive returns immediately. When a transition is in flight (state flipped, persist still running), the receive correctly blocks until the persist completes and transitionTo closes activeCh.

PTY-readiness wait: after the state flip, runOnce takes a brief window (~hundreds of ms) to allocate the PTY master and call setPTY. Activate waits past that window via supervisor.WaitForPTY so callers that follow Activate with WriteUserTurn/Resize observe a live PTY rather than the silent-drop-on-nil branch. The relay-routed send_message path depends on this guarantee (#396).

Cancellation, in two cases that differ (#1805):

  • A ctx already cancelled or expired at the call returns ctx.Err() immediately, before anything else happens: no signal on activateCh, no supervisor start, no child. That guarantee is hard.
  • A cancellation arriving while the call is waiting also returns ctx.Err(), except that a transition completing at the same instant may win the race and return nil — both select arms are then ready. Callers that need certainty must not rely on this half.

func (*Session) Evict

func (s *Session) Evict(ctx context.Context) error

Evict moves the session into stateEvicted if it is currently active, blocking until the lifecycle goroutine has stopped the supervisor (or ctx is cancelled). No-op when the session is already evicted. Safe from any goroutine; idempotent under concurrent calls.

Used by the cap-policy spawn path (Phase 1.2c-B): when activating one more session would exceed Pool.activeCap, the LRU peer is evicted via this primitive before the new spawn proceeds. Force-eviction — unlike the idle timer, it does not defer while a turn is open. The cap is a hard limit; a running turn is killed with the child.

func (*Session) ID

func (s *Session) ID() SessionID

ID returns the session's stable identifier.

func (*Session) LifecycleState

func (s *Session) LifecycleState() lifecycleState

LifecycleState returns a snapshot of the current lifecycle state. Used by tests and (eventually) status payloads. Safe from any goroutine.

func (*Session) Run

func (s *Session) Run(ctx context.Context) error

Run blocks until ctx is cancelled, driving the session's active↔evicted state machine. The body alternates between runActive (supervisor running, idle timer armed) and runEvicted (no supervisor; waiting for an Activate). A registry write happens after each transition.

func (*Session) Runner added in v0.16.0

func (s *Session) Runner() Runner

Runner exposes the underlying runner as the Runner interface, so a consumer can reach runner-type-specific methods (SendEsc / Interrupt) that are deliberately NOT on the narrow Runner interface (#1077). Unlike Supervisor(), which returns the concrete *supervisor.Supervisor (nil for a stream-json runner), Runner() returns whatever backs sess.sup — total for both runner types. Consumed by cmd/pyry's #1121 interrupt routing, which type-switches the returned runner to its concrete interrupt method. No lock: sup is set once at construction, the same discipline as Supervisor().

func (*Session) State

func (s *Session) State() State

State returns a snapshot of the supervisor's runtime state. Pure delegation to (*supervisor.Supervisor).State. Note: in stateEvicted, the supervisor's phase is PhaseStopped — that is faithful, since the supervisor really isn't running.

func (*Session) WriteUserTurn added in v0.11.0

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

WriteUserTurn delegates to the underlying supervisor. Consumed by the send_message handler via the handlers.TurnWriter interface. ctx bounds the supervisor's ready-gate + commit-confirm delivery; the handler passes a timeout-bounded ctx so a busy/wedged claude surfaces as a loud failure rather than hanging the per-conn goroutine.

type SessionConfig

type SessionConfig struct {
	ClaudeBin  string
	WorkDir    string
	ResumeLast bool
	ClaudeArgs []string

	BackoffInitial time.Duration
	BackoffMax     time.Duration
	BackoffReset   time.Duration

	// IdleTimeout, when positive, causes the session's claude process to
	// exit after the configured period, deferred while Config.TurnBusy
	// reports a turn open (re-checked once per period). The
	// JSONL on disk is preserved; a subsequent Activate spawns a fresh
	// claude that reads the prior conversation. Zero inherits
	// Config.IdleTimeout; if both are zero, eviction is disabled.
	IdleTimeout time.Duration
}

SessionConfig is the per-session invocation shape. Phase 1.0 uses it only for the bootstrap entry; Phase 1.1's `pyry sessions new` populates it for each new session.

Phase 1.0 honours ResumeLast (which maps to supervisor.Config.ResumeLast, i.e. --continue on restart). The locked-design `claude --session-id <uuid>` invocation lands in Phase 1.1+ and is deliberately NOT introduced here (parent spec open question #2: "wait").

type SessionID

type SessionID string

SessionID is a per-session identifier. Locked design uses UUIDs (crypto/rand, 36-char canonical 8-4-4-4-12 form). Phase 1.0 generates one at startup for the bootstrap entry; the wire protocol does not carry it yet (Phase 1.1).

The empty SessionID ("") is the unset sentinel and is never a valid generated ID. Pool.Lookup("") resolves to the default (bootstrap) entry.

func NewID

func NewID() (SessionID, error)

NewID returns a fresh UUIDv4-shaped SessionID, drawn from crypto/rand. Returns an error only when the system rng fails — fatal at startup, same fail-fast semantics as today's supervisor.New errors.

type SessionInfo

type SessionInfo struct {
	ID SessionID
	// Label is the operator-set label, except that the bootstrap entry's
	// empty on-disk label is substituted with the synthetic string
	// "bootstrap" here. The on-disk value is unchanged.
	Label          string
	LifecycleState lifecycleState
	LastActiveAt   time.Time
	// Bootstrap is true for the bootstrap entry; lets consumers
	// disambiguate without re-checking IDs.
	Bootstrap bool
}

SessionInfo is one session's operator-visible metadata, returned by Pool.List. Field types are deep-copy-safe: SessionID and string are values, time.Time is a value, and lifecycleState is a uint8 enum. Mutating a SessionInfo does not affect Pool state or the on-disk registry.

type SessionSettings added in v0.16.0

type SessionSettings struct {
	Model  string
	Effort string
	YOLO   bool

	// PermissionMode is the posture claude runs the session under: one of the
	// five non-escalating modes (permissionModeInBand) or permissionModeBypass.
	// Membership in the whole storable set is permissionModeKnown, and since
	// #2066 that set is also the set the daemon DELIVERS on a held-open stream:
	// all six are granted the same way, as a set_permission_mode control
	// request. The escalation used to be the exception — only a relaunch under a
	// recomposed argv could grant it (#1595) — so a reader of this field no
	// longer has to model its two halves differently. Empty is the zero value's
	// "never chosen", read as the default posture and normalised to
	// permissionModeDefault at every construction site.
	PermissionMode string
}

SessionSettings is the per-session model / reasoning-effort / permission-posture set persisted in the registry (#833, #2043) and applied to the claude spawn argv. The zero value inherits the daemon template for Model/Effort and enforces permissions (YOLO off, mode default) — the fail-safe default.

Set initially in Pool.New (bootstrap) or Pool.buildSession (minted) and mutated post-construction by Pool.UpdateSettings (#840) under Pool.mu (write); read under Pool.mu — the same discipline Pool.Rename uses for label.

PermissionMode and YOLO express ONE posture through two fields, and a Pool-held Session always satisfies YOLO == (PermissionMode == permissionModeBypass): every writer either rejects (Pool.UpdateSettings, on an unknown mode or a contradictory pair) or normalises (both construction sites and the registry read, via canonicalPermissionMode). YOLO stays the authoritative half for the escalation — claudeSettingsArgs suppresses the mode pair on it and never derives a posture from the mode string — so the fail-safe is enforced in exactly one place even if a hand-built Session literal in a test breaks the invariant.

Since #2065 the pair no longer decides what the child LAUNCHES as — every child launches in bypass — only what it is walked back to in-band. PermissionMode is therefore the value that actually decides the running posture, and the safety moved from "the flag is absent from the argv" to "the write was confirmed", which is the fail-closed turn gate in internal/streamsup.

yolo is not redundant and is not being phased out here: the mobile client speaks it, and #1687 settles what the two mean together on the wire.

type SessionTransition added in v0.15.0

type SessionTransition struct {
	PreviousID SessionID
	NewID      SessionID
	Reason     TransitionReason
	OccurredAt time.Time
	// AgentSwitch preserves the dedicated committed-switch publication contract.
	AgentSwitch    bool
	Cause          LifecycleCause
	ConversationID string
	PreviousAgent  string
	NextAgent      string
	// ResetHandoffOutcome is an optional caller-supplied classification, not
	// handoff text. Nil means unknown; the supplied value is copied at rotation.
	ResetHandoffOutcome *string
}

SessionTransition is a captured lifecycle fact. Empty session IDs mean absent prior/successor sessions; OccurredAt is nonzero UTC. ConversationID is captured at the binding mutation or eviction decision, never inferred from bootstrap, labels or historical IDs. Empty ownership/agent fields explicitly mean unknown.

type SettingsUpdate added in v0.16.0

type SettingsUpdate struct {
	Model  *string
	Effort *string
	YOLO   *bool

	// PermissionMode names the posture to switch to (#2043). Unlike Model and
	// Effort, "" is NOT a meaningful value here — the default posture is a
	// nameable mode, so an explicit empty string has no reading and is rejected
	// with ErrUnsupportedPermissionMode like any other unrecognised value.
	//
	// It and YOLO express one posture, so an update naming EITHER is an update
	// to the posture; naming both with values that contradict each other is
	// ErrPermissionModeConflict. See Pool.UpdateSettings for the derivation.
	PermissionMode *string
}

SettingsUpdate is a partial change to a session's SessionSettings. A nil field means "leave the stored value untouched"; a non-nil field sets that value — including "" for Model/Effort and false for YOLO, which are thereby distinguishable from omitted. It is the presence contract shared with the v2 settings verb (#841), which decodes the wire payload into it.

YOLO is a *bool for the fail-safe: an omitted (nil) YOLO can never enable bypass — only an explicit non-nil *true turns --dangerously-skip-permissions on, and an explicit *false turns it off.

type SnapshotEntry

type SnapshotEntry struct {
	ID  SessionID
	PID int
}

SnapshotEntry is one (id, pid) pair captured by Pool.Snapshot. The primitive field types are what let the retired rotation watcher consume snapshots without importing internal/sessions; #2137 removed that consumer. Both the type and Pool.Snapshot are kept for the same reason RotateID is — they are exported, and removing them is a separate deliberate call rather than a side effect of retiring the watcher.

type State added in v0.16.0

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 exited
	LastUptime   time.Duration // uptime of the most recent child, zero if first run
	NextBackoff  time.Duration // delay scheduled before the next spawn, zero when running
}

State is a snapshot of a runner's runtime state, returned by Runner.State for the control plane.

type SwitchTransitionMetadata added in v0.38.0

type SwitchTransitionMetadata struct {
	ConversationID string
	PreviousAgent  string
	NextAgent      string
}

SwitchTransitionMetadata is supplied by the caller that committed the switch, before old-session removal loses its ownership and actual agent information. Empty fields explicitly mean unknown.

type TransitionObserver added in v0.15.0

type TransitionObserver func(SessionTransition)

TransitionObserver receives update-only lifecycle facts: creation, unchanged IDs, refused mutations, shutdown and crashes retaining the ID emit nothing. Recovery is observable internally but has no legacy delimiter or production self-heal caller. Notifications run synchronously on the transition's owning goroutine with no pool/session/capacity lock held by that goroutine. Observers MUST NOT block: hand off to a buffered channel and return. Nil disables them.

type TransitionReason added in v0.15.0

type TransitionReason string

TransitionReason preserves the legacy delimiter vocabulary. A lifecycle fact without a legacy delimiter has an empty Reason; consumers must reject it.

const (
	// ReasonClear remains the reset, Claude clear and committed switch delimiter.
	ReasonClear TransitionReason = "clear"
	// ReasonEviction remains the idle and capacity eviction delimiter.
	ReasonEviction TransitionReason = "eviction"
)

Jump to

Keyboard shortcuts

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