api

package
v0.155.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 84 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

A short-lived cache in front of the whole-history aggregates, with single-flight and stale-while-revalidate.

/v1/history and the wide ranges of /v1/stats/summary (7d, 30d, all) answer from aggregates over the whole events table. On the owner's 1 GB database (333k events, 2026-10-04) /v1/history?range=all is ~1.5s and /v1/stats/summary?range=all ~1.0s through the Go driver, and the expensive half is per-row driver work over a covering scan — there is no index that fixes it. Measured under a live dashboard, where the same screen fires a dozen requests at once while ingest commits several times a second, those figures were 4.7s and 1.5s.

What makes that hurt is how often it is asked. Five components on the main screen call `api.history('all')` on their own timers, the share dialog asks for today, 7d, 30d and all at once, and every one of them used to compute from scratch. Three things fix that, and none is a faster query:

  • **Single-flight.** Requests for the same key that arrive while one is already running wait for it and share its result, instead of starting their own. This is what collapses a burst.
  • **A short TTL.** Lifetime figures move by one turn at a time; an answer younger than the TTL is handed back as it is.
  • **Stale-while-revalidate.** An answer older than the TTL is still handed back at once, and a single background refresh replaces it. Nobody waits on a whole-table scan once the key has been computed — the cost moves off the request and onto one goroutine. What the reader sees is at most one refresh behind: the figure computed when the screen last asked. Past maxStale an answer is too old to show, and the caller waits for a fresh one as if there were none.

The daemon also warms the common keys when it starts (Server.Warm), so the first screen after a restart does not pay for the scan either.

Keys carry the range's resolved start, not just its label, so "today" and "7d" roll over at midnight: a new day is a new key, computed fresh, never yesterday's answer served under today's name.

Writes do not invalidate. Wiring ingest into an HTTP cache would couple the recorder to the API, and with ingest committing several times a second while anyone works, an invalidated cache is an empty one exactly when the screen is busiest. The live figures — today's cost, the burn rate, the session cards — do not come through this cache at all.

Package api serves the loopback HTTP surface: REST queries under /v1, the /v1/live WebSocket, the hook receiver, and the embedded dashboard at /. Contract: .ai/03-contracts.md § HTTP API. JSON is snake_case, money is USD float, tokens are int64.

Picking a folder without typing its path.

Starting a session meant typing an absolute path into a text field from memory — on a dashboard that is already displaying the repositories the reader works in every day. The two things that removes the typing are the directories they have used before, and a way to walk the one place they keep their code.

Why this is not a file picker

A browser cannot open a native directory chooser without a user gesture that grants access to that directory alone, and what the daemon needs is a path string it can `cd` into. So the walking happens server-side, which means the daemon is being asked to list directories on behalf of a web page — and that is the whole security question here.

What stops this being a filesystem-read API

Three things, in order of how much they matter:

  1. **Only directories, only names.** No file contents, no sizes, no reading of anything. The response is a list of names and whether each holds a git repository.
  2. **Rooted, and the root is the user's own setting.** Everything is resolved against `BrowseRoot` (default `$HOME`) and a path that escapes it is refused. Symlinks are resolved *before* the check, so a link inside the root pointing out of it does not smuggle a caller past the boundary.
  3. **Hidden entries stay hidden.** `.ssh`, `.aws`, `.config` are not interesting for picking a repository and are exactly what someone probing would want. `.git` is reported as a *property* of its parent, never as somewhere to descend into.

The CSRF guard in csrf.go already prevents a page on another origin from calling this at all; the rules above are what remains true even for a page that legitimately can.

The session deck's Pull requests & CI cell answers from what the daemon last put together for it.

Each of its views (GET /v1/sessions/{id}/prs, …/ci, …/ci/release, …/ci/main, …/branches) is composed from reads the GitHub service keeps (github.PullByURL, CIBySHA, ReleaseByRepo, MainCI, PullsByBranch), each with its own freshness. While those hold, composing is milliseconds; once one has expired, composing waits on GitHub — four pull requests read one after the other, three calls each, so seconds — and the deck, which is unmounted while closed, opened on an empty cell for that long (owner, 2026-10-13, translated: "for a while nothing is shown, it looks frozen and empty").

So the composed answer is kept per session, view and pull request (deckCache), and asked through answerCache:

  • A request for a key never composed waits for it, as before, and concurrent ones share the one composition.
  • Past deckTTL a request starts one background composition and waits up to deckBudget for it: when the sources answer from what they hold, the reader gets the fresh answer; when one has to ask GitHub, the reader gets the last answer at once, marked `refreshing`, and the next poll finds the new one.
  • Every answer says when it was composed (`fetched_at`, Unix ms), so the deck can say how fresh what it shows is.
  • A background composition that fails leaves the last answer in place and says so: `refresh_error` and `refresh_failed_at` ride on that answer, and the next composition waits deckFailBackoff. Before, a composition that failed every time (GitHub slower than its deadline) restarted on every poll and the reader saw the old answer marked `refreshing` for as long as it was kept — a bare "updating…" over a board frozen for hours (owner, 2026-10-14).

GitHub is asked no more than before: a composition calls the same kept reads as the request used to, each still deciding by its own freshness whether to ask, and a burst of requests for one key composes once. Whether GitHub is connected is part of the key, so connecting is not answered with the "not connected" answer kept from before.

Finding a repository by a few letters of its name.

The New agent sheet asked for a project from a native select, and Add a project for a path typed from memory: the owner typed ~/dev/caprock-website for ~/dev/caprock-web and was told only "no such folder" (2026-10-10). Both sheets now search, and what they search includes the git repositories under the default folder — the place the user keeps code — which only the daemon can see. The page never walks the disk; it asks this endpoint once and filters the answer as the user types.

The same rules as GET /v1/browse hold (browse.go): names and paths only, nothing read inside a repository, hidden directories skipped, the scan rooted inside the browse root, and places macOS guards never opened.

Index

Constants

View Source
const (
	DescriptionName   = "name"
	DescriptionTitle  = "title"
	DescriptionPrompt = "prompt"
)

DescriptionSource says where a description came from.

View Source
const (
	// OpenResume carries an ended session on in the user's terminal.
	OpenResume = "resume"
	// OpenMove stops Caprock's own process for the session, then resumes the
	// same conversation in the user's terminal.
	OpenMove = "move"
	// OpenFork branches a live session into the user's terminal under a new
	// id; the original keeps running where it is.
	OpenFork = "fork"
)

Open-in-terminal modes.

View Source
const (
	StageDraft    = "draft"
	StageOpen     = "open"  // open, its checks running (or not read)
	StageFix      = "fix"   // a red check, a conflict or changes requested
	StageReady    = "ready" // green or no checks: waiting for a review or a merge
	StageMerged   = "merged"
	StageReleased = "released"
)

Board stages, in the order a pull request moves through them.

View Source
const (
	ShipsByRelease = "release" // a published release or a version tag within shipsRecentDays
	ShipsByMerge   = "merge"   // neither, both read: merged is the last step
)

How merged work ships in a repository (PRBoard.ShipsBy; owner, 2026-10-18, translated: "why isn't merged the final state — there's one more step after it"). A site deployed on every merge publishes no release, so its merges never wait for one.

View Source
const (
	SeriesFlight     = "flight"
	SeriesThroughput = "throughput"
	SeriesCI         = "ci"
	SeriesTTM        = "ttm"
	SeriesLag        = "lag"
	SeriesCost       = "cost"
)

The series' keys: the figure each one belongs to (FlowFigures' keys).

View Source
const (
	WaitingTurn       = "turn"       // the agent is working
	WaitingPermission = "permission" // a permission prompt is on the screen
	WaitingQuestion   = "question"   // the agent asked a question (AskUserQuestion)
)

Why a message is waiting, as GET /v1/agents/{id}/queue and the "queue" frame say it. Empty: nothing holds it.

View Source
const (
	WorkWorking    = "working"
	WorkPermission = "permission"
	WorkQuestion   = "question"
	WorkAtPrompt   = "at_prompt"
	// WorkBackground: the turn ended and subagents it started still work;
	// the session wants nothing from anyone.
	WorkBackground = "background"
)

Work session states.

View Source
const (
	// LinkRecorded: the session's own `gh pr` commands named the pull
	// request (session_prs).
	LinkRecorded = "recorded"
	// LinkBranch: the session works on a branch other than the default; a
	// pull request whose head is that branch is its.
	LinkBranch = "branch"
	LinkNone   = "none"
)

How a session is tied to a pull request.

View Source
const BrainDecisionsMax = 100

BrainDecisionsMax is the most current decisions GET /v1/brain/decisions returns.

View Source
const QueueMax = 20

QueueMax is how many messages one session's queue holds.

View Source
const QueueTextMax = 16 << 10

QueueTextMax is the longest message, in bytes.

View Source
const (
	// TermV2Protocol is the subprotocol a client asks for v2 with.
	TermV2Protocol = "caprock.term.v2"
)

Terminal protocol v2 (.ai/21-app.md § Terminal protocol v2; the contract is in .ai/03-contracts.md). Version 1 replays a snapshot on every connect and carries no positions, so a reconnect repaints the screen and a keystroke sent into a dying socket is either lost or, on retry, typed twice. Here every output byte has an offset and every input frame a sequence number.

Variables

View Source
var (
	// ErrQueueFull is the 21st message.
	ErrQueueFull = errors.New("this session already has 20 messages waiting")
	// ErrPromptWaiting refuses Send now while a menu is on the screen: the
	// text would answer it.
	ErrPromptWaiting = errors.New("the session is showing a prompt; answer it first, in the terminal or with the buttons")
	// ErrNotOwned is a session Caprock did not start, or that has ended
	// (rule 7: it types only into its own).
	ErrNotOwned = errors.New("caprock did not start this session, or it has ended, so it does not type into it")
)
View Source
var (
	// ErrSubscriptionPremium: the agent already has the free number of
	// subscriptions and there is no licence.
	ErrSubscriptionPremium = errors.New("premium required")
	// ErrSubscriptionInUse: a session Caprock started is running on it.
	ErrSubscriptionInUse = errors.New("a session is running on this subscription")
	// ErrSubscriptionNotFound: no subscription with that id.
	ErrSubscriptionNotFound = errors.New("no such subscription")
)

Errors a SubscriptionManager answers with, mapped to statuses here.

View Source
var ErrBrainAutoOff = errors.New("turn on building Second Brain automatically first")

ErrBrainAutoOff is a backfill asked for while the automatic extraction is off: it reads nothing until the user has said yes to it.

View Source
var ErrBypassConsent error = bypassConsentError{}

ErrBypassConsent is StartSession refusing a Bypass start before the one-time consent (ADR-041).

Functions

func BusyIn added in v0.112.1

func BusyIn(ctx context.Context, st *store.Store, shells ShellController) projects.BusyFunc

BusyIn answers what runs in a folder or below it: every session not ended whose working directory is there, and every shell tab started there. Read once per call; the daemon's copies cleanup uses it too.

func Describe added in v0.74.0

func Describe(ctx context.Context, q store.Querier, sess store.Session) string

Describe is a session's name as Now shows it, for a caller outside the API: the phone alerts name a session the way its card does.

func DescribeWithSource added in v0.118.0

func DescribeWithSource(ctx context.Context, q store.Querier, sess store.Session) (text, source string)

DescribeWithSource is Describe and where the text came from (name, title or prompt), for a daemon-side view that styles a guess apart from a name.

func DistFS

func DistFS() fs.FS

DistFS returns the embedded UI filesystem: the built dashboard when present, else the placeholder page.

func MaskKey added in v0.114.0

func MaskKey(k string) string

MaskKey is how Settings names a stored key without revealing it: its first three and last four characters ("sk-…1a2b"), enough to tell two keys apart and nowhere near enough to use one. A key too short for that to hide most of it is shown as "…" alone; no key is "".

func OrderBranches added in v0.111.0

func OrderBranches(bs []SessionBranch)

OrderBranches puts the current branch first, then the rest by their last activity, newest first, the name breaking ties.

func SaveFile added in v0.137.0

func SaveFile(dataDir string, now time.Time, rawName, mimeType string, raw []byte) (string, error)

SaveFile writes a file that did not come from a browser — one forwarded to the Telegram bot (ADR-081) — into the paste folder with the checks POST /v1/paste makes (the allow-list, plus voice notes and audio; 10 MB; a directory of its own; 0600), and returns its path.

func UIBuilt

func UIBuilt() bool

UIBuilt reports whether the real dashboard is embedded.

Types

type ActivityResponse added in v0.108.0

type ActivityResponse struct {
	From     int64            `json:"from"`
	BucketMs int64            `json:"bucket_ms"`
	Buckets  int              `json:"buckets"`
	Sessions map[string][]int `json:"sessions"`
}

ActivityResponse is GET /v1/activity: each session's turns and tool calls over the last hour in two-minute buckets, oldest first, for the sidebar's per-project sparkline. Sessions with nothing in the hour are absent.

type AdminController added in v0.131.0

type AdminController interface {
	AdminKey() string
	SetAdminKey(string) error
}

AdminController keeps the admin key that opens private modules (ADR-076). The API verifies the key; the controller only stores it.

type AdminState added in v0.131.0

type AdminState struct {
	Admin bool `json:"admin"`
	// KeyError says why a stored key does not verify. Present only when one
	// was stored, so it says nothing to anyone who never pasted one.
	KeyError  string       `json:"key_error,omitempty"`
	Subject   string       `json:"subject,omitempty"`
	Modules   []string     `json:"modules,omitempty"`
	Installed []ModuleInfo `json:"installed,omitempty"`
}

AdminState is GET /v1/admin.

type AgentCatalog added in v0.99.0

type AgentCatalog interface {
	// Catalog lists every agent Caprock knows here, built-in and custom, with
	// what each is missing.
	Catalog() CatalogResponse
	// Custom is the stored list of custom agents, whatever the licence says.
	Custom() []config.CustomAgent
	// SetCustom replaces it with a list already validated.
	SetCustom(list []config.CustomAgent) error
}

AgentCatalog is what the agent pickers read and the custom agents are kept in (ADR-046). The daemon implements it; the API only routes and gates.

type AgentController

type AgentController interface {
	// Available reports whether any agent can be started here.
	Available() bool
	// Has reports whether one agent ("claude", "codex", …) can be started.
	Has(agent string) bool
	Spawn(ctx context.Context, req any) (id string, cwd string, err error)
	Input(sessionID string, data []byte) error
	Signal(sessionID, action string) error
	Resize(sessionID string, cols, rows int) error
	Term(sessionID string) (snapshot []byte, sub <-chan []byte, cancel func(), ok bool)
	// Holds reports whether this daemon has the session's terminal. A session
	// Caprock started under an older release, or whose pty-host died, does
	// not (ADR-033).
	Holds(sessionID string) bool
	Write(sessionID string, data []byte) error
}

AgentController is the subset of internal/agents the API needs (interface for tests).

type AlertSender added in v0.72.0

type AlertSender interface {
	SendAlertCheck(ctx context.Context) error
}

AlertSender sends one test phone alert through the configured bot.

type AttemptView added in v0.102.0

type AttemptView struct {
	store.Attempt
	Session store.Session `json:"session"`
	Stats   store.Stats   `json:"stats"`
	// Changes is what its copy changed since the commit it started from;
	// absent with ChangesError when that could not be read (the folder was
	// removed, git failed).
	Changes      *gitdiff.Totals `json:"changes,omitempty"`
	ChangesError string          `json:"changes_error,omitempty"`
}

