Documentation
¶
Overview ¶
Package agents spawns and controls Claude Code sessions Caprock owns: a real `claude` process in a PTY, its output buffered for the terminal view and its exit recorded. Externally started sessions are never touched here — we only spawn, type into, pause and kill processes we started (.ai/05-orchestration.md).
Index ¶
- Constants
- Variables
- func CarriedMode(reported string) string
- func IsPermissionMode(m string) bool
- func IsSpawnable(agent string) bool
- func NativeResume(agent, id string, fork bool) ([]string, error)
- func RemoveWorktree(ctx context.Context, repoDir, name string) error
- func RevokeTrustGrants() (int, error)
- func TrustGrantCount() int
- func WorktreeName(branch string) string
- type Agent
- func (a *Agent) Done() <-chan struct{}
- func (a *Agent) Exited() (int, bool)
- func (a *Agent) Paused() bool
- func (a *Agent) Resize(cols, rows int) error
- func (a *Agent) Ring() *termbuf.Ring
- func (a *Agent) Signal(sig ptyman.Signal) error
- func (a *Agent) Snapshot() []byte
- func (a *Agent) Subscribe() (<-chan []byte, func())
- func (a *Agent) Write(b []byte) error
- type HookSignal
- type Manager
- func (m *Manager) AgentAvailable(agent string) bool
- func (m *Manager) AnswerPermission(sessionID, id string, choice PermissionChoice) error
- func (m *Manager) ClaudeAvailable() bool
- func (m *Manager) GeminiAvailable() bool
- func (m *Manager) Get(sessionID string) (*Agent, bool)
- func (m *Manager) Input(sessionID string, data []byte) error
- func (m *Manager) InputSeq(sessionID, client string, seq uint64, data []byte) (uint64, error)
- func (m *Manager) IsShell(id string) bool
- func (m *Manager) List() []*Agent
- func (m *Manager) ObserveHook(sig HookSignal)
- func (m *Manager) OwnedRunning() []string
- func (m *Manager) PauseOwned(sessionID string) (bool, error)
- func (m *Manager) PendingPermission(sessionID string) (*Permission, bool)
- func (m *Manager) Reattach(ctx context.Context) []*Agent
- func (m *Manager) Resize(sessionID string, cols, rows int) error
- func (m *Manager) Shells() []*Agent
- func (m *Manager) Shutdown()
- func (m *Manager) Signal(sessionID string, sig ptyman.Signal) error
- func (m *Manager) Spawn(ctx context.Context, req SpawnRequest) (*Agent, error)
- func (m *Manager) SpawnShell(ctx context.Context, req ShellRequest) (*Agent, error)
- func (m *Manager) Survives(sessionID string) bool
- func (m *Manager) UseHosts(exe, version string)
- type Permission
- type PermissionChoice
- type ShellRequest
- type SpawnRequest
- type Worktree
- type WorktreeSpec
Constants ¶
const ( AgentClaude = "claude" AgentGemini = "gemini" AgentCodex = "codex" AgentOpenCode = "opencode" )
The coding agents Caprock can launch.
const KindShell = "shell"
KindShell is the Agent.Kind (and pty-host meta kind) of a shell tab: the user's login shell in a folder, held by a pty-host like an agent session so it outlives the daemon (F04, WP-07).
A shell is not a session. It writes no sessions row and no event, so it is in no total, no Now card, no export and no count by construction — the same reason ADR-037 removes rows rather than flagging them: a filter column would have to be remembered by every query, and a missed one counts a shell as work. What knows a shell exists is this manager (and, across a restart, its pty-host's registry entry).
const ShutdownGrace = 5 * time.Second
ShutdownGrace is how long a session gets to finish on its own before it is killed. Claude Code flushes its transcript and releases its session id on the way out; none of that survives a SIGKILL.
const WorktreeDir = ".caprock-worktrees"
WorktreeDir is where Caprock puts the worktrees it makes, under the repository root (store.WorktreeDir; the resolver strips it by name).
Variables ¶
var ErrNoAlways = errors.New("this prompt has no \"don't ask again\" option")
ErrNoAlways means the prompt has no "don't ask again" option to pick.
var ErrNoNativeResume = errors.New("this agent cannot reopen a session by id")
ErrNoNativeResume is returned for an agent whose CLI cannot reopen a session by its id.
var ErrNoPermission = errors.New("the session is not waiting on that permission prompt")
ErrNoPermission means the session is not showing the prompt named: it was answered, it is queued behind another, or it was never asked.
var ErrNotOnPrompt = errors.New("that option is not on the prompt — answer in the terminal")
ErrNotOnPrompt means the choice is not an option on the menu the session's terminal shows now — or no permission menu is showing at all. Nothing was typed.
var ErrNotOwned = errors.New("caprock did not start this session, so only its own terminal can control it")
ErrNotOwned is returned for control operations on a session Caprock did not spawn.
var ErrWorktreeDirty = errors.New("the worktree has uncommitted or untracked changes")
ErrWorktreeDirty refuses to remove a worktree with changes.
var PermissionModes = []string{"acceptEdits", "auto", "bypassPermissions", "dontAsk", "manual", "plan"}
PermissionModes are the values Claude Code's --permission-mode accepts (`claude --help`), which is also the vocabulary every spawn request uses: the other agents' builders translate them (argv.go).
var Spawnable = []string{AgentClaude, AgentCodex, AgentOpenCode, AgentGemini}
Spawnable lists the agents Caprock can start, in the order the dialog offers them.
Functions ¶
func CarriedMode ¶ added in v0.78.2
CarriedMode is the mode a continued session is started in, given the mode its hooks last reported, or "" to leave the flag off.
Claude Code reports its ordinary mode as "default", which --permission-mode does not accept; leaving the flag off is what starts that mode. Any word this build does not know is dropped too rather than handed to a CLI that would refuse to start over it.
func IsPermissionMode ¶ added in v0.78.2
IsPermissionMode reports whether m is one of PermissionModes.
func IsSpawnable ¶ added in v0.70.0
IsSpawnable reports whether agent names one Caprock can start. "" is Claude Code, which every request before the agent field meant.
func NativeResume ¶ added in v0.70.1
NativeResume is the command that carries a session on in the user's own terminal — what they would type themselves: the CLI's own name and resumeArgs, with none of the flags Caprock adds for a session it runs (folder trust, a port, --no-daemon), which belong to Caprock's PTY and not to the user's terminal.
func RemoveWorktree ¶ added in v0.75.0
RemoveWorktree removes a clean worktree Caprock made, and leaves its branch.
Only a worktree under <repo>/.caprock-worktrees is removed: one the user made elsewhere is theirs. A worktree with any change — modified, staged or untracked — is refused with ErrWorktreeDirty, checked here and again by git itself (no --force), so a race cannot lose work.
func RevokeTrustGrants ¶ added in v0.18.0
RevokeTrustGrants removes hasTrustDialogAccepted from every folder Caprock granted it to, and clears the ledger. Grants Caprock did not create are left alone — the user may have accepted those folders themselves, and undoing a human's decision is not uninstall's job. Returns how many were revoked.
It exists because the grant was previously permanent and one-way: nothing, including `caprock hooks uninstall`, ever removed it, so a machine accumulated a trusted-project entry per worktree forever — including for worktrees long since deleted.
func TrustGrantCount ¶ added in v0.18.0
func TrustGrantCount() int
TrustGrantCount reports how many folders Caprock has granted trust to, for the uninstall command's summary line.
func WorktreeName ¶ added in v0.75.0
WorktreeName is the directory name a branch's worktree gets under <repo>/.caprock-worktrees: the branch with its slashes made dashes, so `feat/x` is `feat-x`.
Types ¶
type Agent ¶
type Agent struct {
SessionID string
Cwd string
Worktree string
Command string
StartedAt time.Time
// Kind is which coding agent this is ("claude", "codex", …).
Kind string
// Port is the loopback port an OpenCode TUI's own server listens on, so
// the daemon can learn the session id it creates; 0 for other agents and
// for a resumed OpenCode session, whose id is already known.
Port int
// contains filtered or unexported fields
}
Agent is a live owned session.
func (*Agent) Done ¶ added in v0.70.0
func (a *Agent) Done() <-chan struct{}
Done is closed when the process exits.
func (*Agent) Ring ¶ added in v0.75.0
Ring is the session's output with offsets (terminal protocol v2).
func (*Agent) Snapshot ¶
Snapshot returns the current terminal scrollback (for a fresh terminal connect).
type HookSignal ¶ added in v0.72.0
type HookSignal struct {
SessionID string
Event string // hook_event_name
AgentID string // set inside a subagent
Tool string
Input json.RawMessage
ToolUseID string
// Suggestions is PermissionRequest's permission_suggestions, verbatim.
Suggestions json.RawMessage
}
HookSignal is the part of a hook payload that sets or clears a prompt.
type Manager ¶
type Manager struct {
OnExit func(sessionID string, code int)
OnOutput func(sessionID string) // called (throttled by caller) when new bytes arrive
// OnPermission is told when an owned session starts or stops waiting on a
// permission prompt (p is nil when it stops), or the one it shows
// changes. See permission.go.
OnPermission func(sessionID string, p *Permission)
// ProjectPrompt returns the instructions the user set for the project a
// directory is in (projects' defaults.system_prompt), or "". A Claude Code
// session started there gets them through --append-system-prompt. Set by
// the daemon; nil means none.
ProjectPrompt func(dir string) string
// NewSessionID generates a session id; overridable in tests.
NewSessionID func() string
// Now is the clock chat directory names are stamped from; overridable in
// tests so a name can be asserted rather than merely observed to exist.
Now func() time.Time
// contains filtered or unexported fields
}
Manager owns the set of running agents.
func NewManager ¶
NewManager builds a manager. claudePath "" resolves "claude" on PATH.
func (*Manager) AgentAvailable ¶ added in v0.70.0
AgentAvailable reports whether an agent's binary can be launched, so the dialog offers only the agents this machine has: a choice that fails on click is worse than no choice.
func (*Manager) AnswerPermission ¶ added in v0.72.0
func (m *Manager) AnswerPermission(sessionID, id string, choice PermissionChoice) error
AnswerPermission presses the key for choice in an owned session's permission dialog, if the prompt named id is the one it shows and the menu on its screen has that option.
func (*Manager) ClaudeAvailable ¶
ClaudeAvailable reports whether the resolved claude binary can be launched.
func (*Manager) GeminiAvailable ¶ added in v0.44.0
GeminiAvailable reports whether the Gemini CLI can be launched.
func (*Manager) InputSeq ¶ added in v0.75.0
InputSeq types sequenced input (terminal protocol v2) exactly once per client, and returns the client's last applied sequence. Sequence 0 types nothing and only asks for it. A pty-host keeps the numbering itself, so it survives this daemon; a session without one is numbered here.
func (*Manager) ObserveHook ¶ added in v0.72.0
func (m *Manager) ObserveHook(sig HookSignal)
ObserveHook updates the prompts an owned session is waiting on from one of its hook events. Sessions this manager did not start are ignored: there is nothing here that could answer them (rule 7).
func (*Manager) OwnedRunning ¶ added in v0.39.0
OwnedRunning lists the sessions Caprock started that are still running.
The name says "owned" rather than "all" because that distinction is the whole safety story: `m.agents` holds only sessions this manager spawned, and a caller must not have to remember that. See PauseOwned.
Shell tabs are not sessions and are left out: the spend cap pauses work that costs money, and a shell costs none.
func (*Manager) PauseOwned ¶ added in v0.39.0
PauseOwned pauses a session Caprock started, reporting whether it did.
An id this manager does not own is refused here, quietly and without error: [Rule 7] is enforced at the thing that holds the process handles rather than by whoever happens to be calling. A session started in someone's own terminal is watched and never signalled, however much it is costing — and the daily spend cap, the one caller today, therefore cannot violate that rule even by mistake.
[Rule 7]: ../../CLAUDE.md
func (*Manager) PendingPermission ¶ added in v0.72.0
func (m *Manager) PendingPermission(sessionID string) (*Permission, bool)
PendingPermission returns the prompt an owned session is showing: the oldest it is waiting on.
func (*Manager) Reattach ¶ added in v0.70.1
Reattach picks up the sessions a previous daemon left running in their pty-hosts and records how the ones that ended in between finished. Returns the reattached sessions, so the daemon can resume watching the agents that need it (an OpenCode session not yet linked to its own id). Call it once, at startup, before the first liveness sweep.
func (*Manager) Shutdown ¶
func (m *Manager) Shutdown()
Shutdown lets go of every owned session that lives in a pty-host — it keeps running, and the next daemon reattaches it (ADR-033) — and ends the rest, giving each a chance to stop cleanly.
It used to SIGKILL them outright, so upgrading Caprock — or any restart of the daemon — silently destroyed whatever the user had running under it, mid-turn, with no warning and nothing written out. A tool that watches your work must not be the thing that eats it. SIGTERM first was better and still ended the session; a pty-host is the fix. What is left for this path is a session that could not be given one (the in-process fallback).
Every session is signalled first and waited on together, so the grace period is spent once rather than once per session. Anything still alive at the end is killed: shutdown has to terminate, and a process that ignores SIGTERM has had its chance.
func (*Manager) Spawn ¶
Spawn launches a new session and registers it. The PTY session id is forced with `claude --session-id <uuid>` so hooks and transcript arrive under the id Caprock already knows.
func (*Manager) SpawnShell ¶ added in v0.75.0
SpawnShell starts the user's login shell in req.Cwd. Rule 7 holds: Caprock started it, so Caprock may type into it and end it.
func (*Manager) Survives ¶ added in v0.70.1
Survives reports whether a running owned session is held by a pty-host and so outlives this daemon. False for one in the in-process fallback, which ends when the daemon does.
func (*Manager) UseHosts ¶ added in v0.70.1
UseHosts starts every new session inside a pty-host process (ADR-033), so it outlives this daemon. exe is the Caprock binary to run as `exe pty-host`. A session whose holder cannot be started falls back to the in-process PTY this manager used before, which works and ends with the daemon.
type Permission ¶ added in v0.72.0
type Permission struct {
// ID names this prompt, so a button drawn for one prompt cannot answer
// the next.
ID string `json:"id"`
// Tool is the tool being asked about ("Bash", "Write", "mcp__…").
Tool string `json:"tool"`
// Detail is what it would do: the command, the file, the URL.
Detail string `json:"detail"`
// Always labels the "don't ask again" option when the hook suggests one;
// empty when the button is not offered. Whether the dialog on the screen
// really has it is checked when the button is pressed.
Always string `json:"always,omitempty"`
Since time.Time `json:"since"`
// Queued is how many more prompts wait behind this one.
Queued int `json:"queued,omitempty"`
// contains filtered or unexported fields
}
Permission is a prompt an owned session is showing or has queued.
type PermissionChoice ¶ added in v0.72.0
type PermissionChoice string
PermissionChoice is one of the answers a button gives.
const ( PermissionAllow PermissionChoice = "allow" PermissionAlways PermissionChoice = "always" PermissionDeny PermissionChoice = "deny" // PermissionDismiss types nothing: it takes the card away, for a prompt // that was settled where no hook saw it (a request that timed out, a // check that denied it without a menu). PermissionDismiss PermissionChoice = "dismiss" )
The answers. The key each one presses is read off the screen (menuKey).
type ShellRequest ¶ added in v0.75.0
ShellRequest starts a shell.
type SpawnRequest ¶
type SpawnRequest struct {
Cwd string `json:"cwd"`
Chat bool `json:"chat,omitempty"` // a quick chat: Caprock picks the directory, no repository needed
Create bool `json:"create,omitempty"` // make Cwd if it does not exist (one level, under an existing parent)
Worktree string `json:"worktree,omitempty"` // git worktree name to create under the repo
Model string `json:"model,omitempty"` // --model
PermissionMode string `json:"permission_mode,omitempty"` // --permission-mode
Command string `json:"command,omitempty"` // default "claude"
// Agent picks which coding agent to launch: "claude" (default), "codex",
// "opencode" or "gemini". They take different flags, so the argv is built
// per agent (argv.go) rather than pretending one shape fits all four.
Agent string `json:"agent,omitempty"`
// Resume continues an existing conversation instead of starting a new one.
//
// This is how a session that lives in somebody's terminal can be picked up
// inside Caprock. It cannot type into a process it did not start — two
// writers on one PTY interleave characters and ruin both — so it starts a
// second process on the same conversation, which is what `--resume` is for.
// The history is on disk, so nothing is lost and nothing is fought over.
Resume string `json:"resume,omitempty"`
// Fork branches the resumed conversation into a new session id rather than
// reusing the original.
//
// Set when the session being picked up is still running somewhere: two live
// processes claiming one id would write the same transcript and each end up
// with half the other's turns. A fork keeps the history and leaves the
// original alone. Claude Code refuses --session-id alongside --resume
// unless --fork-session is present, which is the same distinction from the
// other side.
Fork bool `json:"fork,omitempty"`
// NativeResume is the agent's own id for the session being resumed, when
// it differs from Caprock's (a Codex or OpenCode session Caprock started;
// sessions.native_id). Filled by the daemon from the store, never by the
// browser.
NativeResume string `json:"-"`
// Prompt is the first message, sent as the session starts. A relay's
// brief: built by Caprock, read and edited by the user, and sent only when
// they click Start. Ignored on a resume.
Prompt string `json:"prompt,omitempty"`
// RelayFrom is the session whose work this new one carries on
// (sessions.relay_from). The daemon records it; the agent never sees it.
RelayFrom string `json:"relay_from,omitempty"`
// GeminiKey is the key the daemon holds, passed into the child's
// environment. Never accepted from the browser — the API fills it in from
// settings, so a page cannot hand a spawned process someone else's
// credential.
GeminiKey string `json:"-"`
Args []string `json:"args,omitempty"` // extra args
Cols int `json:"cols,omitempty"`
Rows int `json:"rows,omitempty"`
}
SpawnRequest describes a session to launch.
type Worktree ¶ added in v0.75.0
type Worktree struct {
Path string `json:"path"`
Branch string `json:"branch"`
// Tracks is the remote branch a new local branch was set to track, empty
// when none.
Tracks string `json:"tracks,omitempty"`
}
Worktree is a worktree AddWorktree made.
func AddWorktree ¶ added in v0.75.0
AddWorktree checks out a branch in a new worktree at <repo>/.caprock-worktrees/<WorktreeName(branch)>.
createWorktree, which an agent's `worktree` field uses, makes a branch of its own name (`caprock/<worker>`). This is the general form a person asks for from the sidebar or the phone. It never resets a branch (no -B) and never forces: a branch checked out in another worktree is refused with git's own message, which names where.
type WorktreeSpec ¶ added in v0.75.0
WorktreeSpec asks for a worktree on any branch (WP-08): an existing local branch, a branch only a remote has (created locally, tracking it), or with Create a new branch from Base (HEAD when empty).