sessions

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: MIT Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package 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

This section is empty.

Variables

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 ErrAttachUnavailable = errors.New("sessions: attach unavailable (no bridge)")

ErrAttachUnavailable is returned by Session.Attach when the session has no bridge (foreground mode). The control plane maps this back to the existing "daemon may be in foreground mode" wire string for byte-identical client output.

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 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 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 ErrSessionNotFound = errors.New("sessions: session not found")

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

Functions

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".

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 Config

type Config struct {
	Bootstrap SessionConfig
	Logger    *slog.Logger

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

	// 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" — the test default. Production
	// callers in cmd/pyry default this to 15 minutes via the
	// -pyry-idle-timeout flag.
	IdleTimeout time.Duration

	// 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
}

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 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 the rng, supervisor.New, 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.

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) → register the UUID in the rotation skip-set → schedule sess.Run on Pool.Run's errgroup via supervise → call Pool.Activate (cap-aware) to wake the lifecycle goroutine.

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) 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) 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 (handleAttach already does this).

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) IsAllocated

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

IsAllocated reports whether id is in the freshly-allocated set, consuming the entry on a true return. Opportunistically prunes expired entries. Safe for concurrent use.

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) RegisterAllocatedUUID

func (p *Pool) RegisterAllocatedUUID(id SessionID)

RegisterAllocatedUUID records that id is a UUID pyry just minted (and is about to write to disk via claude --session-id). The watcher consults this set on every CREATE; matching entries skip the rotation path. Entries are consumed on first IsAllocated hit, or pruned after allocatedTTL.

Phase 1.2b-B has no live caller — pyry currently launches claude with --continue, so claude picks the UUID. The scaffolding lands now so Phase 1.1's `pyry sessions new` and `claude --session-id` wiring is a one-liner.

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: sess.Run's loop transitions to runEvicted and parks on activateCh / ctx.Done(). The session is no longer reachable via Pool.sessions, so no caller can signal activateCh; the goroutine survives until pool.Run's runCtx cancels at pool shutdown. Bounded resource cost — see ticket #94 design notes.

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) 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: this mutates session.id without taking session.lcMu. Today the only callers (startup reconciliation, future fsnotify-driven /clear detection) run before any lifecycle goroutine begins observing the id, so no concurrent reader exists. lastActiveAt IS protected by lcMu and is taken briefly. Lock order remains Pool.mu → Session.lcMu.

This is the load-bearing seam the live-detection ticket reuses.

func (*Pool) Run

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

Run blocks until ctx is cancelled, supervising every session in the pool, running the rotation watcher (when ClaudeSessionsDir is set) and 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.

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

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 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 (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.

func (*Session) Attach

func (s *Session) Attach(in io.Reader, out io.Writer) (done <-chan struct{}, err error)

Attach binds a client to this session's bridge. Returns ErrAttachUnavailable when the session has no bridge (foreground mode). Otherwise delegates to (*supervisor.Bridge).Attach, propagating supervisor.ErrBridgeBusy verbatim.

Bookkeeping: a successful attach increments `attached`; the wrapper goroutine spawned here decrements it when the bridge's done channel fires. While `attached > 0` the idle timer's eviction is deferred (see runActive).

Contract: callers must Activate the session before Attach. An Attach on an evicted session would block on the bridge's pipe forever, since no claude is running to drain it. The control plane is the only attach caller and always Activates first.

func (*Session) Bridge added in v0.11.0

func (s *Session) Bridge() *supervisor.Bridge

Bridge exposes the underlying I/O bridge, or nil in foreground mode. Consumed by the assistant-turn bridge in cmd/pyry to register an output observer on the PTY-drain path.

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 for attached>0. The cap is a hard limit; an attached caller will see EOF on its bridge.

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) Resize

func (s *Session) Resize(rows, cols uint16) error

Resize applies the given window size to the session's PTY via the bridge. Returns ErrAttachUnavailable when the session has no bridge (foreground mode); the control plane's attach handler swallows that case since foreground mode has its own SIGWINCH watcher.

rows-then-cols matches Bridge.Resize and pty.Winsize. No lifecycle locking: Resize doesn't bump lastActiveAt or interact with the active↔evicted state machine. The bridge's own ptyMu serializes against iteration boundaries.

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) State

func (s *Session) State() supervisor.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) Supervisor added in v0.11.0

func (s *Session) Supervisor() *supervisor.Supervisor

Supervisor exposes the underlying supervisor handle. Consumed by the assistant-turn bridge in cmd/pyry to read CurrentConversation() at broadcast time. Returned pointer is owned by the session; callers must not retain it past the session's lifetime.

func (*Session) WriteUserTurn added in v0.11.0

func (s *Session) WriteUserTurn(conversationID string, payload []byte) error

WriteUserTurn delegates to the underlying supervisor. Consumed by the send_message handler via the handlers.TurnWriter interface.

type SessionConfig

type SessionConfig struct {
	ClaudeBin  string
	WorkDir    string
	ResumeLast bool
	ClaudeArgs []string
	Bridge     *supervisor.Bridge // nil = foreground

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

	// IdleTimeout, when positive, causes the session's claude process to
	// exit after the configured period with no attached clients. 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 SnapshotEntry

type SnapshotEntry struct {
	ID  SessionID
	PID int
}

SnapshotEntry is one (id, pid) pair captured by Pool.Snapshot. Carries only primitive types so the rotation package can consume snapshots without importing internal/sessions.

Directories

Path Synopsis
Package rotation watches claude's session directory for /clear-style UUID rotations and notifies its host (internal/sessions) so the registry can follow claude to the new <uuid>.jsonl in real time.
Package rotation watches claude's session directory for /clear-style UUID rotations and notifies its host (internal/sessions) so the registry can follow claude to the new <uuid>.jsonl in real time.

Jump to

Keyboard shortcuts

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