api

package
v0.107.5 Latest Latest
Warning

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

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

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 (
	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 (
	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 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 ErrBypassConsent error = bypassConsentError{}

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

Functions

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 DistFS

func DistFS() fs.FS

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

func UIBuilt

func UIBuilt() bool

UIBuilt reports whether the real dashboard is embedded.

Types

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 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 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 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
	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)
	// KeepAwake returns whether the computer is being kept awake, for GET
	// /v1/keepawake (keepawake.Status). Nil ⇒ 501.
	KeepAwake func() any
	// 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
	}
	// 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
	// Catalog answers the agent pickers and keeps the custom agents
	// (ADR-046). nil ⇒ /v1/agents/catalog and /v1/agents/custom return 501.
	Catalog AgentCatalog
	// 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
	// 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
	// Projects is the projects list, its git state and clones (nil ⇒ the
	// /v1/projects endpoints return 501).
	Projects *projects.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
	// 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 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 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"`
}

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 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 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 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 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 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 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 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) 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, and the share dialog's all-time and 30-day Weeks — so the first screen after a start finds them cached instead of paying for the scans. 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 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 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 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:"-"`
	// 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"`
	// 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"`
	// 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"`
	// 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"`
}

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 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"`
	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 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, at most three, 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.
	ID      string `json:"id"`
	Agent   string `json:"agent"`
	Label   string `json:"label"`
	Default bool   `json:"default"`
	// 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"`
	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"`
}

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"`
}

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)
	Rename(ctx context.Context, id, label string) (Subscription, error)
	Remove(ctx context.Context, id string) error
}

SubscriptionManager is the daemon's side.

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"`
}

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.

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()
}

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
}

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

Jump to

Keyboard shortcuts

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