AttemptView is one attempt as the Compare view shows it.

type Bill added in v0.70.0

type Bill struct {
	InputUSD      float64 `json:"input_usd"`
	OutputUSD     float64 `json:"output_usd"`
	CacheWriteUSD float64 `json:"cache_write_usd"`
	CacheReadUSD  float64 `json:"cache_read_usd"`
	// UnpricedTokens belong to models with no pricing row and are in no
	// figure above.
	UnpricedTokens int64 `json:"unpriced_tokens,omitempty"`
}

Bill is the cost of each type of token. CacheRead is the context tax.

type BoardCard added in v0.116.0

type BoardCard struct {
	Number int    `json:"number"`
	Stage  string `json:"stage"`
	// StageAt is since when it is in the stage (unix ms): opened, its checks'
	// start or end, merged, released. Absent when not known.
	StageAt int64 `json:"stage_at,omitempty"`
	// CI is its head commit's checks: running | fail | pass | none; absent
	// when not read.
	CI string `json:"ci,omitempty"`
	// Why is what put it in fix: ci | conflict | changes_requested.
	Why string `json:"why,omitempty"`
	// Failed names what failed when Why is ci: the failed checks (or, read
	// from the runs list, workflows), at most failedNames, so the Pipeline
	// row can say which without opening the pull request.
	Failed []string `json:"failed,omitempty"`
	// OS is its checks by the OS their names say — "go (windows-latest)",
	// "test (macos)" — one entry per OS named (linux, macos, windows, in that
	// order), so the release plan can draw a dot per OS and say which one it
	// waits for. Absent without a live read, or when no check names an OS.
	OS []BoardOS `json:"os,omitempty"`
	// CIMS is how long its head commit's checks took, the first one's start
	// to the last one's finish (unix ms span), once they are all done; absent
	// while they run or when the stamps were not read.
	CIMS   int64  `json:"ci_ms,omitempty"`
	Review string `json:"review,omitempty"`
	// Release is the tag it shipped in (released only).
	Release string `json:"release,omitempty"`
	// Spend is the agent work Caprock recorded for it (store.SpendByPR).
	Spend store.PRSpend `json:"spend"`
	// Stale says its checks are from an earlier read: this composition could
	// not read them again in time (or GitHub refused), so the card is drawn
	// as not re-confirmed.
	Stale bool `json:"stale,omitempty"`
}

BoardCard is one pull request on the board; its title, author and link are the prs entry with the same number.

type BoardDone added in v0.110.0

type BoardDone struct {
	SessionID string `json:"session_id"`
	Agent     string `json:"agent"`
	Title     string `json:"title,omitempty"`
	Project   string `json:"project,omitempty"`
	Prompt    string `json:"prompt"`
	StartedAt int64  `json:"started_at"`
	EndedAt   int64  `json:"ended_at"`
	// Queued: the prompt was a queued message Caprock typed in.
	Queued bool `json:"queued,omitempty"`
	// Failed: the turn ended on a StopFailure (a limit, an overload).
	Failed bool `json:"failed,omitempty"`
}

BoardDone is one finished turn.

type BoardFlow added in v0.116.0

type BoardFlow struct {
	Counts map[string]int `json:"counts"`
	Days   int            `json:"days"`
	// Merged counts the merges in the window; TTMMedianMS is opened to
	// merged (github.TimeToMerge).
	Merged      int   `json:"merged"`
	TTMMedianMS int64 `json:"ttm_median_ms,omitempty"`
	TTMCount    int   `json:"ttm_count"`
	// ReleaseLagMedianMS is merged to released, over the window's released
	// cards: an estimate, the release matched by time. Absent with fewer
	// than two.
	ReleaseLagMedianMS int64 `json:"release_lag_median_ms,omitempty"`
	ReleaseLagCount    int   `json:"release_lag_count"`
	// ReleaseGapMedianMS is the median time between consecutive published
	// releases among those already read (the newest ten): how often the
	// repository ships, measured, never a date for the next one (ADR-064).
	// Absent with fewer than three gaps.
	ReleaseGapMedianMS int64 `json:"release_gap_median_ms,omitempty"`
	ReleaseGapCount    int   `json:"release_gap_count"`
	// CIMedianMS is the busiest workflow's median successful run.
	CIMedianMS int64 `json:"ci_median_ms,omitempty"`
	// CostUSD sums the cards' agent cost.
	CostUSD float64 `json:"cost_usd"`
	// Series is each figure's day by day over the window, keyed by the
	// figure (flight, throughput, ci, ttm, lag, cost; prboardseries.go).
	// Needs a fix and Ready have none: a past day's check state is not read.
	Series map[string][]FlowPoint `json:"series"`
}

BoardFlow is the strip above the board.

type BoardItem added in v0.110.0

type BoardItem struct {
	store.QueuedMessage
	// Position is 1 for the message typed in when the current turn ends.
	Position int  `json:"position"`
	Start    *ETA `json:"start,omitempty"`
	Finish   *ETA `json:"finish,omitempty"`
}

BoardItem is one queued message.

type BoardOS added in v0.125.0

type BoardOS struct {
	OS string `json:"os"` // linux | macos | windows
	// State is fail when any of its checks failed, else running while any
	// is unfinished, else pass.
	State string `json:"state"`
	// Since is, while running, the earliest start of its unfinished checks
	// (unix ms); absent when none has started.
	Since int64 `json:"since,omitempty"`
	// Checks is how many of its checks there are (skipped ones left out).
	Checks int `json:"checks"`
}

BoardOS is one OS's checks on a pull request's head commit.

type BoardRelease added in v0.116.0

type BoardRelease struct {
	github.RepoRelease
	// PRs are the pull requests merged into the default branch after the
	// release before it was published and up to this one: matched by time,
	// from the listed pull requests.
	PRs      []int   `json:"prs"`
	CostUSD  float64 `json:"cost_usd"`
	Sessions int     `json:"sessions"`
	// Partial says the listed pull requests may not reach back to the
	// release before it, so some of its merges may be missing.
	Partial bool `json:"partial,omitempty"`
}

BoardRelease is one published release and the merges it shipped.

type BoardSession added in v0.110.0

type BoardSession struct {
	SessionID string `json:"session_id"`
	Agent     string `json:"agent"`
	Title     string `json:"title,omitempty"`
	Project   string `json:"project,omitempty"`
	// Dir is the project the estimate groups by: the repository root, else
	// the folder.
	Dir    string `json:"dir,omitempty"`
	Branch string `json:"branch,omitempty"`
	// Waiting is the queue's own: "turn", "permission", "question", or ""
	// at its prompt (§ Queued messages).
	Waiting string `json:"waiting"`
	// TurnStartedAt is when the running turn's prompt was sent, unix ms; 0
	// when none runs or it is not known.
	TurnStartedAt int64      `json:"turn_started_at,omitempty"`
	Todo          *BoardTodo `json:"todo,omitempty"`
	// Queue is the session's queued messages, oldest first, each with its
	// place and estimate.
	Queue []BoardItem `json:"queue"`
	// TurnLeft is the running turn's remaining time; absent without an
	// estimate or a running turn.
	TurnLeft *ETA `json:"turn_left,omitempty"`
	// FreeIn is when a message added now would start: 0 at the prompt with
	// nothing queued; absent when it cannot be estimated.
	FreeIn   *ETA      `json:"free_in,omitempty"`
	Estimate *Estimate `json:"estimate,omitempty"`
	// EstimateNote says why there is no estimate, when there is none.
	EstimateNote string `json:"estimate_note,omitempty"`
}

BoardSession is one session Caprock started and still runs.

type BoardTodo added in v0.110.0

type BoardTodo struct {
	// Active is the in-progress item's active form, else its text.
	Active string `json:"active,omitempty"`
	Done   int    `json:"done"`
	Total  int    `json:"total"`
}

BoardTodo is the agent's own task list, summed up.

type BrainAuto added in v0.117.1

type BrainAuto interface {
	// Status is its state for GET /v1/brain/status.
	Status(ctx context.Context) any
	// Configure applies PUT /v1/brain/settings and saves it.
	Configure(ctx context.Context, set BrainSettings) error
	// Estimate is what a backfill of the last days would read.
	Estimate(ctx context.Context, days int) (any, error)
	// Backfill asks for the last days to be read.
	Backfill(ctx context.Context, days int) error
	// DailyTokens is the daily limit the reads keep to.
	DailyTokens() int64
}

BrainAuto is the automatic extraction (internal/brain), wired by the daemon. Nil in builds and tests without it.

type BrainHandoffState added in v0.125.0

type BrainHandoffState struct {
	// On is Settings → Memory between sessions: off, no session is handed
	// anything.
	On bool `json:"on"`
	// LeftOffAt is when the passage a new session would be handed was
	// written, unix ms; 0 when none is recent enough, and then nothing goes.
	LeftOffAt int64 `json:"left_off_at,omitempty"`
	// HoldoutPct is the share of new sessions held back at random to
	// measure whether the handoff helps.
	HoldoutPct int `json:"holdout_pct"`
}

BrainHandoffState is whether a new session in a repository would be served a handoff, which is what carries Second Brain's memories to it.

type BrainHandoffView added in v0.125.0

type BrainHandoffView struct {
	Project string `json:"project"`
	// Decisions are the current decisions, newest first, handed first.
	Decisions []store.BrainNode `json:"decisions"`
	Memories  []store.BrainNode `json:"memories"`
	// Max is how many memories it may carry; Budget the runes they share.
	// DecisionsMax and DecisionsBudget are the same for the decisions.
	Max             int `json:"max"`
	Budget          int `json:"budget"`
	DecisionsMax    int `json:"decisions_max"`
	DecisionsBudget int `json:"decisions_budget"`
	// Served is BrainHandoffState, when the daemon wires it.
	Served *BrainHandoffState `json:"served,omitempty"`
}

BrainHandoffView is GET /v1/brain/handoff: the current decisions and the memories a new session in the project is handed, picked by the same code the SessionStart handoff uses (store.BrainHandoff), and whether one would be served now.

type BrainSettings added in v0.117.2

type BrainSettings struct {
	Auto        *bool   `json:"auto,omitempty"`
	DailyTokens *int    `json:"daily_tokens,omitempty"`
	Model       *string `json:"model,omitempty"`
}

BrainSettings is PUT /v1/brain/settings; a nil field is left as it is.

type BrainSpend added in v0.148.0

type BrainSpend struct {
	// Days is one entry per local day, oldest first, today the last.
	Days []store.BrainDaySpend `json:"days"`
	// Projects is the same window by the read session's project, most
	// tokens first.
	Projects []store.BrainProjectSpend `json:"projects"`
	// DailyTokens is the daily limit; 0 in a build without the extraction.
	DailyTokens int64 `json:"daily_tokens"`
	// Spent24h is the reads' tokens in the last 24 hours (the status's
	// `spent`); ClaudeTokens24h is Claude Code's assistant turns in the
	// recorded sessions over the same 24 hours, the reads not among them.
	Spent24h        int64 `json:"spent_24h"`
	ClaudeTokens24h int64 `json:"claude_tokens_24h"`
}

BrainSpend is GET /v1/brain/spend (03-contracts.md § Second Brain): what the automatic extraction's reads spent (brain_runs), per local day and per project, and the figures its share of all Claude Code tokens in the last 24 hours is counted from.

type BrainStatus added in v0.117.1

type BrainStatus struct {
	// Memories is how many memories there are; Manual how many were dropped
	// in by hand.
	Notes    int                       `json:"notes"`
	Memories int                       `json:"memories"`
	Manual   int                       `json:"manual"`
	Projects []store.BrainProjectCount `json:"projects"`
	// Auto is the automatic extraction's state, when it is wired.
	Auto any `json:"auto,omitempty"`
	// DBPath is the database the memories live in, resolved from the
	// daemon's data directory (config.DBPath), so the screen's "Where it's
	// kept" names the real file, not a guess per OS. Omitted without one.
	DBPath string `json:"db_path,omitempty"`
}

BrainStatus is GET /v1/brain/status.

type BrowserController added in v0.129.0

type BrowserController interface {
	// List is the installed browsers, the default first.
	List() []browser.Browser
	// Open opens url (http or https) in the browser with this id.
	Open(ctx context.Context, id, url string) (browser.Browser, error)
}

BrowserController finds the web browsers installed here and opens a link in one (internal/browser): the chooser a ⇧⌘-click on a terminal link opens. nil ⇒ the endpoints answer 501.

type Burn

type Burn struct {
	WindowMin  int     `json:"window_min"`
	USDPerHour float64 `json:"usd_per_hour"`
	TokPerMin  float64 `json:"tokens_per_min"`
	Turns      int64   `json:"turns"`
	// Filling is true while the daemon has been up for less than the window,
	// so the screen can say "still measuring" rather than print a rate
	// extrapolated from a handful of seconds. Honest arithmetic on twenty
	// seconds of history still reads as an alarming number.
	Filling bool `json:"filling,omitempty"`
}

Burn is the recent spend rate ("$/hr equivalent, tokens/min") over a short window.

type CallTool added in v0.95.0

type CallTool struct {
	Tool   string `json:"tool"`
	Detail string `json:"detail,omitempty"`
}

CallTool is a tool call a model call asked for, with the short line the cockpit's tool list gives it.

type CatalogResponse added in v0.99.0

type CatalogResponse struct {
	Agents []agentcat.Entry `json:"agents"`
	// Licensed says whether custom agents may be added and started.
	Licensed bool `json:"licensed"`
	// Home is the folder a setup shell tab opens in.
	Home string `json:"home,omitempty"`
}

CatalogResponse is GET /v1/agents/catalog.

type ChatFile added in v0.126.0

type ChatFile struct {
	// Path is relative to the chat's folder, in slash form.
	Path     string `json:"path"`
	Size     int64  `json:"size"`
	Modified int64  `json:"modified"` // unix ms
	// Kind is how the viewer shows it: markdown, html, pdf, image, text, or
	// other (offered as a download).
	Kind string `json:"kind"`
}

ChatFile is one file a chat wrote in its folder.

type ChatImport added in v0.129.0

type ChatImport struct {
	chatimport.Result
	Error string `json:"error,omitempty"`
}

ChatImport is POST /v1/chats/import's answer: what was imported, and where it stopped when a conversation could not be read.

type ChatList added in v0.126.0

type ChatList struct {
	Items    []SessionSummary `json:"items"`
	Total    int              `json:"total"`
	Chats    int              `json:"chats"`
	Archived int              `json:"archived"`
}

ChatList is GET /v1/chats: one page of chats, newest first, with how many match and how many there are, archived and not.

type ContextFill

type ContextFill struct {
	Tokens int64   `json:"tokens"`
	Window int64   `json:"window"`
	Pct    float64 `json:"pct"`
	// NextCallUSD is what the next tool call costs at this context before it
	// does any work, because every call re-reads the whole conversation as a
	// cache read. It is the marginal figure, and the marginal figure is the
	// one that makes a full context legible: a percentage says the window is
	// nearly full, this says what that is charging per call.
	NextCallUSD float64 `json:"next_call_usd"`
}

ContextFill is the "context fill %" badge input: last turn's prompt size vs the model window.

type Costliest added in v0.153.0

