Documentation
¶
Overview ¶
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:
- **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.
- **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.
- **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.
A short-lived cache in front of /v1/history, and single-flight around it.
The endpoint answers "everything, ever": four aggregates over the whole events table. On the owner's 600 MB database that is ~540ms warm, and the expensive half is a 160,000-row scan whose cost is per-row driver work rather than SQL — `sqlite3` runs the same scan in 160ms, so there is no index that fixes it.
What makes that hurt is how it is asked for. Five components on the main screen call `api.history('all')` on their own timers — the lifetime strip, the breakdown panel, the share card, the share nudge, and the screen itself — so a single open tab produces bursts of identical requests, and each one was computed from scratch. Three arriving together took three connections and roughly three times the work to produce three identical answers.
Two things fix that, and neither is a faster query:
- **Single-flight.** Requests for the same range that arrive while one is already running wait for it and share its result, instead of starting their own. This is what collapses the burst.
- **A short TTL.** Lifetime figures move by one turn at a time; serving a few-second-old copy is invisible on a screen that polls every 60s.
The TTL is deliberately shorter than the fastest poller. It exists to collapse a burst, not to serve stale numbers: anyone who reloads the page gets figures no older than `historyTTL`, and the live pulse — which is what people actually watch move — does not come through this endpoint at all.
Writes do not invalidate it. An entry expires on its own within seconds, and wiring ingest into an HTTP cache would couple the recorder to the API for a few seconds of freshness nobody can perceive.
Index ¶
- func DistFS() fs.FS
- func UIBuilt() bool
- type AgentController
- type Burn
- type ContextFill
- type Deps
- type HistoryResponse
- type RateLimits
- type RateWindow
- type ReportSender
- type Server
- type SessionDetail
- type SessionSummary
- type Settings
- type SettingsController
- type StatuslineStats
- type SummaryResponse
- type TaskController
- type UpdateController
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AgentController ¶
type AgentController interface {
Available() 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)
Write(sessionID string, data []byte) error
}
AgentController is the subset of internal/agents the API needs (interface for tests).
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 ContextFill ¶
type ContextFill struct {
Tokens int64 `json:"tokens"`
Window int64 `json:"window"`
Pct float64 `json:"pct"`
}
ContextFill is the "context fill %" badge input: last turn's prompt size vs the model window.
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
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
// 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
}
// ActiveLoops reports whether a session currently has an unexpired loop alert.
ActiveLoops func(sessionID string) *loop.Alert
// 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
// 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
// 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 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"`
}
HistoryResponse is /v1/history.
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"`
}
RateWindow is one window's measured state plus an optional honest forecast.
type ReportSender ¶ added in v0.46.0
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 Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the http.Handler.
type SessionDetail ¶
type SessionDetail struct {
SessionSummary
Files []string `json:"files"`
Events []event.Event `json:"events"`
}
SessionDetail is /v1/sessions/{id}.
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"`
}
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"`
// 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"`
// 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:"-"`
// 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:"-"`
// 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"`
// 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"`
}
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
SettingsController is the subset of config handling the API needs. Values are entered by the user and stored locally; Caprock never fetches them.
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 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
}
SummaryResponse extends the store summary with burn rate and savings.
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)
// 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.