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 CanonicalMode(mode string) string
- func CarriedMode(reported string) string
- func CrossesBypass(from, to string, bypass bool) bool
- func EffortLevels(agent string) []string
- func FindBinary(name string) string
- func FlattenForBatch(p string) string
- func HoldsMessage(screen []string, text string) bool
- func IsBatch(p string) bool
- func IsChatDirIn(dataDir, dir string) bool
- func IsPermissionMode(m string) bool
- func IsSpawnable(agent string) bool
- func NativeResume(agent, id string, fork bool) ([]string, error)
- func NextMode(from string, bypass, auto bool) string
- func RemoveWorktree(ctx context.Context, repoDir, name string) error
- func RevokeTrustGrants() (int, error)
- func ScreenMode(screen []string) (string, bool)
- func TrustGrantCount() int
- func Unexpected(code int, stopped, early bool) bool
- func ValidEffort(agent, e string) bool
- func ValidSubagentModel(m string) bool
- func WorktreeName(branch string) string
- type Agent
- func (a *Agent) Current() string
- func (a *Agent) Done() <-chan struct{}
- func (a *Agent) Exited() (int, bool)
- func (a *Agent) LastIO() time.Time
- func (a *Agent) PID() int
- 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) TouchIO(t time.Time)
- func (a *Agent) Write(b []byte) error
- type Branch
- type ExitReport
- type HookSignal
- type LaunchFacts
- type Manager
- func (m *Manager) AgentAvailable(agent string) bool
- func (m *Manager) AgentBinary(agent string) string
- func (m *Manager) AnswerPermission(sessionID, id string, choice PermissionChoice) error
- func (m *Manager) ClaudeAvailable() bool
- func (m *Manager) ClaudeBinary() string
- func (m *Manager) End(sessionID string) error
- func (m *Manager) Exit(sessionID string) (ExitReport, bool)
- func (m *Manager) Follow(next, prev string) 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) IsChatDir(dir string) bool
- func (m *Manager) IsShell(id string) bool
- func (m *Manager) Key(sessionID string, data []byte) error
- func (m *Manager) LastKey(sessionID string) time.Time
- func (m *Manager) List() []*Agent
- func (m *Manager) MarkFreed(sessionID string)
- func (m *Manager) Nudge(sessionID string) (narrate.Nudge, bool)
- func (m *Manager) ObserveHook(sig HookSignal)
- func (m *Manager) OpenCodeVersion() string
- func (m *Manager) OwnedRunning() []string
- func (m *Manager) OwnedRunningKind(kind string) []string
- func (m *Manager) PasteMode(sessionID string) bool
- func (m *Manager) PauseOwned(sessionID string) (bool, error)
- func (m *Manager) PendingPermission(sessionID string) (*Permission, bool)
- func (m *Manager) PromptHolds(sessionID, text string) bool
- func (m *Manager) Reattach(ctx context.Context) []*Agent
- func (m *Manager) Resize(sessionID string, cols, rows int) error
- func (m *Manager) Restarting(sessionID string) bool
- func (m *Manager) ResumeOwned(sessionID string) (bool, error)
- func (m *Manager) RunAtPrompt(id, text string)
- func (m *Manager) SessionMode(sessionID string) (mode string, source ModeSource, facts LaunchFacts, ok bool)
- func (m *Manager) SessionPID(sessionID string) int
- func (m *Manager) SetBinary(agent, path string)
- func (m *Manager) SetRestarting(sessionID string, on bool)
- func (m *Manager) ShellJob(id string) (string, int)
- func (m *Manager) ShellProgram(id string) string
- func (m *Manager) ShellScreen(id string) ([]string, bool)
- 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) StopForRestart(ctx context.Context, sessionID string) (cols, rows int, err error)
- func (m *Manager) Survives(sessionID string) bool
- func (m *Manager) SwitchMode(ctx context.Context, sessionID, target string) (string, error)
- func (m *Manager) TypeAtPrompt(id, text string)
- func (m *Manager) UseHosts(exe, version string)
- type ModeSource
- type Permission
- type PermissionChoice
- type ShellRequest
- type SpawnRequest
- type Worktree
- type WorktreeSpec
Constants ¶
const ( AgentClaude = "claude" AgentGemini = "gemini" AgentCodex = "codex" AgentOpenCode = "opencode" // AgentGrok is xAI's Grok Build CLI, `grok` (ADR-046). AgentGrok = "grok" // AgentHermes is Nous Research's Hermes Agent CLI, `hermes` (ADR-069). AgentHermes = "hermes" // AgentCursor is Cursor's CLI, `cursor-agent` (ADR-095). AgentCursor = "cursor" )
The coding agents Caprock can launch.
const ( ModeDefault = "default" ModeAccept = "acceptEdits" ModePlan = "plan" ModeBypass = "bypassPermissions" ModeAuto = "auto" ModeDontAsk = "dontAsk" )
The mode names this file speaks: Claude Code's own, with "default" for the ordinary one (what its hooks report). "manual" is accepted as its spelling on the command line.
const ( KimiModel = "kimi-k3[1m]" KimiFastModel = "kimi-k2.7-code" )
KimiModel is the model the guide maps every tier but Haiku to; the `[1m]` suffix is the guide's own. KimiFastModel is its Haiku tier.
const ClaudeEffortEnv = "CLAUDE_CODE_EFFORT_LEVEL"
ClaudeEffortEnv is the variable Claude Code reads its effort from first, over --effort (code.claude.com/docs/en/model-config, "Adjust effort level", read 2026-11-23).
const DeepSeekBaseURL = "https://api.deepseek.com/anthropic"
DeepSeekBaseURL is DeepSeek's Anthropic-compatible endpoint.
const DeepSeekModel = "deepseek-flash"
DeepSeekModel is the model every tier maps to. The `[1m]` suffix tells Claude Code the model has a 1M-token context; Claude Code does not send it.
const KimiBaseURL = "https://api.moonshot.ai/anthropic"
KimiBaseURL is Moonshot's Anthropic-compatible endpoint (platform.kimi.ai/docs/api/overview and the guide above, read 2026-11-03).
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 MaxModePresses = 5
MaxModePresses bounds a switch: the longest cycle Claude Code has is five modes long.
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 SubagentModelEnv = "CLAUDE_CODE_SUBAGENT_MODEL"
SubagentModelEnv is the variable Claude Code reads for the model its subagents run on; it accepts a model alias or a full model name.
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 ( // ErrModeMenu: a dialog or menu is on the screen, and Shift+Tab would // act on it. ErrModeMenu = errors.New("the session is showing a prompt; answer it first") // ErrModeStuck: Shift+Tab was pressed and the footer did not change. ErrModeStuck = errors.New("Shift+Tab did not change the mode: the session may have Shift+Tab bound to something else, or its footer is hidden") // ErrModeUnreachable: the cycle came round without passing the mode. ErrModeUnreachable = errors.New("that mode is not in this session's Shift+Tab cycle") )
Errors a switch reports; nothing more was typed after any of them.
var EarlyExit = 15 * time.Second
EarlyExit is how soon after its start a session's program may end, with nothing typed into it, for the end to read as "it exited at once": a program that could not start (a flag it refused, a conversation it could not find), not one somebody used and closed.
var ErrBypassConsent = errors.New("bypass needs a one-time consent first: Claude Code's warning for skipping permissions has not been accepted on this computer; start it from New agent, which shows the warning with Accept and start, or pick a mode that asks")
ErrNotOwned is returned for control operations on a session Caprock did not spawn. ErrBypassConsent is Spawn refusing a Claude Code start in bypass before its one-time warning was accepted in the settings that session reads (ADR-041). The API answers it as 409 bypass_consent, which the start dialogs, here and on a linked computer, turn into the warning itself.
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")
var ErrSeveralPrompts = errors.New("several approvals are waiting and the terminal shows one of them — answer in the terminal")
ErrSeveralPrompts means more than one prompt is outstanding, so which one the terminal shows is unknown and no key is pressed.
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, AgentGrok, AgentHermes, AgentCursor}
Spawnable lists the agents Caprock can start, in the order the dialog offers them.
var SubagentModels = []string{"haiku", "sonnet", "opus"}
SubagentModels is the allowlist for SpawnRequest.SubagentModel: the three aliases Claude Code resolves to the current model of each family. The request names one of these, never a variable or a free-form value.
Functions ¶
func CanonicalMode ¶ added in v0.109.0
CanonicalMode is mode in the words above, or "" for a word Claude Code does not have.
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 CrossesBypass ¶ added in v0.109.0
CrossesBypass reports whether going from one mode to another by Shift+Tab passes through bypass on the way — whether or not auto mode is in the cycle. A session mid-turn must not spend even a moment there that the user did not ask for.
func EffortLevels ¶ added in v0.192.0
EffortLevels is the efforts agent takes at launch, lowest first; nil for an agent that takes none.
func FindBinary ¶ added in v0.99.0
FindBinary resolves a command the way an agent's binary is resolved: the daemon's PATH, the login shell's, then the installers' directories. "" when it is not found. For a custom agent's command (ADR-046).
func FlattenForBatch ¶ added in v0.99.0
FlattenForBatch makes a prompt safe for a Windows batch shim's command line.
func HoldsMessage ¶ added in v0.132.0
HoldsMessage reports whether screen (rows, top to bottom) shows text still sitting in the prompt: the input box's rows hold the end of the message or a paste placeholder ("[Pasted text #1 +3 lines]", Codex's "[Pasted Content 1200 chars]"). A screen with a menu on it never holds a message — an Enter there would answer the menu.
The input box is Claude Code's: the rows between two horizontal rules with a "❯" or ">" prompt line in them, the lowest such pair. Anything else is read from its last few non-empty rows. A message already sent and echoed above the box is outside it; where no box is found an echo can still match, and the cost is one Enter at an empty prompt, which does nothing.
func IsChatDirIn ¶ added in v0.126.0
IsChatDirIn is IsChatDir for a data directory the caller names.
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 NextMode ¶ added in v0.109.0
NextMode is where one Shift+Tab takes a session in mode from, as Claude Code 2.1.296 cycles: bypass only when the process may enter it, auto only when the account has it.
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 ScreenMode ¶ added in v0.109.0
ScreenMode reads the permission mode off the footer of a Claude Code screen; false when no indicator is there (an older build in its default mode, a dialog over the footer, a screen not drawn yet).
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 Unexpected ¶ added in v0.185.2
Unexpected is whether an owned session's end is one nobody asked for: the program exited with a non-zero code or was killed by a signal (code -1: the owner's "ops" session died with Chrome, 2026-11-20), Caprock did not stop it (Stop, closing its tab, freeing memory, a permission-mode restart, a shutdown — stopped), and it did not end at once (early, which has its own panel). A clean exit 0 — /exit, Ctrl+D — is the user's own and is not one.
func ValidEffort ¶ added in v0.192.0
ValidEffort reports whether e is "" (the agent's own default) or one of the efforts agent takes at launch. Any value is valid for an agent that takes none, since it is dropped there.
func ValidSubagentModel ¶ added in v0.138.0
ValidSubagentModel reports whether m is "" (subagents follow the session) or one of SubagentModels.
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
// NativeID is the agent's own id for a new session Caprock named at the
// start — an OpenCode 2 session (`--session <id>` creates it) — for the
// daemon to link at once; "" otherwise.
NativeID string
// EndWhenDone: the spawn asked for the session to be ended once its
// turn finishes (SpawnRequest.EndWhenDone). Kept in the pty-host's
// metadata, so a restarted daemon still knows.
EndWhenDone bool
// contains filtered or unexported fields
}
Agent is a live owned session.
func (*Agent) Current ¶ added in v0.146.0
Current is the session the process runs now: the spawn's id until a /clear, then the newest session a /clear started in it.
func (*Agent) Done ¶ added in v0.70.0
func (a *Agent) Done() <-chan struct{}
Done is closed when the process exits.
func (*Agent) LastIO ¶ added in v0.143.0
LastIO is when the session last drew output or was typed into, as this daemon saw it; zero before either. A reattached session's replayed screen does not count (quietUntil), so after a restart this is zero until the session draws something new.
func (*Agent) PID ¶ added in v0.101.0
PID is the agent's (or shell's) own process id — the child of its pty-host, not the host. The resource meter starts its process tree here.
func (*Agent) Paused ¶
Paused reports the pause state; false for an Agent with no process behind it (a caller's fake).
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).
func (*Agent) Subscribe ¶
Subscribe returns a channel of new output chunks and a cancel func. The channel is closed when the process exits.
type Branch ¶ added in v0.100.0
type Branch struct {
Name string `json:"name"`
// Main marks the branches people start from: the remote's default branch,
// main, master, develop, dev, trunk. They are listed first.
Main bool `json:"main,omitempty"`
// Default is the remote's default branch (origin/HEAD), else main or master.
Default bool `json:"default,omitempty"`
Local bool `json:"local,omitempty"`
// Remote is the remote that has it ("origin"), empty for a local-only branch.
Remote string `json:"remote,omitempty"`
// CommittedMs is the newest commit on it, local or remote, for ordering.
CommittedMs int64 `json:"committed_ms"`
}
Branch is one branch a new copy can start from: local, on a remote, or both, listed under its short name ("main", not "origin/main").
func ListBranches ¶ added in v0.100.0
ListBranches lists repo's branches for the New copy picker: main branches first (the default one at the top), then the rest by their newest commit. Caprock's own worker branches (caprock/…) are left out: nobody starts from another agent's scratch branch by choice, and they crowded the list.
type ExitReport ¶ added in v0.157.0
type ExitReport struct {
SessionID string `json:"session_id"`
// Agent is which coding agent it was ("claude", "codex", …); "" when
// only the store remembers the exit.
Agent string `json:"agent,omitempty"`
Code int `json:"code"`
// Early: it ended within EarlyExit of its start with nothing typed.
Early bool `json:"early"`
// Freed: Caprock ended it to free memory, on the user's click; its
// conversation is kept and can be continued.
Freed bool `json:"freed,omitempty"`
// Unexpected: nobody asked it to end (Unexpected). The tab that falls
// back to a shell says so, with Resume, and Recently closed lists it.
Unexpected bool `json:"unexpected,omitempty"`
RanMs int64 `json:"ran_ms"`
// Tail is the end of what it printed, as plain text: the screen it left,
// ANSI and blank lines stripped, at most exitTailLines lines.
Tail string `json:"tail"`
// At is when it ended, unix ms.
At int64 `json:"at"`
// Retry is the request that started it, for Try again: the same launch
// once more, which for a fork or a fresh session is a new session id. Only
// what a request body may carry is in it (the keys and directories the
// daemon fills in are not JSON fields). Absent when this daemon did not
// start it.
Retry *SpawnRequest `json:"retry,omitempty"`
// Binary is the program that ran, as resolved in the daemon's
// environment; absent when only the store remembers the exit.
Binary string `json:"binary,omitempty"`
}
ExitReport is how an owned session's program ended: its code, how long it ran, and the last lines its terminal showed. Served by GET /v1/agents/{id}/exit; the tab of a session that exited at once shows it in place of a terminal that can no longer connect.
type HookSignal ¶ added in v0.72.0
type HookSignal struct {
SessionID string
Event string // hook_event_name
AgentID string // set inside a subagent
AgentType string // the subagent's type ("general-purpose"), with AgentID
Tool string
Input json.RawMessage
ToolUseID string
// Suggestions is PermissionRequest's permission_suggestions, verbatim.
Suggestions json.RawMessage
// PermissionMode is the mode the session was in when the hook fired
// (permission_mode, on every hook Claude Code sends).
PermissionMode string
}
HookSignal is the part of a hook payload that sets or clears a prompt.
type LaunchFacts ¶ added in v0.109.0
type LaunchFacts struct {
Mode string `json:"mode"`
Bypass bool `json:"bypass"`
Model string `json:"model,omitempty"`
}
LaunchFacts is what a Claude Code session's command line says about its permission mode: the mode it started in ("default" when no flag named one), whether bypass is reachable by Shift+Tab, and the model it was given.
func ReadLaunch ¶ added in v0.109.0
func ReadLaunch(command string) LaunchFacts
ReadLaunch reads LaunchFacts from the command an owned session was started with (Agent.Command: the binary and its arguments, space-joined). It stops at --append-system-prompt, whose text is the project's and may contain anything, flags included.
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)
// ProjectSetup returns the setup command set for the project a directory
// is in (projects' defaults.setup_command), or "". It runs in a fresh
// worktree's terminal before the agent starts (ADR-050). Nil means none.
ProjectSetup func(dir string) string
// SetupExe is the Caprock binary whose `worktree-setup` runs that
// command and then becomes the agent. Empty skips the command.
SetupExe string
// 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, a Codex
// one as developer_instructions. Set by the daemon; nil means none.
ProjectPrompt func(dir string) string
// ProjectRepos returns the other member repositories of the multi-repo
// project a directory is in (projects' OtherRepos, ADR-055): a Claude
// Code or Codex session started there gets each as --add-dir, a Gemini
// one as --include-directories. Nil means none.
ProjectRepos func(dir string) []string
// BypassConsent reports whether Claude Code's one-time bypass warning
// has been accepted in the settings a session started with configDir
// ("" for the user's own) reads. A Claude Code session is started with
// --allow-dangerously-skip-permissions only when it has, so Shift+Tab can
// reach bypass without that start opening on the warning (ADR-054). Nil
// means never.
BypassConsent func(configDir string) bool
// OnNudge is told when one is noted, with the session's agent kind, so
// every screen asks for the session's status again at once. It must
// not block: a keystroke calls it.
OnNudge func(sessionID, kind string, n narrate.Nudge)
// 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) AgentBinary ¶ added in v0.178.0
AgentBinary is an agent's executable as an absolute path, "" when this machine does not have it. 2nd Brain reads through it (ADR-103).
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 only one outstanding and the menu on its screen has that option. With several outstanding it types nothing (ErrSeveralPrompts); dismiss, which types nothing, takes any of them.
A prompt a button settles is cleared from the store before this returns, not later the way a keystroke's is (persistLater). A button is a request, not a keystroke, so it can wait on the database; and nothing after it says the dialog went away when the session writes no event for it — a crash a moment after the answer otherwise brought back buttons for a dialog already answered. The key is typed first, so a busy database never delays it.
func (*Manager) ClaudeAvailable ¶
ClaudeAvailable reports whether the resolved claude binary can be launched.
func (*Manager) ClaudeBinary ¶ added in v0.117.2
ClaudeBinary is the claude executable the manager starts, "" when this machine has none. Second Brain's extraction calls the same one (ADR-063).
func (*Manager) Exit ¶ added in v0.157.0
func (m *Manager) Exit(sessionID string) (ExitReport, bool)
Exit is how an owned session ended: from memory while this daemon remembers it, else from the store. ok is false for a session still running, and for one no exit was ever recorded for.
func (*Manager) Follow ¶ added in v0.146.0
Follow records that session next took over the process prev ran in. prev may itself be a session an earlier /clear filed here. False when Caprock holds no terminal for prev, or next is a session of its own (a fork runs in its own process and is never filed here).
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) IsChatDir ¶ added in v0.126.0
IsChatDir reports whether dir is one chat's own folder, directly inside the chats workspace: `<data_dir>/chats/<name>` (ADR-071). The workspace itself is not a chat.
func (*Manager) Key ¶ added in v0.198.0
Key is Input for what a person typed in a terminal (the dashboard's, v1 or v2 without a client id): the same bytes, also kept as the session's last key (LastKey).
func (*Manager) LastKey ¶ added in v0.198.0
LastKey is when someone last typed into an owned session from a terminal; zero before, and for a session that is not Caprock's.
func (*Manager) MarkFreed ¶ added in v0.159.0
End stops an owned session the way a user closing its tab means it: asked first (SIGTERM, resumed if paused so it can act on it), so Claude Code flushes its transcript and the conversation can be continued with --resume; killed only if it is still running after endGrace. It returns once the request is sent; the kill, if needed, follows in the background. MarkFreed notes that the next End of this session frees memory: the exit it records says so (ExitReport.Freed).
func (*Manager) Nudge ¶ added in v0.117.2
Nudge is the newest input noted for a session Caprock holds; false for any other session, and for one nothing was typed into.
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) OpenCodeVersion ¶ added in v0.93.0
OpenCodeVersion is the version of the OpenCode this machine would start, "" while unknown. It never blocks: the first call asks in the background.
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) OwnedRunningKind ¶ added in v0.92.0
OwnedRunningKind lists the running sessions Caprock started with one coding agent ("claude", "codex", …). The plan-window stop pauses only Claude Code: Anthropic's window is not spent by a Codex or Gemini session.
func (*Manager) PasteMode ¶ added in v0.132.0
PasteMode reports whether an owned session's output has turned bracketed paste on and not off again.
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 oldest prompt an owned session waits on, with every other outstanding one in Waiting.
func (*Manager) PromptHolds ¶ added in v0.132.0
PromptHolds reports whether an owned session's screen still shows text in its prompt — typed but not sent — and nothing else that an Enter would answer: no permission or question menu on the screen.
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) Restarting ¶ added in v0.109.0
Restarting reports whether an owned session is being stopped to be resumed in another mode: its terminals reconnect to the new process rather than closing.
func (*Manager) ResumeOwned ¶ added in v0.92.0
ResumeOwned resumes a session Caprock started, reporting whether it did. Like PauseOwned it refuses, quietly, any id this manager does not own: the plan-window stop resumes what it paused hours earlier, and the session may have ended — or never been ours — by then.
func (*Manager) RunAtPrompt ¶ added in v0.102.0
RunAtPrompt types one line as TypeAtPrompt does and then presses Enter: a saved command the user picked to run (ADR-051). Still one line: anything from the first line break on is dropped, so what runs is what was shown.
func (*Manager) SessionMode ¶ added in v0.109.0
func (m *Manager) SessionMode(sessionID string) (mode string, source ModeSource, facts LaunchFacts, ok bool)
SessionMode is an owned Claude Code session's permission mode, as best known now: its footer, else the newest of its hooks and Caprock's own switches, else its command line. ok is false for a session this manager did not start.
func (*Manager) SessionPID ¶ added in v0.198.0
SessionPID is the pid of a running session's own program (the child of its pty-host), 0 when this daemon does not hold it.
func (*Manager) SetBinary ¶ added in v0.171.0
SetBinary points agent at the binary at path, for a test's fake.
func (*Manager) SetRestarting ¶ added in v0.109.0
SetRestarting marks or clears a session as being restarted.
func (*Manager) ShellJob ¶ added in v0.185.2
ShellJob is ShellProgram with the job it names (fgproc.Job), 0 when the shell is idle: what the daemon matches a session's process against to name a shell tab after the agent running in it.
func (*Manager) ShellProgram ¶ added in v0.94.2
ShellProgram is the program running in front of shell id's prompt — "claude", "npm", "vim" — or "" when the shell is idle, unknown or not a shell. Closing an idle shell's tab ends it; a busy one asks first (.ai/21-app.md § Shell tabs). Read at most every fgTTL per shell, and only for a shell Caprock started (rule 7: this reads, it never signals).
func (*Manager) ShellScreen ¶ added in v0.198.0
ShellScreen is what shell id's terminal shows now, a row a line, read from its output ring (termbuf.Screen): the setup checklist's runs read the last line and the GitHub CLI's one-time code from it (issue #1088). false when id is no shell Caprock started.
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) StopForRestart ¶ added in v0.109.0
StopForRestart ends an owned session's process and waits for it to be gone, so the same conversation can be resumed under its own id with no second writer on its transcript. The session is asked first (SIGTERM; Claude Code writes its transcript on the way out) and killed after restartGrace. Rule 7: only a session this manager started.
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) SwitchMode ¶ added in v0.109.0
SwitchMode presses Shift+Tab in an owned Claude Code session until its footer shows target, one press at a time, reading the footer after each. It returns the mode the session is left in. Nothing is typed into a session showing a permission menu; a press that changes nothing stops it (ErrModeStuck), and so does coming back round to a mode already passed (ErrModeUnreachable).
func (*Manager) TypeAtPrompt ¶ added in v0.99.0
TypeAtPrompt types one line into a shell Caprock started, once the shell has drawn its prompt, and does not press Enter: the user reads the command and runs it (an agent's install or sign-in, ADR-046). A line break in text is cut off there, so nothing can run by itself. Rule 7 holds: the shell is Caprock's.
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 ModeSource ¶ added in v0.109.0
type ModeSource string
ModeSource says where a mode was learned.
const ( SourceScreen ModeSource = "screen" // the footer, read now SourceHook ModeSource = "hook" // the session's own hook payload SourceSwitch ModeSource = "switch" // a switch Caprock made and saw take SourceLaunch ModeSource = "launch" // the command line it started with )
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 are outstanding besides this one.
Queued int `json:"queued,omitempty"`
// AgentID and AgentType name the subagent that asked; empty when the
// main thread did. Claude Code draws a subagent's dialog in the parent's
// terminal, and a card that did not say whose it was read as the
// parent's own request.
AgentID string `json:"agent_id,omitempty"`
AgentType string `json:"agent_type,omitempty"`
// Waiting is every outstanding prompt, oldest first and this one
// included, when there is more than one; no button answers any of them.
Waiting []Permission `json:"waiting,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 chat: Caprock picks the directory when Cwd is empty (ADR-071), else it runs in Cwd (ADR-091)
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
// WorktreeBase is the branch a new worktree starts from (HEAD when empty);
// WorktreePull fetches it from its remote first.
WorktreeBase string `json:"worktree_base,omitempty"`
WorktreePull bool `json:"worktree_pull,omitempty"`
// WorktreePR starts the new worktree from a GitHub pull request's head
// instead: refs/pull/<n>/head, fetched from the repository's remote with
// the user's own git credentials (prStartPoint). Needs Worktree; not with
// WorktreeBase.
WorktreePR int `json:"worktree_pr,omitempty"`
Model string `json:"model,omitempty"` // --model
PermissionMode string `json:"permission_mode,omitempty"` // --permission-mode
// Effort is the reasoning effort the session starts at, "" for the
// agent's own default: Claude Code's --effort, Codex's
// model_reasoning_effort (effort.go). Dropped for an agent that takes
// none at launch.
Effort string `json:"effort,omitempty"`
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:"-"`
// Subscription is the sign-in to run on (ADR-048): a subscription id from
// Settings → Subscriptions, or "" (or "default") for the user's normal
// one. Claude Code and Codex only. Recorded on the session.
Subscription string `json:"subscription,omitempty"`
// ConfigDir is that subscription's configuration directory, set by the
// daemon from its own settings — never from the request, so a page cannot
// point a session at a directory of its choosing. It becomes
// CLAUDE_CONFIG_DIR or CODEX_HOME in the child's environment.
ConfigDir string `json:"-"`
// DeepSeekKey is the user's DeepSeek key, for a Claude Code session on
// DeepSeek (Subscription subs.DeepSeekID). Like GeminiKey it is never
// accepted from the browser: the daemon fills it in from its settings.
DeepSeekKey string `json:"-"`
// KimiKey is the user's Kimi platform key, for a Claude Code session on
// Kimi (Subscription subs.KimiID); filled by the daemon like DeepSeekKey.
KimiKey string `json:"-"`
// SubagentModel is the model Claude Code's subagents run on:
// "haiku", "sonnet" or "opus" (SubagentModels), or "" to follow the
// session. It becomes CLAUDE_CODE_SUBAGENT_MODEL in the child's
// environment; nothing else from the request reaches it.
SubagentModel string `json:"subagent_model,omitempty"`
// EndWhenDone asks the daemon to end the session, the way End does,
// once its turn finishes with nothing waiting on anyone: a scripted
// one-job start that would otherwise sit idle at its prompt for good
// (daemon/enddone.go). Claude Code and Codex only, with a prompt.
EndWhenDone bool `json:"end_when_done,omitempty"`
// Automation says a scheduled job started this session, not a person:
// Second Brain never reads it and hands it nothing (store.
// MarkBrainAutomation, written in the spawn's transaction). Nothing else
// in Caprock changes for it.
Automation bool `json:"automation,omitempty"`
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"`
// Copied says what .worktreeinclude brought over from the main checkout
// (internal/wtsetup), empty when nothing was.
Copied string `json:"copied,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).