type Costliest struct {
	Repo   string `json:"repo,omitempty"`
	Reason string `json:"reason,omitempty"`
	// Days is the period (0 = all time); Since its start (unix ms, 0 for
	// all time): Days local calendar days ending today, as the board's
	// window is counted.
	Days  int   `json:"days"`
	Since int64 `json:"since,omitempty"`
	// PRs are the dearest pull requests that moved in the period (merged,
	// closed or last active), at most costliestShown.
	PRs []store.KnownPR `json:"prs"`
	// PRsCounted is how many pull requests with a recorded cost moved in the
	// period; PRsKnown how many of the repository's Caprock knows at all.
	PRsCounted int `json:"prs_counted"`
	PRsKnown   int `json:"prs_known"`
	// Releases are the dearest releases tagged in the period, at most
	// costliestShown; ReleasesCounted how many were tagged in it.
	Releases        []CostlyRelease `json:"releases"`
	ReleasesCounted int             `json:"releases_counted"`
	// TagsRead says the checkout's tags and history were read: false (no
	// checkout, git failing) is not "no releases".
	TagsRead bool `json:"tags_read"`
	// contains filtered or unexported fields
}

Costliest is GET /v1/sessions/{id}/ci/costliest.

type CostlyRelease added in v0.153.0

type CostlyRelease struct {
	Tag string `json:"tag"`
	At  int64  `json:"at"`
	URL string `json:"url"`
	// PRs are the pull requests its commits name.
	PRs     []int   `json:"prs"`
	CostUSD float64 `json:"cost_usd"`
	// Sessions sums its pull requests' sessions: a session cut between two
	// of them counts in each.
	Sessions int `json:"sessions"`
	// First says it is the oldest release on the line: it shipped
	// everything before it too.
	First bool `json:"first,omitempty"`
}

CostlyRelease is one release and what the pull requests it shipped cost.

type Deps

type Deps struct {
	Store *store.Store
	// Pairing decides which devices on the local network may be served. Nil
	// when LAN access is off, which is the default and the usual case — see
	// lanauth.go.
	Pairing *pairing.Store
	// LANURL is the address a second device types in, empty when LAN access is
	// off. Shown on the pairing screen and encoded in its QR code.
	LANURL string
	Bus    *bus.Bus
	Table  *cost.Table
	Log    *slog.Logger
	Hook   http.Handler // POST /v1/hook (hookd)
	// Reporter sends a weekly report on demand, so somebody can find out
	// whether their bot works without waiting for Monday. Nil disables the
	// endpoint rather than crashing it.
	Reporter ReportSender
	// Telegram is the bridge to the owner's bot (ADR-047): its setup and
	// pairing. Nil answers 501.
	Telegram TelegramController
	// Alerts sends a test phone alert on demand (ADR-036). Nil disables the
	// endpoint.
	Alerts AlertSender
	// PhoneLink sends the phone's page address to the owner's Telegram chat
	// ("Send the link to my phone", Settings → Use on your phone). Nil
	// answers 501.
	PhoneLink PhoneLinkSender
	UI        fs.FS // embedded dashboard (index.html at root); nil ⇒ placeholder
	Version   string
	// Status returns daemon/ingest/hooks status for /v1/status.
	Status func(ctx context.Context) any
	// InstallHooks registers the shim in Claude Code's settings, as
	// `caprock hooks install` does, and returns what is registered after.
	// nil ⇒ 501.
	InstallHooks func(ctx context.Context) (any, error)
	// BypassAccepted reports whether the user accepted Claude Code's one-time
	// bypass warning (hooks.BypassKey in user settings); AcceptBypass records
	// that they accepted Caprock's copy of it (ADR-041). nil ⇒ not checked,
	// and the route answers 501.
	BypassAccepted func() (bool, error)
	AcceptBypass   func() error
	// Storage returns what the data directory holds for /v1/storage. nil ⇒ 501.
	Storage func(ctx context.Context) any
	// Resources returns the resource meter's figures for GET /v1/resources;
	// ReapOrphans stops orphaned pty-hosts for POST /v1/resources/reap.
	// nil ⇒ 501.
	Resources   func(ctx context.Context) any
	ReapOrphans func(ctx context.Context) (any, error)
	// ResourceHistory returns the meter's kept samples after a unix-ms
	// time for GET /v1/resources/history. nil ⇒ 501.
	ResourceHistory func(sinceMs int64) any
	// Footprint returns what Caprock costs this machine for GET
	// /v1/footprint; orphans is ?orphans=1, which answers with the orphan
	// list (at most 30 s old), and fresh is &fresh=1, which takes it now.
	// StopOrphans stops processes from that list for POST
	// /v1/footprint/orphans/stop; force (the second click on one that
	// outlived SIGTERM) sends SIGKILL. nil ⇒ 501.
	Footprint   func(ctx context.Context, orphans, fresh bool) any
	StopOrphans func(ctx context.Context, targets []OrphanTarget, force bool) any
	// SystemMemory returns the machine's memory with the agents' states and
	// the other apps for GET /v1/system/memory; paired leaves the apps'
	// names out. EndIdleAgents ends the named idle agents Caprock started
	// for POST /v1/system/memory/end-idle. nil => 501.
	SystemMemory  func(ctx context.Context, paired bool) any
	EndIdleAgents func(ctx context.Context, sessionIDs []string) any
	// RestartEnd ends a heavy agent Caprock started and waits for it to exit,
	// so the dashboard can continue it fresh: POST /v1/system/memory/restart.
	RestartEnd func(ctx context.Context, sessionID string) any
	// KeepAwake returns whether the computer is being kept awake, for GET
	// /v1/keepawake (keepawake.Status). Nil ⇒ 501.
	KeepAwake func() any
	// OpenTabs keeps which sessions a dashboard has a tab for, for PUT
	// /v1/tabs: a session with a tab is never ended for idling
	// (daemon/endidle.go). nil ⇒ 501.
	OpenTabs func(viewer string, sessions []string) error
	// LatestTabs is the reported list GET /v1/tabs answers with, in tab-strip
	// order: the window on screen whose tabs changed last; ok is false when
	// no viewer's report counts. nil ⇒ 501.
	LatestTabs func() (sessions []string, at int64, ok bool)
	// WindowStop returns the plan-window stop's state for GET
	// /v1/window-stop: the share, whether a licence is active, the figures it
	// acts on and how fresh they are, and the sessions it has paused. nil ⇒ 501.
	WindowStop func(ctx context.Context) any
	// RateLimitsRecorded is called after POST /v1/statusline stores new plan
	// figures, so the plan-window stop checks them the moment they arrive.
	RateLimitsRecorded func(ctx context.Context)
	// Started is when this daemon came up. The burn tile needs it: in the
	// first minutes there is less history than the window it divides by.
	Started time.Time
	// LAN switches network access on and off while the daemon runs. Nil in
	// builds or tests that do not serve; then the switch reports itself as
	// unavailable rather than pretending.
	LAN interface {
		EnableLAN() (string, error)
		DisableLAN() error
		// LANKeepOn and SetLANKeepOn read and store *Keep on after Caprock
		// restarts* (ADR-060).
		LANKeepOn() bool
		SetLANKeepOn(on bool) error
	}
	// Remote is access from anywhere, through a relay (ADR-058): its state for
	// the pairing panel and the switch. Nil in builds or tests without it.
	Remote RemoteControl
	// Machines are the other computers this machine reaches (ADR-067,
	// machines.go); nil in a build or test without them.
	Machines Machines
	// TLDR is what AI;DR squeezes an answer with (ADR-072): the user's own
	// claude, through Second Brain's runner. Nil in builds or tests without
	// it, and POST /v1/events/{id}/tldr answers 503 for a long answer.
	TLDR brain.Runner
	// BrainAuto is Second Brain's automatic extraction (ADR-063). Nil in
	// builds or tests without it; the graph and manual drops work either way.
	BrainAuto BrainAuto
	// Obsidian imports local Markdown vaults; nil without the importer.
	Obsidian *obsidian.Service
	// BrainHandoffState says whether a new session in a repository would be
	// served a handoff at all — Memory between sessions on, a passage left
	// recently enough — for GET /v1/brain/handoff. Nil in tests; the
	// memories are listed either way.
	BrainHandoffState func(ctx context.Context, project string) BrainHandoffState
	// ActiveLoops reports whether a session currently has an unexpired loop alert.
	ActiveLoops func(sessionID string) *loop.Alert
	// LoopK and LoopWindow are the loop detector's settings, so the Week
	// card's longest loop is found by the same rule as the live alert. Zero
	// means the detector's defaults.
	LoopK      int
	LoopWindow time.Duration
	// IdleAfter is the silence threshold for the idle badge.
	IdleAfter time.Duration
	Now       func() time.Time
	// Token gates POST /v1/shutdown (same per-run token the shim uses).
	Token string
	// Shutdown is invoked by POST /v1/shutdown (caprock down).
	Shutdown func()
	// AskGemini answers one prompt on the user's own key and records what it
	// cost. nil ⇒ the endpoint returns 501. See ADR-023.
	AskGemini func(ctx context.Context, model, prompt string) (any, error)
	// Agents is the Phase 1 owned-session manager (nil ⇒ endpoints return 501).
	Agents AgentController
	// Queue holds what the chat field sends while a turn runs (ADR-053).
	// nil ⇒ /v1/agents/{id}/queue returns 501.
	Queue Queuer
	// Board assembles the Queue view (GET /v1/queue). nil ⇒ 501.
	Board QueueBoarder
	// Work assembles the Work board (GET /v1/work, ADR-064). nil ⇒ 501.
	Work WorkBoarder
	// Catalog answers the agent pickers and keeps the custom agents
	// (ADR-046). nil ⇒ /v1/agents/catalog and /v1/agents/custom return 501.
	Catalog AgentCatalog
	// MCP reads and changes whether `caprock mcp` is registered with Claude
	// Code and Codex (ADR-078). nil ⇒ /v1/mcp/agents returns 501.
	MCP MCPRegistrar
	// Subscriptions keeps the sign-ins of Settings → Subscriptions (ADR-048).
	// nil ⇒ /v1/subscriptions returns 501.
	Subscriptions SubscriptionManager
	// Tasks is the Phase 2 hive-backed task board (nil ⇒ endpoints return 501).
	Tasks TaskController
	// Settings reads and persists the user-editable settings (the subscription
	// plan and whether release checks are on). nil ⇒ 501.
	Settings SettingsController
	// Update reports whether a newer release exists. nil ⇒ 501. It is only
	// ever consulted when the user enabled checks.
	Update UpdateController
	// UpdateBusy counts the sessions an app restart would interrupt — an
	// agent mid-turn or waiting on a permission prompt — for GET
	// /v1/update/busy, which the desktop app reads before it installs an
	// update on its own (ADR-042 as amended). nil ⇒ 501.
	UpdateBusy func(ctx context.Context) (int, error)
	// Terminals opens a session in the user's own terminal application. nil ⇒
	// the open-terminal endpoints return 501 and no session offers it.
	Terminals TerminalController
	// Editors opens a folder or a file in the user's own editor (F18). nil ⇒
	// the editor endpoints return 501.
	Editors EditorController
	// Browsers lists the web browsers installed here and opens a link in
	// one (the terminal link chooser). nil ⇒ the browser endpoints return 501.
	Browsers BrowserController
	// Projects is the projects list, its git state and clones (nil ⇒ the
	// /v1/projects endpoints return 501).
	Projects *projects.Service
	// Templates makes projects from the person's templates (ADR-065; nil ⇒
	// /v1/templates and /v1/projects/from-template return 501).
	Templates *templates.Service
	// GitHub is the GitHub integration (nil ⇒ the /v1/github endpoints
	// return 501).
	GitHub *github.Service
	// Shells starts and lists shell tabs (nil ⇒ /v1/shells returns 501).
	Shells ShellController
	// Mail serves /v1/mail/* (Caprock Mail, internal/mail). nil ⇒ 501.
	Mail http.Handler
	// Admin keeps the admin key for private modules, which live under
	// DataDir (ADR-076). nil ⇒ GET /v1/admin answers {admin:false} and the
	// module routes answer 404.
	Admin AdminController
	// AdminVerify checks an admin key; nil ⇒ modules.ParseKey, the key
	// compiled into the build. Tests pass a key pair of their own.
	AdminVerify func(key string) (modules.Grant, error)
	// ModuleNotify shows a module's desktop notification (POST
	// /v1/x/{id}/notify). nil ⇒ the route answers 204 and shows nothing.
	ModuleNotify ModuleNotifier
	// DataDir is where Caprock keeps its own state. Needed so a file pasted
	// into the terminal can be written somewhere Claude Code can read it by
	// path. Empty ⇒ POST /v1/paste returns 501.
	DataDir string
}

Deps is everything the API needs from the daemon.

type ETA added in v0.110.0

type ETA struct {
	LoMs  int64 `json:"lo_ms"`
	MidMs int64 `json:"mid_ms"`
	HiMs  int64 `json:"hi_ms"`
}

ETA is an estimate in milliseconds from Now: the median and the 25th–75th percentile range.

type EditorController added in v0.78.0

type EditorController interface {
	// List is the installed editors and the id of the one used when none is
	// named.
	List() (editors []editor.Editor, preferred string)
	// Open opens path, at line when it is above zero, in the editor with this
	// id ("" for the preferred one).
	Open(ctx context.Context, id, path string, line int) (editor.Editor, error)
}

EditorController finds the user's editors and opens a folder or a file in one (internal/editor). nil ⇒ the endpoints answer 501.

type Estimate added in v0.110.0

type Estimate struct {
	Turns    int   `json:"turns"`
	P25Ms    int64 `json:"p25_ms"`
	MedianMs int64 `json:"median_ms"`
	P75Ms    int64 `json:"p75_ms"`
}

Estimate is what the estimates are made from: the project's newest finished Claude Code turns.

type FlowPoint added in v0.119.0

type FlowPoint struct {
	// Day is the local calendar day, "2006-01-02".
	Day string `json:"day"`
	// Value is the day's figure: a count, a median in ms, dollars. Absent on
	// a day with no sample for a median — a gap, never a zero.
	Value *float64 `json:"value,omitempty"`
	// N is how many samples the value rests on: the merges, runs, released
	// merges or open pull requests counted.
	N int `json:"n"`
	// ByNow is a running total's value up to the clock time it is now
	// (throughput, cost), so today so far can be set against earlier days
	// at the same hour rather than against whole days.
	ByNow *float64 `json:"by_now,omitempty"`
}

FlowPoint is one day of a figure's series.

type GlanceResponse added in v0.70.0

type GlanceResponse struct {
	Agents []store.WeekAgent `json:"agents"`
	// Bill prices each model's tokens by type at the table's current rates,
	// the way the context tax is priced. Absent without a pricing table.
	Bill *Bill `json:"bill,omitempty"`
	// Display maps the model ids in range to the pricing table's names, so a
	// chart can say "Opus 5.5" rather than an id.
	Display map[string]string `json:"display"`
	// Trend is the last seven days against the seven before them, for the
	// block's change-in-share markers. Only on the all-time answer.
	Trend *GlanceTrend `json:"trend,omitempty"`
}

GlanceResponse is GET /v1/glance: what the Now screen's At a glance block draws beyond /v1/history, over everything Caprock has seen — who did the work, and what kind of token the bill was made of. Contract: .ai/03-contracts.md § At a glance.

type GlanceTrend added in v0.132.0

type GlanceTrend struct {
	Days        int          `json:"days"`
	PriorFromMs int64        `json:"prior_from_ms"`
	CutMs       int64        `json:"cut_ms"`
	ToMs        int64        `json:"to_ms"`
	Prior       GlanceWindow `json:"prior"`
	Recent      GlanceWindow `json:"recent"`
}

GlanceTrend is two equal windows ending now: prior = [prior_from_ms, cut_ms), recent = [cut_ms, to_ms).

type GlanceWindow added in v0.132.0

type GlanceWindow struct {
	// Models is stored cost by model id, the money donut's figure.
	Models map[string]float64 `json:"models"`
	Bill   *Bill              `json:"bill,omitempty"`
	// Tools is tool calls by tool.
	Tools  map[string]int64  `json:"tools"`
	Agents []store.WeekAgent `json:"agents"`
}

GlanceWindow is one trend window: the same four splits the block draws.

type HistoryResponse

type HistoryResponse struct {
	Range   string              `json:"range"`
	Totals  store.HistoryTotals `json:"totals"`
	Tools   []store.ToolCount   `json:"tools"`
	Daily   []store.DailyStat   `json:"daily"`
	Savings cost.Savings        `json:"savings"`
	Summary store.Summary       `json:"summary"`
	// Tax is what this range paid to re-send its own context: every turn
	// re-reads the whole conversation before it does anything. Absent when
	// there is no pricing table to charge it at, rather than zero -- a zero
	// tax reads as "this workload had none", which no workload does.
	Tax *contexttax.Lifetime `json:"tax,omitempty"`
}

HistoryResponse is /v1/history.

type LimitsResponse added in v0.145.0

type LimitsResponse struct {
	RateLimits      *RateLimits `json:"rate_limits,omitempty"`
	CodexRateLimits *RateLimits `json:"codex_rate_limits,omitempty"`
}

LimitsResponse is GET /v1/stats/limits: the plan windows alone, as the summary carries them, for a reader that wants nothing else: the phone home's Limits line, which would otherwise pay for the whole summary (projects, sparks, models, the usual) to show two percentages.

type MCPRegistrar added in v0.148.0

type MCPRegistrar interface {
	Statuses() []mcpreg.Status
	Executable() (string, error)
	Connect(ctx context.Context, agent string) (mcpreg.Status, error)
	Disconnect(ctx context.Context, agent string) (mcpreg.Status, error)
}

MCPRegistrar reads and changes whether `caprock mcp` is registered with the user's coding agents (internal/mcpreg, ADR-078).

type MachineSocket added in v0.122.0

type MachineSocket interface {
	Read(ctx context.Context) (websocket.MessageType, []byte, error)
	Write(ctx context.Context, typ websocket.MessageType, msg []byte) error
	Close(code websocket.StatusCode, reason string) error
	Subprotocol() string
}

MachineSocket is a WebSocket on another computer's API (remote.WSConn).

type Machines added in v0.122.0

type Machines interface {
	List() []peers.Status
	Get(id string) (peers.Status, error)
	Check(ctx context.Context, id string) (peers.Status, error)
	Pair(ctx context.Context, link string) (peers.Status, error)
	Rename(id, name string) error
	// Leave asks computer id to drop this machine's token there (DELETE
	// /v1/pair/me), best effort.
	Leave(ctx context.Context, id string) error
	Forget(id string) error
	Do(id string, req *http.Request) (*http.Response, error)
	OpenWS(ctx context.Context, id, path string, protocols []string) (MachineSocket, error)
}

Machines is internal/peers' Manager, as the API uses it.

type ModeError added in v0.109.0

type ModeError struct {
	Status int
	// Code names the refusal for the client: "prompt", "busy", "restart",
	// "bypass_consent", "unreachable", "stuck", "not_owned".
	Code string
	Msg  string
	// Mode is the mode the session was left in, when one was read.
	Mode string
}

ModeError is a switch refused or failed, with the status to answer.

func (*ModeError) Error added in v0.109.0

func (e *ModeError) Error() string

type ModuleAttention added in v0.148.0

type ModuleAttention struct {
	Count     int                   `json:"count"`
	Items     []ModuleAttentionItem `json:"items"`
	UpdatedAt int64                 `json:"updated_at"`
}

ModuleAttention is what a module last said waits on the owner.

type ModuleAttentionItem added in v0.148.0

type ModuleAttentionItem struct {
	Label string `json:"label"`
	Href  string `json:"href"`
}

ModuleAttentionItem is one thing waiting in a module: a short line and the route inside the module's page that shows it ("#review/42").

type ModuleInfo added in v0.131.0

type ModuleInfo struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`
	URL     string `json:"url"`
	// Attention is what the module last said waits on the owner, while it
	// is under a day old and its count is above 0 (moduleattention.go).
	Attention *ModuleAttention `json:"attention,omitempty"`
}

ModuleInfo is one installed module the key names: what a sidebar row needs.

type ModuleNotifier added in v0.147.0

type ModuleNotifier interface {
	NotifyModule(id, name, title, body string) bool
}

ModuleNotifier shows a module's desktop notification: a notify frame the desktop app turns into an OS notification, when the owner's desktop notifications are on. It reports whether it published one.

type OfferAnswer added in v0.117.2

type OfferAnswer struct {
	Offer   string            `json:"offer"`
	Answers map[string]string `json:"answers"`
	Email   string            `json:"email,omitempty"`
}

OfferAnswer is the body of POST /v1/offer.

type OpenTerminalInfo added in v0.70.1

type OpenTerminalInfo struct {
	Modes  []string `json:"modes"`
	Reason string   `json:"reason,omitempty"`
}

OpenTerminalInfo says how a session can be opened in the user's own terminal: the modes allowed, the first being what the main button does, and the reason when there is none or a mode is missing.

type OrphanTarget added in v0.116.0

type OrphanTarget struct {
	PID       int32 `json:"pid"`
	StartedAt int64 `json:"started_at"`
}

OrphanTarget names one process from the footprint's orphan list: its pid and the start time the list gave, so a pid reused since is not touched.

type Overlap added in v0.116.0

type Overlap struct {
	WindowMinutes int                       `json:"window_minutes"`
	Sessions      map[string]SessionOverlap `json:"sessions"`
}

Overlap answers GET /v1/overlap.

type OverlapPeer added in v0.116.0

type OverlapPeer struct {
	SessionID  string   `json:"session_id"`
	Name       string   `json:"name"`
	NameSource string   `json:"name_source,omitempty"`
	StartedAt  int64    `json:"started_at"`
	Files      []string `json:"files"`
}

OverlapPeer is another live session working in the same checkout, named the way its card names it, with the files both edited in the window.

type PRBoard added in v0.116.0

type PRBoard struct {
	Cards    []BoardCard    `json:"cards"`
	Releases []BoardRelease `json:"releases"`
	Flow     BoardFlow      `json:"flow"`
	// DefaultBranch is the branch a merge must land on to ship in a release.
	DefaultBranch string `json:"default_branch,omitempty"`
	// ShipsBy is how merged work ships here: ShipsByRelease when a published
	// release or a version tag is dated within shipsRecentDays, ShipsByMerge
	// when the release list and the local tags were both read and neither
	// is; absent when that cannot be said.
	ShipsBy string `json:"ships_by,omitempty"`
}

PRBoard is the Board view's answer.

type PermissionModeView added in v0.109.0

type PermissionModeView struct {
	SessionID string `json:"session_id"`
	// Mode is Claude Code's word for it ("default", "acceptEdits", "plan",
	// "bypassPermissions", "auto", "dontAsk"); "" when nothing says.
	Mode string `json:"mode"`
	// Source is where Mode was learned: "screen" (the footer, now), "hook"
	// (the session's own hook payload), "switch" (a switch Caprock made and
	// saw take), "launch" (its command line).
	Source string `json:"source,omitempty"`
	// Switchable is a Claude Code session Caprock started and holds the
	// terminal of: Mode can be changed from here. Any other session's mode
	// changes only in its own terminal (rule 7).
	Switchable bool `json:"switchable"`
	// InSession are the modes Shift+Tab reaches in this process; "auto" is
	// in it only when the account has auto mode, which a switch finds out.
	InSession []string `json:"in_session,omitempty"`
	// Restart are the modes only a new process has: the conversation is
	// resumed under its own id with the new flag.
	Restart []string `json:"restart,omitempty"`
	// Waiting says what keeps a switch from happening now: "permission" or
	// "question" (a prompt on the screen) refuse both kinds, "turn" (the
	// agent is working) refuses a restart. "" at the prompt.
	Waiting string `json:"waiting,omitempty"`
}

PermissionModeView is GET /v1/sessions/{id}/permission-mode.

type PhoneLinkSender added in v0.119.0

type PhoneLinkSender interface {
	// PhoneLinkReady reports whether a bot and a chat are set up.
	PhoneLinkReady() bool
	SendPhoneLink(ctx context.Context, app string) error
}

PhoneLinkSender sends the address of the phone's page — no code, no key — to the Telegram chat the owner set up (ADR-047), so a phone that is already paired finds its way back.

type QueueBoard added in v0.110.0

type QueueBoard struct {
	// Now is the daemon's clock (unix ms) when the board was read; every
	// estimate counts from it.
	Now      int64          `json:"now"`
	Sessions []BoardSession `json:"sessions"`
	// Done is the turns of sessions Caprock started that ended at or after
	// DoneSince, newest first.
	Done      []BoardDone `json:"done"`
	DoneSince int64       `json:"done_since"`
}

QueueBoard is GET /v1/queue.

type QueueBoarder added in v0.110.0

type QueueBoarder interface {
	Board(ctx context.Context) (QueueBoard, error)
}

QueueBoarder assembles the board. Optional on Deps: nil answers 501.

type QueueView added in v0.104.0

type QueueView struct {
	SessionID string                `json:"session_id"`
	Messages  []store.QueuedMessage `json:"messages"`
	Waiting   string                `json:"waiting"`
}

QueueView is a session's queue and why it waits.

type Queuer added in v0.104.0

type Queuer interface {
	View(ctx context.Context, sessionID string) (QueueView, error)
	Send(ctx context.Context, sessionID, text string) (SendResult, error)
	Edit(ctx context.Context, sessionID string, id int64, text string) (QueueView, error)
	Cancel(ctx context.Context, sessionID string, id int64) (QueueView, error)
	SendNow(ctx context.Context, sessionID string, id int64) (QueueView, error)
}

Queuer is the daemon's message queue. Optional on Deps so a test server without one answers 501.

type RateLimits added in v0.4.0

type RateLimits struct {
	FiveHour *RateWindow `json:"five_hour,omitempty"`
	SevenDay *RateWindow `json:"seven_day,omitempty"`
}

RateLimits is the current plan-limit window state (from the statusline feed).

type RateWindow added in v0.4.0

type RateWindow struct {
	UsedPercentage float64 `json:"used_percentage"` // 0..100, measured
	ResetsAt       int64   `json:"resets_at"`       // unix seconds, from Claude Code
	// Forecast is a conditional "~Nh to limit at current pace" — present only when
	// the measured slope is rising and exhaustion is projected before the reset.
	// nil ⇒ show only the measured fact (no guess).
	Forecast string `json:"forecast,omitempty"`
	// LimitAt is when the same pace reaches 100% (unix ms), set exactly when
	// Forecast is, so the dashboard can say "around 19:10" without parsing
	// the sentence.
	LimitAt int64 `json:"limit_at,omitempty"`
	// ObservedAt is when the agent wrote this figure (unix ms). Set for
	// Codex, whose windows are read out of a transcript that may be hours or
	// days old; Claude Code's arrive live and leave it unset.
	ObservedAt int64 `json:"observed_at,omitempty"`
}

RateWindow is one window's measured state plus an optional honest forecast.

type RemoteControl added in v0.116.0

type RemoteControl interface {
	// RemoteState is what the pairing panel shows. code is the outstanding
	// pairing code, "" for none; when there is one the state's link carries
	// it, so the QR pairs in one scan.
	RemoteState(code string) RemoteState
	// SetRemote turns it on or off, and on, optionally changes the relay and
	// the phone's page. Remembered across restarts.
	SetRemote(on bool, relay, app string) error
}

RemoteControl is the daemon's side of access from anywhere (ADR-058).

type RemoteState added in v0.116.0

type RemoteState struct {
	Enabled bool   `json:"enabled"`
	Status  string `json:"status"` // off, connecting, online, offline
	Error   string `json:"error,omitempty"`
	Phones  int    `json:"phones"`
	Relay   string `json:"relay"`
	App     string `json:"app"`
	HostID  string `json:"host_id,omitempty"`
	// Link is the pairing link the QR draws: the phone's page with the relay,
	// this machine's id and key, and the code when one is live.
	Link string `json:"link,omitempty"`
}

RemoteState is GET /v1/pair's "remote".

type RemoveRequest added in v0.73.0

type RemoveRequest struct {
	IDs       []string `json:"ids"`
	CwdPrefix string   `json:"cwd_prefix"`
	DryRun    bool     `json:"dry_run"`
}

RemoveRequest is the body of POST /v1/sessions/remove: the sessions to remove, named by id or by the folder they ran in. DryRun lists them and changes nothing.

type RemoveResult added in v0.73.0

type RemoveResult struct {
	DryRun   bool                     `json:"dry_run"`
	Sessions []store.RemovalCandidate `json:"sessions"`
	Skipped  []RemoveSkipped          `json:"skipped"`
	CostUSD  float64                  `json:"cost_usd"`
	// UnmatchedUSD is cost that could not be found in any day's totals to
	// take out (store.RemoveSession); zero in every case seen so far.
	UnmatchedUSD float64 `json:"unmatched_usd"`
}

RemoveResult is what POST /v1/sessions/remove did, or would do.

type RemoveSkipped added in v0.73.0

type RemoveSkipped struct {
	store.RemovalCandidate
	Reason string `json:"reason"`
}

RemoveSkipped is a matched session that was left alone, and why.

type RepoActivityRow added in v0.115.0

type RepoActivityRow struct {
	projects.RepoActivity
	ProjectID int64 `json:"project_id"`
	Sessions  int   `json:"sessions"`
	// GitHub is set only while GitHub is connected and the repository's
	// remote is on GitHub; its fields only from what Caprock already keeps.
	GitHub *RepoGitHub `json:"github,omitempty"`
}

RepoActivityRow is one repository: its local git figures, how many sessions run in it, and the GitHub figures already kept for it.

type RepoCIAuthor added in v0.116.0

type RepoCIAuthor struct {
	Login   string  `json:"login"`
	Avatar  string  `json:"avatar,omitempty"`
	PRs     int     `json:"prs"`
	Merged  int     `json:"merged"`
	CostUSD float64 `json:"cost_usd"`
}

RepoCIAuthor is one person who opened pull requests in the window.

type RepoCIPR added in v0.116.0

type RepoCIPR struct {
	Number       int     `json:"number"`
	Title        string  `json:"title,omitempty"`
	URL          string  `json:"url"`
	State        string  `json:"state"`
	Draft        bool    `json:"draft,omitempty"`
	Author       string  `json:"author,omitempty"`
	AuthorAvatar string  `json:"author_avatar,omitempty"`
	CostUSD      float64 `json:"cost_usd"`
	Sessions     int     `json:"sessions"`
	Live         int     `json:"live"`
	// Shared counts its sessions charged only in part (store.PRSpend).
	Shared int `json:"shared,omitempty"`
	// The tokens of the same work.
	TokensIn   int64 `json:"tokens_in"`
	TokensOut  int64 `json:"tokens_out"`
	CacheRead  int64 `json:"cache_read"`
	CacheWrite int64 `json:"cache_write"`
}

RepoCIPR is one pull request with its agent cost.

type RepoCIQuiet added in v0.117.1

type RepoCIQuiet struct {
	ProjectID  int64  `json:"project_id"`
	Name       string `json:"name"`
	Repo       string `json:"repo"`
	LastActive int64  `json:"last_active,omitempty"`
	// Why: "older" (no activity in RecentDays), "hidden" (this viewer hid
	// it), "more" (past the bound on rows read).
	Why string `json:"why"`
}

RepoCIQuiet is a listed GitHub repository the section does not read.

type RepoCIRow added in v0.116.0

type RepoCIRow struct {
	ProjectID int64  `json:"project_id"`
	Name      string `json:"name"`
	// Repo is owner/name on GitHub.
	Repo string `json:"repo"`
	// Live counts the sessions running in it.
	Live int `json:"live"`
	// LastActive is its newest session's last event, or when it was added
	// to the list if later (Unix ms; 0 when neither is known).
	LastActive int64 `json:"last_active,omitempty"`
	// Older says it is listed only because older repositories were asked.
	Older bool `json:"older,omitempty"`
	// Pending says GitHub's figures are being read: the quick answer, while
	// the first composition waits on GitHub.
	Pending bool `json:"pending,omitempty"`
	// Slow says GitHub did not answer within reposCIRepoTimeout; Error has
	// its words, and the next composition asks again.
	Slow bool `json:"slow,omitempty"`
	// CI is github.RunStats over its newest runs, 14 days.
	CI *github.CIStats `json:"ci,omitempty"`
	// Days are the local calendar days CI's series cover, oldest first.
	Days []string `json:"days,omitempty"`
	// Stuck are its runs going on far past their median, or queued long.
	Stuck []github.StuckRun `json:"stuck"`
	// Open counts its open pull requests, Merged7 those merged in 7 days.
	Open    int `json:"open"`
	Merged7 int `json:"merged_7d"`
	// TopPRs are the most expensive by agent cost (open, or merged in the
	// last 7 days), at most 5; Authors who opened those, by agent cost.
	TopPRs  []RepoCIPR     `json:"top_prs"`
	Authors []RepoCIAuthor `json:"authors"`
	// Release is its newest published release.
	Release *github.RepoRelease `json:"release,omitempty"`
	Error   *github.Error       `json:"error,omitempty"`
	// ReadAt is when GitHub last answered its pull request list (unix ms):
	// with Error, the row draws on that older read, not refreshed.
	ReadAt int64 `json:"read_at,omitempty"`
}

RepoCIRow is one repository's CI, pull requests and agent spend.

type RepoGitHub added in v0.115.0

type RepoGitHub struct {
	Repo string `json:"repo"`
	// Pulls is from the last list of the repository's pull requests (the
	// Branches view, the PRs & CI tab).
	Pulls *RepoGitHubPulls `json:"pulls,omitempty"`
	// CI is from the last list of its newest runs (the PRs & CI tab).
	CI *RepoGitHubCI `json:"ci,omitempty"`
	// Release is from the last answer of the deck's Release view.
	Release *RepoGitHubRelease `json:"release,omitempty"`
}

RepoGitHub is what the deck and the PRs & CI tab already read for a repository, however old — read from their caches, so this route sends nothing to GitHub. A part nobody read yet is absent.

type RepoGitHubCI added in v0.115.0

type RepoGitHubCI struct {
	Runs int `json:"runs"`
	Red  int `json:"red"`
	// Workflow and MedianMS are the workflow taking the most time and its
	// median successful run (absent with fewer than two).
	Workflow string `json:"workflow,omitempty"`
	MedianMS int64  `json:"median_ms,omitempty"`
	// Last is the newest run of the kept list, whatever its age.
	Last *RepoGitHubRun `json:"last,omitempty"`
}

RepoGitHubCI is github.RunStats over the kept runs, 14 days.

type RepoGitHubPulls added in v0.115.0

type RepoGitHubPulls struct {
	Open int `json:"open"`
	// Merged7 counts those merged in the last 7 local days.
	Merged7     int   `json:"merged_7d"`
	TTMMedianMS int64 `json:"ttm_median_ms,omitempty"`
	Listed      int   `json:"listed"`
}

RepoGitHubPulls counts the kept list.

type RepoGitHubRelease added in v0.115.0

type RepoGitHubRelease struct {
	Tag   string `json:"tag,omitempty"`
	State string `json:"state"`
	At    int64  `json:"at,omitempty"`
}

RepoGitHubRelease is the newest release run the deck read.

type RepoGitHubRun added in v0.129.0

type RepoGitHubRun struct {
	Name   string `json:"name"`
	Branch string `json:"branch,omitempty"`
	// Status is GitHub's (queued, in_progress, completed…); Conclusion is
	// set once it completed (success, failure, cancelled…).
	Status     string `json:"status"`
	Conclusion string `json:"conclusion,omitempty"`
	At         int64  `json:"at,omitempty"`
	URL        string `json:"url,omitempty"`
}

RepoGitHubRun is one run, as a row's expanded line says it.

type RepoRemote added in v0.120.0

type RepoRemote struct {
	Dir string `json:"dir"`
	// Root is the repository's top level; absent when the folder is not in a
	// git repository.
	Root string `json:"root,omitempty"`
	// Repo is owner/name on GitHub; absent without a GitHub remote.
	Repo string `json:"repo,omitempty"`
	// Guarded is a folder macOS guards (Documents, Downloads…): this route
	// never runs git there, so it is not known either way.
	Guarded bool `json:"guarded,omitempty"`
}

RepoRemote is one asked folder.

type ReportSender added in v0.46.0

type ReportSender interface {
	SendReportNow(ctx context.Context) error
}

ReportSender sends one weekly report immediately.

An interface rather than the daemon itself, for the same reason as every other seam here: the API package must stay testable without building a daemon, and a handler that can only be exercised with a live Telegram token is a handler nobody tests.

type ReposActivity added in v0.115.0

type ReposActivity struct {
	Repos []RepoActivityRow `json:"repos"`
	// GitHubConnected says whether the rows' github figures could exist.
	GitHubConnected bool `json:"github_connected"`
}

ReposActivity is GET /v1/repos/activity: the Now screen's Repos section (.ai/04-ui.md § Repos on Now). One row per listed repository with a session that has not ended.

type ReposCI added in v0.116.0

type ReposCI struct {
	GitHubConnected bool `json:"github_connected"`
	// Status is GitHub's own status page (githubstatus.com), only while
	// GitHub is connected.
	Status *github.GitHubStatus `json:"status,omitempty"`
	Repos  []RepoCIRow          `json:"repos"`
	// Quiet are the listed GitHub repositories not read: no session in them
	// for RecentDays (unless `older` was asked), hidden by this viewer
	// (`hide`), or past the rows' bound. Nothing is sent to GitHub for them.
	Quiet []RepoCIQuiet `json:"quiet"`
	// RecentDays is the window of activity that lists a repository.
	RecentDays int `json:"recent_days"`
	// contains filtered or unexported fields
}

ReposCI is GET /v1/repos/ci: the Now screen's CI/CD section (.ai/04-ui.md § CI/CD on Now). Owner, 2026-10-14, translated: "find a place on the dashboard for CI/CD indicators — costs, time, possible GitHub outages, or something stuck … but the core is the release: a team lead wants to understand where the money for tokens goes, how much each PR costs, who pushes there — literally face and name."

type ReposRemotes added in v0.120.0

type ReposRemotes struct {
	Repos []RepoRemote `json:"repos"`
}

ReposRemotes is GET /v1/repos/remotes?dir=…&dir=…: which of the given folders are git repositories with a GitHub remote, and which repository that is. The Pipeline's repository picker lists only those (.ai/04-ui.md § Pipeline): a folder that is not a repository, or whose remote is not on GitHub, has no pull requests to show (owner, 2026-10-15, translated: two "caprock" entries, the second one "This folder is not a git repository with a remote").

type ResumeInfo added in v0.59.0

type ResumeInfo struct {
	OK bool `json:"ok"`
	// Reason is shown in place of the button when OK is false.
	Reason string `json:"reason,omitempty"`
	// Command resumes the session from the user's own terminal, when the
	// agent has such a command. Offered even when Caprock cannot run it.
	Command string `json:"command,omitempty"`
	// PermissionMode is the mode continuing it here starts in, when the
	// request names none (continueMode): the one the session was last running
	// in, else the spawn preference. Absent when neither says one, and when it
	// cannot be continued here. Shown beside the button, so a session that
	// never asks is never continued by surprise — and one that always asked
	// does not come back asking for nothing.
	PermissionMode string `json:"permission_mode,omitempty"`
}

ResumeInfo says whether a session can be carried on from here, and if not, why (FB-036).

The button used to be gated on who started the session and which agent it was, and on nothing that decides whether a resume works. On the owner's machine it told the truth for 39 of 116 ended Claude Code sessions: 65 offered a resume that failed — 44 transcripts Claude Code had already deleted, 21 folders gone, each a terminal that opened and died — and 12 that could be resumed offered nothing, because Caprock had started them.

type SecretWhere added in v0.116.0

type SecretWhere = secret.Where

SecretWhere is where a credential is kept: kind "keychain" (the macOS login keychain), "file" (a 0600 file, with its path) or "config" (still in config.json, when moving it out failed).

type SendResult added in v0.104.0

type SendResult struct {
	Sent   bool                 `json:"sent"`
	Queued *store.QueuedMessage `json:"queued,omitempty"`
	Queue  QueueView            `json:"queue"`
}

SendResult is POST /v1/agents/{id}/queue's answer: typed in, or queued.

type Server

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

Server is the http.Handler.

func New

func New(d Deps) *Server

New builds the router.

func (*Server) Close

func (s *Server) Close()

Close shuts down live connections.

func (*Server) LiveClients added in v0.101.0

func (s *Server) LiveClients() int

LiveClients is how many /v1/live sockets are open: whether anyone is looking, for work that is only worth doing while someone is.

func (*Server) PublishShells added in v0.138.0

func (s *Server) PublishShells() bool

PublishShells sends a "shells" frame on /v1/live — every running shell, as GET /v1/shells answers it — when the list differs from the last one sent, so the app's tabs follow it instead of polling. The daemon calls it every 10 s while a live client is connected; a start calls it at once. True when a frame went out.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP applies loopback-only + security headers, then routes.

func (*Server) SetLAN added in v0.50.0

func (s *Server) SetLAN(p *pairing.Store, url string)

SetLAN switches network access on or off while the daemon is running. A nil store means off: from then on nothing off-loopback is served, and the other addresses (SetLANAlternates) are forgotten too.

func (*Server) SetLANAlternates added in v0.77.0

func (s *Server) SetLANAlternates(urls []string)

SetLANAlternates names the addresses network access answers on besides the one SetLAN gave: the second listener's, and the MagicDNS name of the Tailscale one. Ignored while network access is off.

func (*Server) StartSession added in v0.101.0

func (s *Server) StartSession(ctx context.Context, req map[string]any) (string, error)

StartSession starts a session the way POST /v1/agents does — the stated mode filled in, the Bypass consent checked — for a caller inside the daemon: a /new from the paired Telegram chat (ADR-047).

func (*Server) Warm added in v0.70.0

func (s *Server) Warm(ctx context.Context)

Warm computes the whole-history answers the dashboard asks for first — the lifetime strip's /v1/history?range=all and the 7d, 30d and all-time summaries the Cost screen and the share dialog open with — so the first screen after a start finds them cached instead of paying for the scans.

It does not warm the share dialog's 30-day and all-time Weeks any more. Those read the payload of every Bash, Edit and Write result in the window — on the owner's 2.2 GB database the slow-query log named them as the startup's biggest reads, seconds of a gigabyte-scale scan (2026-10-13) — on every start, for a dialog most starts never open. The dialog pays for it once, when it is opened. Run in the background; it returns when they are done or ctx ends. Errors are dropped: a key that failed to warm is simply computed on first request, as it would have been without this.

type SessionBranch added in v0.111.0

type SessionBranch struct {
	branches.Branch
	// PR is the branch's pull request (the open one, else the newest) from
	// one list of the repository's pull requests; absent while GitHub is not
	// connected.
	PR *github.BranchPR `json:"pr,omitempty"`
	// Live is an open PR as the PRs view reads it, with its checks.
	Live *github.PR `json:"live,omitempty"`
	// CostUSD, Sessions and Agents sum the sessions recorded on this branch
	// of this repository (store.SpendByBranch).
	CostUSD  float64  `json:"cost_usd"`
	Sessions int      `json:"sessions"`
	Agents   []string `json:"agents"`
	// SessionAt is the newest event of those sessions; ActivityAt the later
	// of it and the last commit, what the rows are ordered by.
	SessionAt  int64 `json:"session_at,omitempty"`
	ActivityAt int64 `json:"activity_at"`
	// Stale: no commit in 30 days and no open pull request.
	Stale bool `json:"stale,omitempty"`
	// Landed: its changes are already on the default branch by content (a
	// squash merge, or inside another branch's batch); checked only for a
	// branch ahead of it, committed in the last 14 days, with no open pull
	// request. Absent: not landed, or not checked.
	Landed bool `json:"landed,omitempty"`
	// InPR is the open pull request whose branch already carries this
	// branch's last commit (a batch PR): it has a PR, though not its own.
	// Checked for the same branches as Landed, against the newest eight
	// open PRs.
	InPR int `json:"in_pr,omitempty"`
}

SessionBranch is one row of the deck's Branches view: what git knows of the branch, its pull request, what Caprock's sessions on it cost.

type SessionBranches added in v0.111.0

type SessionBranches struct {
	Connected bool `json:"connected"`
	// Repo is "owner/name" when the remote is on GitHub.
	Repo string `json:"repo,omitempty"`
	// Reason says why there are no branches: no_repo (not a git repository).
	Reason   string          `json:"reason,omitempty"`
	Default  string          `json:"default,omitempty"`
	Base     string          `json:"base,omitempty"`
	Current  string          `json:"current,omitempty"`
	Branches []SessionBranch `json:"branches"`
	Error    *github.Error   `json:"error,omitempty"`
	// contains filtered or unexported fields
}

SessionBranches is GET /v1/sessions/{id}/branches.

type SessionCI added in v0.108.0

type SessionCI struct {
	Connected bool          `json:"connected"`
	PR        *SessionCIPR  `json:"pr,omitempty"`
	CI        *github.CI    `json:"ci,omitempty"`
	Error     *github.Error `json:"error,omitempty"`
	// contains filtered or unexported fields
}

SessionCI is GET /v1/sessions/{id}/ci.

type SessionCIPR added in v0.108.0

type SessionCIPR struct {
	Number  int    `json:"number"`
	URL     string `json:"url"`
	Title   string `json:"title,omitempty"`
	State   string `json:"state,omitempty"` // open | merged | closed; "" when GitHub was not read
	Repo    string `json:"repo"`
	HeadSHA string `json:"head_sha,omitempty"`
	// Live is the pull request as GitHub returned it: its review, merge
	// state and diff size, for the PRs & CI tab's detail.
	Live *github.PR `json:"live,omitempty"`
}

SessionCIPR is the pull request whose CI the deck shows.

type SessionCIStats added in v0.114.0

type SessionCIStats struct {
	Connected bool `json:"connected"`
	// Repo and Reason: as SessionRepoCI says them.
	Repo   string `json:"repo,omitempty"`
	Reason string `json:"reason,omitempty"`
	// PRs is the repository's own pull requests, most recently updated
	// first, from the list the Branches view reads (its newest 50).
	PRs   []github.BranchPR `json:"prs"`
	Stats *github.RepoStats `json:"stats,omitempty"`
	// Board is the Board view: the pull requests by stage, the releases and
	// the flow strip (prboard.go).
	Board *PRBoard `json:"board,omitempty"`
	// Error is GitHub's refusal of the newest read: with PRs present, those
	// are the ones read at ReadAt, not refreshed.
	Error *github.Error `json:"error,omitempty"`
	// ReadAt is when GitHub last answered what the board draws on — the
	// older of the pull request list's and the releases' reads (unix ms; 0
	// when not read). FetchedAt says when the answer was put together,
	// which can be later: a composition that could not reach GitHub draws on
	// what it last read.
	ReadAt int64 `json:"read_at,omitempty"`
	// contains filtered or unexported fields
}

SessionCIStats is GET /v1/sessions/{id}/ci/stats: the figures and the pull request list of the PRs & CI tab (.ai/21-app.md § PRs & CI tab), for the repository of the session's working directory.

type SessionCall added in v0.95.0

type SessionCall struct {
	ID           int64             `json:"id"`
	Ts           int64             `json:"ts"`
	Model        string            `json:"model,omitempty"`
	ModelDisplay string            `json:"model_display,omitempty"`
	CostUSD      float64           `json:"cost_usd"`
	Tokens       *event.TokenDelta `json:"tokens,omitempty"`
	Tools        []CallTool        `json:"tools,omitempty"`
	ToolCount    int               `json:"tool_count,omitempty"`
}

SessionCall is one entry of GET /v1/sessions/{id}/calls: a priced model call of the main thread, as the cockpit's spend scrubber reads it.

type SessionDetail

type SessionDetail struct {
	SessionSummary
	Files  []string      `json:"files"`
	Events []event.Event `json:"events"`
	// Repo is where the session's directory lives on the web, from its git
	// remote; absent when the directory is not in a repository.
	Repo *gitremote.Repo `json:"repo,omitempty"`
	// PRs are the pull requests this session opened or merged, latest first.
	PRs []store.SessionPR `json:"prs"`
	// RelayedFrom is the session this one was started to carry on; RelayedTo
	// the sessions started to carry this one on (ADR-032).
	RelayedFrom *store.RelayLink  `json:"relayed_from,omitempty"`
	RelayedTo   []store.RelayLink `json:"relayed_to"`
}

SessionDetail is /v1/sessions/{id}.

type SessionOverlap added in v0.116.0

type SessionOverlap struct {
	Checkout string        `json:"checkout"`
	With     []OverlapPeer `json:"with"`
}

SessionOverlap is one session's neighbours in its checkout.

type SessionPRLive added in v0.107.0

type SessionPRLive struct {
	store.SessionPR
	Live  *github.PR    `json:"live,omitempty"`
	Error *github.Error `json:"error,omitempty"`
}

SessionPRLive is one of a session's pull requests with what GitHub says of it now: state, checks and review. Live is absent while GitHub is not connected or could not be read; Error then says why, when it was asked.

type SessionPRs added in v0.113.0

type SessionPRs struct {
	Connected bool            `json:"connected"`
	PRs       []SessionPRLive `json:"prs"`
	// contains filtered or unexported fields
}

SessionPRs is GET /v1/sessions/{id}/prs.

type SessionRepoCI added in v0.110.0

type SessionRepoCI struct {
	Connected bool `json:"connected"`
	// Repo is "owner/name", read from the session's working directory's remote.
	Repo string `json:"repo,omitempty"`
	// Reason says why there is no repository: no_repo (not a git repository,
	// or no remote) or not_github (a remote elsewhere than github.com).
	Reason  string            `json:"reason,omitempty"`
	Branch  string            `json:"branch,omitempty"`
	Release *github.ReleaseCI `json:"release,omitempty"`
	CI      *github.CI        `json:"ci,omitempty"`
	Error   *github.Error     `json:"error,omitempty"`
	// contains filtered or unexported fields
}

SessionRepoCI is GET /v1/sessions/{id}/ci/release and …/ci/main: the release build and the default branch's CI of the session's repository.

type SessionSummary

type SessionSummary struct {
	store.Session
	Stats    store.Stats      `json:"stats"`
	Activity narrate.Activity `json:"activity"`
	Savings  cost.Savings     `json:"savings"`
	Loop     *loop.Alert      `json:"loop,omitempty"`
	Context  *ContextFill     `json:"context,omitempty"`
	// ContextNote says why Context is absent, which the client cannot work out
	// on its own: a model missing from the pricing table and a session that has
	// not answered yet both arrive as "no context", and they call for opposite
	// reactions. Empty whenever Context is present.
	ContextNote string `json:"context_note,omitempty"`
	// Description tells this session from the others on the screen: the
	// agent's own title, else the first prompt that says something. Source is
	// "title" or "prompt", so the card can style a guess differently from a
	// name.
	Description       string `json:"description,omitempty"`
	DescriptionSource string `json:"description_source,omitempty"`
	// Resume is whether this session can be carried on from here. On the list
	// it is filled for ended sessions only, so a card can offer continue
	// without a trip to the detail screen; the detail fills it for any session
	// that is not Caprock's own live one.
	Resume *ResumeInfo `json:"resume,omitempty"`
	// Detached marks a session Caprock started, not ended, whose terminal this
	// daemon does not hold — it was started before a restart. The terminal tab
	// opened an empty screen for it (FB-040); what it can do is continue.
	Detached bool `json:"detached,omitempty"`
	// ModelDisplay is the pricing table's name for the session's model (its
	// main thread's latest), "Opus 5.5" rather than the id. Empty when the
	// table does not know the model.
	ModelDisplay string `json:"model_display,omitempty"`
	// LiveSubagents is how many subagents are working in the session now:
	// heard from within the last 30 minutes and not yet stopped. Zero for an
	// ended session. The main thread is not counted.
	LiveSubagents int `json:"live_subagents,omitempty"`
	// SurvivesRestart marks a live session Caprock started whose terminal is
	// held by a pty-host (ADR-033), so restarting or upgrading Caprock leaves
	// it running. A live owned session without it is in the daemon's own PTY
	// (the fallback) and ends with the daemon; the upgrade notice counts those.
	SurvivesRestart bool `json:"survives_restart,omitempty"`
	// OpenTerminal is how this session can be opened in the user's own
	// terminal application, filled wherever Resume is. Absent for an agent
	// that cannot reopen a session by id, and when the daemon cannot open
	// terminals at all.
	OpenTerminal *OpenTerminalInfo `json:"open_terminal,omitempty"`
}

SessionSummary is one Now-screen card.

type Settings added in v0.8.0

type Settings struct {
	// UpdateChecks enables the release check — one of three calls that can
	// leave the machine, all off unless the user turns them on.
	UpdateChecks bool `json:"update_checks"`
	// Memory decides whether a session opening a folder is told what the last
	// one left there. On unless someone turns it off; see ADR-030.
	Memory bool `json:"memory"`
	// MemoryHoldoutPct holds the handoff back from this share of new sessions
	// (0–50), to measure what it is worth. 0 holds nothing back.
	MemoryHoldoutPct int `json:"memory_holdout_pct"`
	// PlanKind: "" (not stated), "flat" (Pro/Max/Team seat), or "metered"
	// (API key, Bedrock, Vertex, Enterprise usage at API rates).
	PlanKind        string  `json:"plan_kind"`
	PlanLabel       string  `json:"plan_label"`
	PlanUSDPerMonth float64 `json:"plan_usd_per_month"`
	// LicenseKey unlocks the paid features, checked locally against the expiry
	// it carries (ADR-022). Empty is the ordinary state.
	LicenseKey string `json:"license_key,omitempty"`
	// CapUSDPerDay is the daily spend ceiling; 0 is off. Reaching it pauses the
	// sessions Caprock started and nothing else (rule 7).
	//
	// No omitempty: zero means "the cap is off", which is a state the UI has to
	// be able to read. Omitted, an off cap is indistinguishable from a daemon
	// too old to have the field, and the panel cannot tell "you turned this
	// off" from "this build cannot do it".
	CapUSDPerDay float64 `json:"cap_usd_per_day"`
	// WindowStopPct is the share of a Claude plan window at which Premium
	// pauses the Claude Code sessions Caprock started until the window resets;
	// 0 is off. Like the cap it has no omitempty: 0 is a state the control
	// must read. Without a licence it is stored and shown but pauses nothing.
	WindowStopPct int `json:"window_stop_pct"`
	// ReportChatID is where the weekly report goes. Not a credential — a chat
	// id identifies a conversation and grants nothing — so it round-trips like
	// any other setting.
	ReportChatID string `json:"report_chat_id"`
	// ReportBotSet reports whether a bot token is stored, WITHOUT the token.
	//
	// The token is the first write-only field in this API: accepted by PUT,
	// never returned by GET. Every other setting round-trips, and the licence
	// key is echoed back plainly — but that key unlocks features on this
	// machine, while a bot token can send messages as somebody's bot. This
	// response is read on every settings render and by `caprock report`, and a
	// credential should not ride along on either. What a screen needs is
	// whether one is set, which is this.
	ReportBotSet bool `json:"report_bot_set"`
	// ReportBotToken is never serialised — the `-` tag is the mechanism that
	// makes "write-only" true rather than merely intended. It is set by the PUT
	// handler and read by the daemon; GET renders ReportBotSet instead.
	ReportBotToken string `json:"-"`
	// ReportBotWhere and DeepSeekKeyWhere say where each credential is kept —
	// the macOS login keychain, or a 0600 file with its path — so Settings can
	// say so. Absent when none is set.
	ReportBotWhere   *SecretWhere `json:"report_bot_where,omitempty"`
	DeepSeekKeyWhere *SecretWhere `json:"deepseek_key_where,omitempty"`
	// GeminiKeySet reports whether a Gemini key is available — from the
	// environment or entered here — without revealing it. Same write-only rule
	// as the bot token (ADR-025).
	GeminiKeySet bool `json:"gemini_key_set"`
	// GeminiKeyFromEnv says the key comes from GEMINI_API_KEY rather than from
	// the field, so the panel can say why editing it changes nothing.
	GeminiKeyFromEnv bool `json:"gemini_key_from_env"`
	// GeminiAPIKey is never serialised, for the same reason as the bot token.
	GeminiAPIKey string `json:"-"`
	// DeepSeekKeySet reports whether a DeepSeek key is stored, and
	// DeepSeekKeyHint shows its first and last few characters (MaskKey) so the
	// user can tell which key it is; the key itself is write-only, like the
	// two above.
	DeepSeekKeySet  bool   `json:"deepseek_key_set"`
	DeepSeekKeyHint string `json:"deepseek_key_hint,omitempty"`
	DeepSeekAPIKey  string `json:"-"`
	// ReportLastError is why the last send failed, empty when it did not.
	//
	// A weekly message that silently stops arriving is the failure mode this
	// feature has: nobody notices an absence. Telegram's own words are kept
	// ("chat not found", "bot was blocked by the user") because both are things
	// only the user can fix.
	ReportLastError string `json:"report_last_error,omitempty"`
	// ReportLastSentMs is when a report last went out, 0 for never.
	ReportLastSentMs int64 `json:"report_last_sent_ms,omitempty"`
	// AlertApproval and AlertFinished are the phone alerts' two switches, off
	// unless turned on; they send nothing until a bot is configured
	// (ADR-036). Free, unlike the weekly report that shares the bot.
	AlertApproval bool `json:"alert_approval"`
	AlertFinished bool `json:"alert_finished"`
	// AlertReply puts the first line of the final reply in a finished alert;
	// on unless turned off.
	AlertReply bool `json:"alert_reply"`
	// AlertDone sends a turn that asked nothing (Done) as a finished alert;
	// on unless turned off. The desktop app never notifies one.
	AlertDone bool `json:"alert_done"`
	// TelegramChat is the two-way Telegram switch (Premium, ADR-047);
	// TelegramCode keeps code blocks in the replies sent there. Both off
	// unless turned on.
	TelegramChat bool `json:"telegram_chat"`
	TelegramCode bool `json:"telegram_code"`
	// NotifyApproval and NotifyFinished are the desktop app's OS
	// notifications, apart from Telegram's: approval on unless turned off,
	// finished off unless turned on (WP-09).
	NotifyApproval bool `json:"notify_approval"`
	NotifyFinished bool `json:"notify_finished"`
	// Prompts is when each of the dashboard's own offers (star strip, Premium
	// and Teams nudges, share prompt) was last answered: prompt id → Unix ms.
	// On the daemon so the answer holds across the app and a browser tab.
	Prompts map[string]int64 `json:"prompts,omitempty"`
	// AlertLastError is why the last alert failed to send, empty when it did
	// not; AlertLastSentMs is when one last arrived, 0 for never since the
	// daemon started.
	AlertLastError  string `json:"alert_last_error,omitempty"`
	AlertLastSentMs int64  `json:"alert_last_sent_ms,omitempty"`
	// AlertUntested is a bot token or chat saved since the last alert was
	// tried: the outcome before it was the old bot's and is forgotten, and
	// none is known yet. Read-only.
	AlertUntested bool `json:"alert_untested,omitempty"`
	// BrowseRoot is the only directory the folder picker may look inside, and
	// the boundary every path it returns is checked against. Empty means the
	// user's home directory.
	//
	// It is a setting rather than a constant because "where I keep my code" is
	// personal — ~/dev for one person, ~/src or /work for another — and because
	// the narrower it is, the less this endpoint can be asked. See browse.go.
	BrowseRoot string `json:"browse_root,omitempty"`
	// DefaultFolder is where the Add project sheet starts: its folder field,
	// a new project's parent, a clone's destination and the folder browser.
	// Empty means the home folder. A leading ~ is the home folder.
	DefaultFolder string `json:"default_folder,omitempty"`
	// Terminal is the terminal application a session opens in when the user
	// asks for their own terminal: an id from GET /v1/terminals, or empty for
	// the first one installed.
	Terminal string `json:"terminal"`
	// Editor is the editor "Open in editor" uses: an id from GET
	// /v1/editors, or empty for the first one installed.
	Editor string `json:"editor"`
	// SpawnMode is the permission mode new sessions start in: what the
	// new-session dialogs open on, and what POST /v1/agents uses when the
	// request names no mode and has no session to carry one from. One of
	// agents.PermissionModes, or empty for not set.
	SpawnMode string `json:"spawn_permission_mode"`
	// KeepAwake is when the computer is kept from idle-sleeping: one of
	// keepawake.Modes. GET returns the effective mode, "working" when never
	// chosen (ADR-049).
	KeepAwake string `json:"keep_awake"`
	// WorktreeCleanup is what happens to finished copies: one of
	// projects.CleanupModes. GET returns the effective mode, "ask" when
	// never chosen.
	WorktreeCleanup string `json:"worktree_cleanup"`
	// EndIdleAfter is how long an agent session Caprock started, with no
	// tab, may sit idle before its process is ended: one of
	// config.EndIdleModes. GET returns the effective choice, "12h" when
	// never chosen.
	EndIdleAfter string `json:"end_idle_after"`
	// StatuslineMode is what Caprock's Claude Code status line shows: one
	// of config.StatuslineModes. GET returns the effective mode, "full"
	// when never chosen; "hidden" prints nothing but keeps forwarding the
	// plan windows; "off" removes Caprock's own statusLine entry from
	// Claude Code's settings (never the user's own).
	StatuslineMode string `json:"statusline_mode"`
	// QuickReplies are the one-click replies under a session Caprock
	// started (config.QuickReply). GET returns the list in use, the defaults
	// until changed; PUT replaces the whole list (config.NormalizeQuickReplies).
	QuickReplies []config.QuickReply `json:"quick_replies"`
	// AppUpdate is what the desktop app does when a newer release is found:
	// one of config.AppUpdateModes. GET returns the effective mode, "ask"
	// when never chosen.
	AppUpdate string `json:"app_update"`
}

Settings is the user-editable configuration exposed over the API. Caprock cannot detect how a user pays for Claude Code and never guesses — these values are stated by the user and stored locally.

type SettingsController added in v0.8.0

type SettingsController interface {
	Get() Settings
	Set(Settings) error
}

SettingsController is the subset of config handling the API needs. Values are entered by the user and stored locally; Caprock never fetches them.

type ShellController added in v0.75.0

type ShellController interface {
	StartShell(ctx context.Context, cwd string, cols, rows int) (ShellInfo, error)
	Shells() []ShellInfo
	IsShell(id string) bool
}

ShellController starts and lists shell tabs. The terminal itself is the agent's: /v1/agents/{id}/term, input, signal and resize.

type ShellInfo added in v0.75.0

type ShellInfo struct {
	ID              string `json:"id"`
	Cwd             string `json:"cwd"`
	Command         string `json:"command"`
	StartedAt       int64  `json:"started_at"`
	SurvivesRestart bool   `json:"survives_restart"`
	ProjectID       int64  `json:"project_id,omitempty"`
	// Program is what runs in front of the shell's prompt ("claude", "npm",
	// "vim"); absent when the shell is idle or the platform cannot tell.
	// Closing the tab of an idle shell ends it; a busy one asks first.
	Program string `json:"program,omitempty"`
	// Internal is always true: a shell is not a session and is in no total.
	Internal bool   `json:"internal"`
	Kind     string `json:"kind"` // "shell"
}

ShellInfo is a running shell tab.

type StatuslineStats added in v0.53.0

type StatuslineStats struct {
	Turns     int64 `json:"turns"`
	ToolCalls int64 `json:"tool_calls"`
	TokensIn  int64 `json:"tokens_in"`
	TokensOut int64 `json:"tokens_out"`
	// CacheRead and CacheWrite are returned raw rather than as a hit rate:
	// what counts as the denominator is a presentation choice, and the caller
	// that renders it should make it.
	CacheRead  int64 `json:"cache_read"`
	CacheWrite int64 `json:"cache_write"`
}

StatuslineStats is GET /v1/statusline/{id} — the figures the status line puts on screen, and nothing else.

The session detail endpoint already carries these, but it also loads sixty events, a hundred file paths, narration and a pricing lookup to do it. This runs on every assistant message, ahead of a line the user is waiting for, so it is deliberately one indexed row and no derived work.

type SubagentCallView added in v0.110.0

type SubagentCallView struct {
	// ID is the call's event id, the cursor ?before= pages by.
	ID        int64  `json:"id"`
	ToolUseID string `json:"tool_use_id,omitempty"`
	Tool      string `json:"tool"`
	// Detail is its short line, as the cockpit's tool list writes it.
	Detail    string `json:"detail,omitempty"`
	StartedAt int64  `json:"started_at"`
	// EndedAt is omitted while it has no result.
	EndedAt int64 `json:"ended_at,omitempty"`
	Error   bool  `json:"error,omitempty"`
}

SubagentCallView is one call in a subagent's activity feed.

type SubagentDetail added in v0.110.0

type SubagentDetail struct {
	AgentID      string `json:"agent_id"`
	AgentType    string `json:"agent_type,omitempty"`
	Description  string `json:"description,omitempty"`
	Prompt       string `json:"prompt,omitempty"`
	SubagentType string `json:"subagent_type,omitempty"`
	// ParentToolUseID is the parent's Agent/Task call that launched it.
	ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
	Background      bool   `json:"background,omitempty"`
	// State is "working", "finished" (its newest event is its
	// SubagentStop) or "quiet" (neither, and nothing heard for longer than
	// the live window).
	State     string `json:"state"`
	Asking    bool   `json:"asking"`
	StartedAt int64  `json:"started_at"`
	LastAt    int64  `json:"last_at"`
	StoppedAt int64  `json:"stopped_at,omitempty"`
	Result    string `json:"result,omitempty"`
	// Calls are the newest `limit` calls before the cursor, oldest first;
	// Earlier is how many older ones there are.
	Calls   []SubagentCallView `json:"calls"`
	Earlier int                `json:"earlier"`
	Stats   SubagentStats      `json:"stats"`
}

SubagentDetail is GET /v1/sessions/{id}/subagents/{agent}: one subagent opened up — the task its parent gave it, its calls, what it answered and its numbers.

type SubagentDone added in v0.94.0

type SubagentDone struct {
	AgentID     string `json:"agent_id"`
	AgentType   string `json:"agent_type,omitempty"`
	Description string `json:"description,omitempty"`
	ToolCalls   int    `json:"tool_calls"`
	// StartedAt is its first event in the window, StoppedAt its
	// SubagentStop (unix ms).
	StartedAt int64 `json:"started_at"`
	StoppedAt int64 `json:"stopped_at"`
	SubagentModel
}

SubagentDone is a subagent that finished lately.

type SubagentModel added in v0.94.0

type SubagentModel struct {
	// Model is its newest turn's model id, ModelDisplay the pricing table's
	// short name for it ("Haiku 4.5"); both omitted before its first turn.
	Model        string `json:"model,omitempty"`
	ModelDisplay string `json:"model_display,omitempty"`
	// CostUSD is omitted when unknown: no turn yet, or one the pricing
	// table could not price. Never a zero standing in for unknown.
	CostUSD *float64 `json:"cost_usd,omitempty"`
}

SubagentModel is the model a subagent runs on and what its own calls cost so far, from its transcript's turns.

type SubagentNow added in v0.92.0

type SubagentNow struct {
	AgentID     string `json:"agent_id"`
	AgentType   string `json:"agent_type,omitempty"`
	Description string `json:"description,omitempty"`
	ToolCalls   int    `json:"tool_calls"`
	StartedAt   int64  `json:"started_at"`
	LastAt      int64  `json:"last_at"`
	// Tool and Detail are its newest call — the file, command, pattern or
	// URL on one short line — and ToolAt when it started (unix ms).
	Tool   string `json:"tool,omitempty"`
	Detail string `json:"detail,omitempty"`
	ToolAt int64  `json:"tool_at,omitempty"`
	// Doing is roughly what it is doing now, at most 60 runes (subagentDoing),
	// and DoingFrom where that came from: "call" (its newest call's own
	// description), "tool" (its tool and target) or "task" (what it was
	// spawned to do). Both omitted when none of them says anything.
	Doing     string `json:"doing,omitempty"`
	DoingFrom string `json:"doing_from,omitempty"`
	Running   bool   `json:"running"`
	Asking    bool   `json:"asking"`
	SubagentModel
}

SubagentNow is one subagent working in a session, as the agent cockpit lists it (GET /v1/sessions/{id}/subagents).

type SubagentSaving added in v0.138.0

type SubagentSaving struct {
	// Models are the pricier models' display names, dearest spend first.
	Models []string `json:"models"`
	// CostUSD is those models' subagent tokens at the pricing table's rates.
	CostUSD float64 `json:"cost_usd"`
	// HaikuUSD is the same tokens at Haiku's rates; Haiku is its display name.
	HaikuUSD float64 `json:"haiku_usd"`
	Haiku    string  `json:"haiku"`
}

SubagentSaving is the honest hint beside the week's subagent spend: what the subagents that ran on a pricier model than Haiku cost at list prices, and what the same tokens would cost on Haiku. An estimate: Haiku is not a drop-in for every task, its answers and its token counts differ, and a prompt over a tier boundary is priced at the row's lower tier. Contract: .ai/03-contracts.md § Subagent saving.

type SubagentStats added in v0.110.0

type SubagentStats struct {
	ToolCalls  int                `json:"tool_calls"`
	Turns      int                `json:"turns"`
	Tokens     event.TokenDelta   `json:"tokens"`
	DurationMs int64              `json:"duration_ms"`
	ByTool     []SubagentToolCost `json:"by_tool"`
	SubagentModel
}

SubagentStats are a subagent's own numbers.

type SubagentToolCost added in v0.110.0

type SubagentToolCost struct {
	// Tool is empty for the turns that called no tool (they only wrote).
	Tool  string `json:"tool"`
	Calls int    `json:"calls"`
	// CostUSD is omitted when a turn behind it was not priced.
	CostUSD *float64 `json:"cost_usd,omitempty"`
}

SubagentToolCost is one tool kind's share of a subagent's spend.

type SubagentsResponse added in v0.92.0

type SubagentsResponse struct {
	Working []SubagentNow `json:"working"`
	// Finished is how many stopped within the same window after making a
	// tool call.
	Finished int `json:"finished"`
	// Recent is the newest of those, three unless ?recent= asks for more
	// (at most 30), newest stop first.
	Recent []SubagentDone `json:"recent"`
	// CostUSD is what every subagent of the session has cost, over its whole
	// life; omitted when any of them is unknown.
	CostUSD *float64 `json:"cost_usd,omitempty"`
}

SubagentsResponse is GET /v1/sessions/{id}/subagents.

type Subscription added in v0.101.0

type Subscription struct {
	// ID is "default" for the user's own sign-in, and Default is true for it
	// alone: the name predates Make default and means "own".
	ID      string `json:"id"`
	Agent   string `json:"agent"`
	Label   string `json:"label"`
	Default bool   `json:"default"`
	// Preferred marks the one a new session of this agent starts on when none
	// is picked (Make default). Exactly one per agent.
	Preferred bool `json:"preferred"`
	// Plan is how this sign-in is paid for, when the user said; the own
	// sign-in's is the main plan in /v1/settings and is not repeated here.
	Plan *SubscriptionPlan `json:"plan,omitempty"`
	// Dir is its configuration directory; EnvVar the variable that selects it
	// ("" for the Default one, which uses none).
	Dir    string `json:"dir"`
	EnvVar string `json:"env_var,omitempty"`
	// SignedIn and Account are read from files the agent wrote (internal/subs).
	SignedIn bool   `json:"signed_in"`
	Account  string `json:"account,omitempty"`
	// LoginCommand is the agent's own sign-in for this directory, to be typed
	// into a shell tab and run by the user.
	LoginCommand string `json:"login_command"`
	// LogoutCommand is the agent's own sign-out for this directory, typed
	// into a shell tab the same way: how an added subscription's credential
	// leaves the Keychain or keyring before it is removed. "" for the own
	// sign-in and for a provider.
	LogoutCommand string `json:"logout_command,omitempty"`
	// KeychainItem names the macOS Keychain item an added Claude Code
	// subscription's sign-in is kept in (subs.KeychainService), so the user
	// can find it; Caprock never opens it. "" elsewhere.
	KeychainItem string               `json:"keychain_item,omitempty"`
	Windows      []SubscriptionWindow `json:"windows"`
	// Sessions7d and Cost7dUSD are the last seven days of priced work on it.
	Sessions7d int64   `json:"sessions_7d"`
	Cost7dUSD  float64 `json:"cost_7d_usd"`
	// Running is how many sessions Caprock started are running on it.
	Running   int   `json:"running"`
	CreatedAt int64 `json:"created_at,omitempty"`
	// Provider is set on an entry that is not a sign-in but a model provider
	// Claude Code runs on with the user's own key: "deepseek" (id "deepseek").
	// It is offered in the pickers like a sign-in, but it has no directory,
	// no plan windows and no sign-in command, cannot be renamed, removed or
	// made the default, and does not count toward the free number.
	Provider string `json:"provider,omitempty"`
}

Subscription is one sign-in, as Settings and the pickers show it.

type SubscriptionAgent added in v0.101.0

type SubscriptionAgent struct {
	Agent         string         `json:"agent"`
	Label         string         `json:"label"`
	Installed     bool           `json:"installed"`
	Subscriptions []Subscription `json:"subscriptions"`
	// IgnoredEnv names the credential variables the user's login shell sets
	// that a session on an added subscription runs without, so it runs on
	// that subscription's own sign-in (subs.CredentialEnv). Names only.
	IgnoredEnv []string `json:"ignored_env,omitempty"`
}

SubscriptionAgent groups one agent's subscriptions, the Default one first.

type SubscriptionManager added in v0.101.0

type SubscriptionManager interface {
	List(ctx context.Context) (SubscriptionsResponse, error)
	Add(ctx context.Context, agent, label string) (Subscription, error)
	Update(ctx context.Context, id string, p SubscriptionPatch) (Subscription, error)
	Remove(ctx context.Context, id string) error
}

SubscriptionManager is the daemon's side.

type SubscriptionPatch added in v0.112.0

type SubscriptionPatch struct {
	Agent       string
	Label       *string
	MakeDefault bool
	// SetPlan with Plan nil clears the plan: the main one stands for it.
	SetPlan bool
	Plan    *SubscriptionPlan
}

SubscriptionPatch is PATCH /v1/subscriptions/{id}: each field present changes one thing. Agent names whose own sign-in "default" is.

type SubscriptionPlan added in v0.112.0

type SubscriptionPlan struct {
	Kind        string  `json:"kind"`
	Label       string  `json:"label,omitempty"`
	USDPerMonth float64 `json:"usd_per_month,omitempty"`
}

SubscriptionPlan is one sign-in's plan: kind "flat" or "metered", the user's words for it and a monthly price (0 = not stated).

type SubscriptionWindow added in v0.101.0

type SubscriptionWindow struct {
	Window         string  `json:"window"` // five_hour | seven_day
	UsedPercentage float64 `json:"used_percentage"`
	ResetsAt       int64   `json:"resets_at"`   // unix seconds
	ObservedAt     int64   `json:"observed_at"` // unix ms
}

SubscriptionWindow is one plan window as last reported for a subscription.

type SubscriptionsResponse added in v0.101.0

type SubscriptionsResponse struct {
	Agents       []SubscriptionAgent `json:"agents"`
	Licensed     bool                `json:"licensed"`
	FreePerAgent int                 `json:"free_per_agent"`
	// Home is where a sign-in's shell tab opens.
	Home string `json:"home,omitempty"`
}

SubscriptionsResponse is GET /v1/subscriptions.

type SummaryResponse

type SummaryResponse struct {
	store.Summary
	Savings    cost.Savings `json:"savings"`
	Burn       Burn         `json:"burn"`
	Pricing    string       `json:"pricing_version"`
	Throttles  int64        `json:"throttles"`             // rate-limit/overloaded events in range (honest signal, not a forecast)
	RateLimits *RateLimits  `json:"rate_limits,omitempty"` // live window state from Claude Code's statusline (Pro/Max only); nil when unknown
	// CodexRateLimits is Codex's plan windows as its newest transcript last
	// recorded them: measured, with observed_at, and never a forecast. nil
	// when no Codex transcript has carried one.
	CodexRateLimits *RateLimits `json:"codex_rate_limits,omitempty"`
	// Usual is this machine's own 30-day baseline the cockpit sets a
	// session's headline against (store.Usual); absent with too little
	// history, so a new user sees nothing rather than a guess.
	Usual *store.Usual `json:"usual,omitempty"`
}

SummaryResponse extends the store summary with burn rate and savings.

type SupportReport added in v0.128.0

type SupportReport struct {
	Text        string        `json:"text"`
	Email       string        `json:"email,omitempty"`
	Screenshots []SupportShot `json:"screenshots,omitempty"`
}

SupportReport is the body of POST /v1/support.

type SupportShot added in v0.128.0

type SupportShot struct {
	Name string `json:"name"`
	Type string `json:"type"`
	Data []byte `json:"data"`
}

SupportShot is one attached screenshot. Data is base64 in JSON (standard encoding, as encoding/json reads and writes []byte).

type TLDRResponse added in v0.128.0

type TLDRResponse struct {
	TLDR   string `json:"tldr"`
	Cached bool   `json:"cached"`
}

TLDRResponse is POST /v1/events/{id}/tldr.

type TabsAnswer added in v0.148.0

type TabsAnswer struct {
	// Known is false when no viewer's report counts (none yet, or none for
	// a week): the phone then lists live sessions in a fixed order.
	Known bool `json:"known"`
	// At is when that viewer last reported, unix ms; 0 when not known.
	At int64 `json:"at"`
	// Sessions is the reported list as it came: tab-strip order, and ids
	// that are not sessions (a file, a page, a shell) included.
	Sessions []string `json:"sessions"`
	// Items is each of those that is a session in the store, in the same
	// order, as GET /v1/sessions describes it. Shells are left out.
	Items []SessionSummary `json:"items"`
}

TabsAnswer is GET /v1/tabs: the tabs the computer has open, in tab-strip order, for the phone home's Continue (03-contracts.md § Open tabs).

type TaskController

type TaskController interface {
	// Enabled reports whether the task runner is on. It is asked per request
	// rather than assumed from the controller being non-nil, because the runner
	// can be turned on while the daemon runs (Enable) — the controller outlives
	// the off state.
	Enabled() bool
	// Enable opens a hive directory and starts the board on a running daemon.
	// An empty hiveDir/repoCwd means the daemon's own suggestion. Turning it on
	// twice is an error, not a silent rebuild.
	Enable(ctx context.Context, hiveDir, repoCwd string) (any, error)
	List(ctx context.Context) (any, error)
	Create(ctx context.Context, req any) (any, error)
	Get(ctx context.Context, id string) (any, error)
	Approve(ctx context.Context, id string, approve bool) error
	Approvals(ctx context.Context) (any, error)
	// StartOrchestrator spawns the orchestrator session (T21). Returns its info.
	StartOrchestrator(ctx context.Context) (any, error)
	// StopOrchestrator kills the orchestrator and every worker it spawned, in
	// one call. Returns how many sessions were stopped.
	StopOrchestrator(ctx context.Context) (any, error)
	// Starter is what the Tasks screen's templates prefill from: the repository
	// the workers branch from (current, or suggested while the runner is off),
	// the check commands that repository declares (internal/projcheck), and the
	// budget Caprock applies when a task names none. It answers with the runner
	// off too, so the off state can show a template against the real repo.
	Starter(ctx context.Context) (any, error)
	// Verify runs a task's done_criteria (T22). Returns the VerifyResult.
	Verify(ctx context.Context, id string) (any, error)
}

TaskController is the subset of the Phase 2 hive the API needs.

type TelegramController added in v0.101.0

type TelegramController interface {
	Status() telegram.Status
	Connect(ctx context.Context, token string) (telegram.User, error)
	Disconnect() error
	StartPairing() (telegram.Pairing, error)
	CancelPairing()
	SendPhoto(ctx context.Context, png []byte, caption string) error
	// SendModule sends a private module's message to the paired chat
	// (POST /v1/x/{id}/telegram) and returns its Telegram message id.
	SendModule(ctx context.Context, m telegram.ModuleMessage) (int64, error)
	// EditModule changes a message that module sent
	// (PATCH /v1/x/{id}/telegram/{message_id}).
	EditModule(ctx context.Context, e telegram.ModuleEdit) error
}

TelegramController is the bridge to the owner's own Telegram bot (ADR-047), as Settings drives it. Every route here is the machine's: none is on a paired device's allowlist (ADR-034, "outbound calls").

type TermStream added in v0.75.0

type TermStream interface {
	// Ring is the session's output with offsets.
	Ring() *termbuf.Ring
	// Done is closed when the process exits.
	Done() <-chan struct{}
	// Exited reports the exit code once Done is closed.
	Exited() (int, bool)
	// InputSeq types data unless the client's seq was applied already, and
	// returns the client's last applied sequence (seq 0: only ask).
	InputSeq(client string, seq uint64, data []byte) (uint64, error)
}

TermStream is an owned session's terminal as protocol v2 sees it.

type TerminalController added in v0.70.1

type TerminalController interface {
	// List is the installed terminals, most preferred first, and the id of
	// the one a button opens when none is named.
	List() (terminals []nativeterm.Terminal, preferred string)
	// Open runs argv in cwd in the terminal with this id ("" for the
	// preferred one). before runs once the launch is planned and before it
	// starts — so a refusal (no such terminal, an unsafe folder name) is
	// known before anything is stopped for it.
	Open(ctx context.Context, terminal, cwd string, argv []string, before func() error) (nativeterm.Terminal, string, error)
}

TerminalController finds the user's own terminal applications and opens a command in one (internal/nativeterm). nil ⇒ the endpoints answer 501.

type ToolDrillResponse added in v0.70.0

type ToolDrillResponse struct {
	store.ToolDrill
	Range  string           `json:"range"`
	Locked bool             `json:"locked"`
	Teaser *store.DrillHint `json:"teaser,omitempty"`
}

ToolDrillResponse is GET /v1/tools/drill: one tool's calls grouped by what they were about. Contract: .ai/03-contracts.md.

The groups and their call counts are free. What came back — bytes, failure rates, the per-group trend and the hints — is Premium (ADR-022), and is removed here, on the server, when the licence is not active: a gate the page enforces alone is a gate anyone can open from the console. One hint, the strongest, is sent in full either way as Teaser, so a reader without a licence sees the kind of thing they would get rather than a blur.

type UpdateController added in v0.8.1

type UpdateController interface {
	Status(enabled bool, current string) update.Status
	Check(ctx context.Context, force bool) error
	// CheckSoon is the check a page asks for when its window comes to the
	// front: it reaches the network only when the last check is ten minutes
	// old (update.SoonInterval).
	CheckSoon(ctx context.Context) error
}

UpdateController is the subset of the release checker the API needs.

type WeekResponse added in v0.70.0

type WeekResponse struct {
	store.Week
	// Period is the named window asked for (today, 7d, 30d, all), or empty
	// for a week picked by its first day.
	Period string `json:"period,omitempty"`
	// Start and End are the first and last local day, inclusive.
	Start string `json:"start"`
	End   string `json:"end"`
	// Partial is true while the window has not finished: it reaches today.
	Partial bool `json:"partial"`
	// Tax is the share of the cost that went on re-reading context, priced
	// per model exactly as the Lifetime screen prices it. Absent without a
	// pricing table.
	Tax *contexttax.Lifetime `json:"tax,omitempty"`
	// CostPerMergedPR divides all of the week's cost by the merges counted:
	// an estimate (research, docs and sessions that merged nothing are in the
	// numerator), and absent when nothing was merged.
	CostPerMergedPR *float64 `json:"cost_per_merged_pr,omitempty"`
	// SubagentSaving is what the window's subagents on a pricier model than
	// Haiku cost, against the same tokens on Haiku. An estimate at list
	// prices; absent unless the difference is a dollar or more.
	SubagentSaving *SubagentSaving `json:"subagent_saving,omitempty"`
	// Estimates names the fields that are estimates rather than counts or
	// sums, so a renderer cannot forget the "≈" on one.
	Estimates []string `json:"estimates"`
	Pricing   string   `json:"pricing_version,omitempty"`
}

WeekResponse is GET /v1/week: seven local days of what this machine's agents did, for the Week screen's shareable card. Contract: .ai/03-contracts.md.

Everything is computed from the local database; nothing here asks GitHub, so "merged" means a merge the agents ran and saw succeed, never GitHub's state. Nothing in it names a repository, a path, a prompt or a session title: the card is made to be posted.

type Work added in v0.118.0

type Work struct {
	// Now is the daemon's clock (unix ms); every ETA counts from it.
	Now int64 `json:"now"`
	// DayStart is the local midnight today's figures count from (unix ms).
	DayStart int64         `json:"day_start"`
	Sessions []WorkSession `json:"sessions"`
	// Tasks are the task runner's tasks; absent when the runner is off.
	Tasks  []WorkTask   `json:"tasks,omitempty"`
	Hive   string       `json:"hive"` // on | off
	Queued []WorkQueued `json:"queued"`
	Repos  []WorkRepo   `json:"repos"`
	Totals WorkTotals   `json:"totals"`
}

Work is GET /v1/work.

type WorkBoarder added in v0.118.0

type WorkBoarder interface {
	Work(ctx context.Context) (Work, error)
}

WorkBoarder assembles the Work board. Optional on Deps: nil answers 501.

type WorkPR added in v0.118.0

type WorkPR struct {
	Number   int    `json:"number"`
	URL      string `json:"url"`
	Title    string `json:"title,omitempty"`
	OpenedAt int64  `json:"opened_at,omitempty"`
	MergedAt int64  `json:"merged_at,omitempty"`
}

WorkPR is one recorded pull request.

type WorkQueued added in v0.118.0

type WorkQueued struct {
	SessionID string `json:"session_id"`
	Position  int    `json:"position"`
	// Text is clipped to 200 runes.
	Text   string `json:"text"`
	Start  *ETA   `json:"start,omitempty"`
	Finish *ETA   `json:"finish,omitempty"`
}

WorkQueued is a message waiting in an owned session's queue.

type WorkRepo added in v0.118.0

type WorkRepo struct {
	Root string `json:"root"`
	Name string `json:"name"`
	// Remote is "owner/name" from its remote's web address.
	Remote string `json:"remote,omitempty"`
	// ViaSession is the newest session that brought the repository here.
	ViaSession string `json:"via_session"`
	// Live counts its live sessions.
	Live       int             `json:"live"`
	Unreleased *WorkUnreleased `json:"unreleased,omitempty"`
	Tags       *WorkTags       `json:"tags,omitempty"`
	// AheadOfTag is how many commits the default branch has past the last
	// tag, as of the last fetch.
	AheadOfTag *int `json:"ahead_of_tag,omitempty"`
}

WorkRepo is a repository a live or recent session works in.

type WorkSession added in v0.118.0

type WorkSession struct {
	SessionID string `json:"session_id"`
	Agent     string `json:"agent"`
	// Owned: Caprock started it.
	Owned        bool   `json:"owned"`
	Model        string `json:"model,omitempty"`
	ModelDisplay string `json:"model_display,omitempty"`
	Subscription string `json:"subscription,omitempty"`
	Name         string `json:"name,omitempty"`
	// Description and DescriptionSource as on the session list.
	Description       string `json:"description,omitempty"`
	DescriptionSource string `json:"description_source,omitempty"`
	Project           string `json:"project"`
	RepoRoot          string `json:"repo_root,omitempty"`
	Worktree          string `json:"worktree,omitempty"`
	Branch            string `json:"branch,omitempty"`
	// OnDefault: Branch is the repository's default branch, as the clone
	// knows it. Absent when either is unknown.
	OnDefault *bool  `json:"on_default,omitempty"`
	StartedAt int64  `json:"started_at"`
	WorkedAt  int64  `json:"worked_at,omitempty"`
	State     string `json:"state"`
	// TurnStartedAt is when the running turn's prompt was sent (unix ms).
	TurnStartedAt int64 `json:"turn_started_at,omitempty"`
	// TurnLeft is the running turn's remaining time, from the project's
	// finished turns (the Queue's estimate); only while it works.
	TurnLeft     *ETA       `json:"turn_left,omitempty"`
	Estimate     *Estimate  `json:"estimate,omitempty"`
	EstimateNote string     `json:"estimate_note,omitempty"`
	Todo         *BoardTodo `json:"todo,omitempty"`
	CostUSD      float64    `json:"cost_usd"`
	TodayUSD     float64    `json:"today_usd"`
	// PRs are the pull requests the session's own commands opened or
	// merged, newest four.
	PRs      []WorkPR `json:"prs"`
	Link     string   `json:"link"`
	LinkNote string   `json:"link_note,omitempty"`
}

WorkSession is one live session (shells are not sessions).

type WorkTag added in v0.118.0

type WorkTag struct {
	Name string `json:"name"`
	At   int64  `json:"at"`
}

WorkTag is one tag.

type WorkTags added in v0.118.0

type WorkTags struct {
	Last *WorkTag `json:"last,omitempty"`
	// GapMedianMs is the median time between the newest (up to eleven)
	// tags; absent with fewer than three gaps.
	GapMedianMs int64 `json:"gap_median_ms,omitempty"`
	Gaps        int   `json:"gaps"`
}

WorkTags is the newest tags, read locally.

type WorkTask added in v0.118.0

type WorkTask struct {
	ID        string  `json:"id"`
	Title     string  `json:"title"`
	Status    string  `json:"status"`
	SessionID string  `json:"session_id,omitempty"`
	Branch    string  `json:"branch,omitempty"`
	BudgetUSD float64 `json:"budget_usd"`
	SpentUSD  float64 `json:"spent_usd"`
}

WorkTask is one of the task runner's tasks.

type WorkTotals added in v0.118.0

type WorkTotals struct {
	Live       int `json:"live"`
	Working    int `json:"working"`
	WaitingYou int `json:"waiting_you"`
	// TodayUSD sums the live sessions' today_usd; MachineTodayUSD is every
	// session's since DayStart.
	TodayUSD        float64 `json:"today_usd"`
	MachineTodayUSD float64 `json:"machine_today_usd"`
}

WorkTotals sums the board up.

type WorkUnreleased added in v0.118.0

type WorkUnreleased struct {
	// Ref is the branch it was read from, "origin/main".
	Ref string `json:"ref"`
	// Items are its top-level entries' first lines, at most 30.
	Items []string `json:"items"`
	Count int      `json:"count"`
	// More: Count is larger than Items.
	More bool `json:"more,omitempty"`
	// Kinds counts the entries by Keep a Changelog kind (Added, Fixed, …):
	// the `### ` heading in the section, a fragment's `kind:`. An entry of
	// no kind counts in Count only. Absent when none has a kind.
	Kinds map[string]int `json:"kinds,omitempty"`
}

WorkUnreleased is the CHANGELOG's [Unreleased] section on the remote's default branch, as of the last fetch.

Jump to

Keyboard shortcuts

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