daemon

package
v0.93.1 Latest Latest
Warning

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

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

Package daemon wires every component into the running `caprock up` process: store, pricing, recorder, hookd, ingest, loop detector, API/WS server, the idle sweeper, and the runtime.json lifecycle.

Index

Constants

View Source
const EnvTelegramAPI = "CAPROCK_TELEGRAM_API"

EnvTelegramAPI replaces the Telegram API host, for testing against a stub.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, opt Options) error

Run starts the daemon and blocks until ctx is cancelled or a fatal error occurs.

Types

type Daemon

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

Daemon is a running instance.

func (*Daemon) DisableLAN added in v0.50.0

func (d *Daemon) DisableLAN() error

DisableLAN closes the second listener. Paired devices are kept — they are the guest list, not the open door — so turning it back on does not mean walking to the tablet again.

func (*Daemon) EnableLAN added in v0.50.0

func (d *Daemon) EnableLAN() (string, error)

EnableLAN opens the second listener on this machine's private address, so a device on the same network can reach the dashboard after pairing.

Callable while the daemon runs, because the dashboard is where a person is when they decide they want this — and the alternative was "restart it from a terminal", which on a machine you are reading from a tablet is advice to give up. `caprock up --lan` still works and does the same thing at startup.

Still not remembered across a restart. That was the point of making it a flag: a laptop opened somewhere you do not trust should not be carrying a decision you made at home. Switching it on is an act, every time.

func (*Daemon) SendAlertCheck added in v0.72.0

func (d *Daemon) SendAlertCheck(ctx context.Context) error

SendAlertCheck sends a test alert now, so whoever set up the bot sees what an alert looks like without waiting for a session to need them.

func (*Daemon) SendReportNow added in v0.46.0

func (d *Daemon) SendReportNow(ctx context.Context) error

weeklyLoop sends the report when a week has gone by, not when a timer fires.

A ticker set for Monday 09:00 sends to nobody: the laptop is closed at the weekend, macOS does not fire missed ticks on wake, and the next tick is a week later. So this asks a question instead — is the ISO week of the last report we sent behind the current one, and is it past the send hour — and answers it every hour. A machine opened on Wednesday gets Monday's report on Wednesday, labelled with the week it covers, which is the honest outcome.

The marker is in the store rather than in memory, or a restart would send a second copy. SendReportNow builds this week's report and sends it immediately.

Without this the only way to find out whether a bot token and chat id are right is to wait for Monday. Somebody pastes two values, presses save, and has no way to tell a working setup from a typo until a week has passed — at which point nothing arrives and there is still nothing to look at, because the failure mode of this feature is silence.

It deliberately does not touch the week marker: a test send must not make the real report skip its week.

func (*Daemon) URL

func (d *Daemon) URL() string

URL returns the bound base URL (after start).

type FileSize added in v0.64.0

type FileSize struct {
	Name  string `json:"name"`
	Bytes int64  `json:"bytes"`
	Dir   bool   `json:"dir,omitempty"`
}

FileSize is one top-level entry of the data directory; a directory is the sum of the files under it.

type Interrupted added in v0.60.0

type Interrupted struct {
	// StoppedAt is the last heartbeat of the run that stopped, unix ms: when
	// it stopped, to within a minute.
	StoppedAt int64    `json:"stopped_at"`
	IDs       []string `json:"ids"`
}

Interrupted is the sessions that were running when Caprock last stopped and were gone when it came back — a reboot, an OS update, the laptop lid. Somebody coming back to the machine wants exactly these, and they were scattered among every other ended session with nothing to tell them apart (FB-038).

type MemoryStatus added in v0.51.0

type MemoryStatus struct {
	// Repos and Since describe the handoff: how many folders it can speak for,
	// and the oldest passage recent enough to be handed over.
	Repos int    `json:"repos"`
	Since string `json:"since,omitempty"`
	// Held is when the oldest passage Caprock still has was written — the whole
	// corpus, not the fortnight the handoff reaches. The search screen spans
	// all of it, and using the handoff's date there would understate what is
	// searchable by a month.
	Held string `json:"held,omitempty"`
	// HoldoutPct is the share of handoffs held back to measure them, and
	// Served / Withheld how each group has done so far: how many sessions,
	// how many reached a first edit, and the median minutes and tool calls to
	// get there. Absent until a session has been counted in either group.
	HoldoutPct int                 `json:"holdout_pct,omitempty"`
	Served     *store.HandoffGroup `json:"served,omitempty"`
	Withheld   *store.HandoffGroup `json:"withheld,omitempty"`
}

MemoryStatus is what the handoff can do on this machine: how many repositories it could speak for, and since when.

type Options

type Options struct {
	DataDir        string
	Config         config.Config
	Version        string
	Log            *slog.Logger
	TranscriptRoot string // "" ⇒ ~/.claude/projects
	// Listener overrides the port (tests pass a pre-bound 127.0.0.1:0 listener).
	Listener net.Listener
	// LAN also serves the machine's private network address, so a tablet or
	// phone on the same network can reach the dashboard after pairing.
	//
	// A run flag rather than a stored setting, deliberately. Loopback-only is
	// what the product promises, and a promise that quietly survives a restart
	// is one nobody re-consents to: a laptop opened in a coworking space would
	// carry a decision made at home on a trusted network. Turning it on is an
	// act, every time.
	LAN bool
	// DisableIngest turns transcript tailing off (tests, or hooks-only mode).
	DisableIngest bool
	// OpenCodeURL overrides where OpenCode's headless server is expected.
	// Empty means the documented default; tests point it at a stub.
	OpenCodeURL string
	// OpenCodeDB overrides where OpenCode's database is looked for. Empty means
	// discover it; "off" disables the reader entirely. Tests must set one or
	// the other, or a developer's own OpenCode sessions leak into a temporary
	// store and make assertions about session counts fail on their machine and
	// pass in CI.
	OpenCodeDB string
	// CodexDir overrides where Codex's rollout transcripts are looked for.
	// Empty means the default (sessions/ and archived_sessions/ under
	// $CODEX_HOME, else ~/.codex); "off" disables the import.
	CodexDir string
	// DeepseekDir overrides where DeepSeek Harness session transcripts are
	// looked for. Empty means the default (~/.dsh/sessions); "off" disables it.
	DeepseekDir string
	// IdleAfter is the silence threshold before a session is marked idle.
	IdleAfter time.Duration
	// EndAfter is the silence threshold before a session is marked ended
	// (default 1h). It is a backstop, not the main path: SessionEnd ends a
	// session the moment the user leaves it. What this catches is the session
	// whose hook never fired — kill -9, a closed terminal, a crashed host.
	EndAfter time.Duration
	// HiveDir enables Phase 2 orchestration (tasks board + Stop-loop) at this path.
	// Empty ⇒ orchestration off (task endpoints return 501).
	HiveDir string
	// RepoCwd is the repo the orchestrator + workers operate on (default: cwd).
	RepoCwd string
	// HolderExe is the Caprock binary that runs `pty-host`, the process that
	// keeps an owned session's terminal alive across daemon restarts
	// (ADR-033). Empty runs sessions inside the daemon, as before: tests that
	// run the daemon in-process have no such binary to offer.
	HolderExe string
	// OnReady is called once the server is listening (with the bound URL).
	OnReady func(url string)
}

Options configure a daemon run.

type PricingStatus

type PricingStatus struct {
	Version      string `json:"version"`
	Source       string `json:"source"`
	FetchedAt    string `json:"fetched_at"`
	UserOverride bool   `json:"user_override"`
	Models       int    `json:"models"`
}

PricingStatus summarizes the table in force.

type Status

type Status struct {
	Version string `json:"version"`
	// APILevel is version.APILevel: what a client compares against the
	// minimum it needs, instead of parsing Version.
	APILevel int `json:"api_level"`
	// Platform is GOOS/GOARCH — the first thing a bug report needs and the
	// last thing anyone remembers to include.
	Platform  string        `json:"platform"`
	PID       int           `json:"pid"`
	StartedAt int64         `json:"started_at"`
	UptimeS   int64         `json:"uptime_s"`
	URL       string        `json:"url"`
	DataDir   string        `json:"data_dir"`
	Pricing   PricingStatus `json:"pricing"`
	Ingest    *ingest.Stats `json:"ingest,omitempty"`
	// IngestError is the terminal error that stopped transcript ingest, when
	// one happened (a read-only ~/.claude, a vanished transcript root). Empty
	// while ingest is running. Without it the daemon looked healthy while
	// capturing nothing, and the dashboard told the user to start `claude` and
	// wait for sessions that could never arrive.
	IngestError string        `json:"ingest_error,omitempty"`
	Hooks       *hooks.Status `json:"hooks,omitempty"`
	// ClaudeBypassAccepted says the user accepted Claude Code's one-time
	// bypass warning, so a bypass session starts without it (ADR-041).
	ClaudeBypassAccepted bool `json:"claude_bypass_accepted"`
	UIBuilt              bool `json:"ui_built"`
	ClaudeAvailable      bool `json:"claude_available"`
	// ShellEnv says whether sessions Caprock starts get the user's login-shell
	// environment or, because it could not be read, the daemon's own — the
	// difference between a spawned session finding gcloud and not (FB-033).
	ShellEnv userenv.State `json:"shell_env"`
	// GeminiAvailable says the Gemini CLI is on PATH, so the new-session
	// dialog offers an agent the machine actually has rather than a choice
	// that fails on click.
	GeminiAvailable bool `json:"gemini_available"`
	// CodexAvailable and OpenCodeAvailable say the same of those CLIs, found on
	// the login shell's PATH or where their installers put them.
	CodexAvailable    bool `json:"codex_available"`
	OpenCodeAvailable bool `json:"opencode_available"`
	// OpenCodeVersion is the version of the OpenCode a new session would
	// start ("2.0.26"), absent while unknown. OpenCode 1 and 2 take different
	// flags, and the New session dialog words a mode by what it becomes.
	OpenCodeVersion string `json:"opencode_version,omitempty"`
	// OpenCode reports what the second agent's reader is doing, or is absent
	// when OpenCode is not installed. Without it there was no way to tell
	// whether a machine that runs OpenCode was having those sessions read:
	// the dashboard shows them mixed in with Claude Code's, so their absence
	// looks the same as having none.
	OpenCode *opencode.Stats `json:"opencode,omitempty"`
	// Codex reports the third agent's reader on the same terms, and is absent
	// when the machine has no Codex transcripts.
	Codex *codex.Stats `json:"codex,omitempty"`
	// Deepseek reports the DeepSeek Harness reader on the same terms, and is
	// absent when the machine has no DSH transcripts.
	Deepseek      *deepseek.Stats `json:"deepseek,omitempty"`
	OwnedActive   int             `json:"owned_active"`
	Orchestration bool            `json:"orchestration"`
	// Memory reports how many repositories have enough history to hand a new
	// session what was left there. A feature that acts before you type is one
	// nobody can see working, so the status screen says whether it can.
	Memory MemoryStatus `json:"memory"`
	// Hive is the orchestration directory in force, and Repo the checkout its
	// workers operate on. Both empty when orchestration is off. Without them
	// there was no way — CLI, API or log — to ask which hive a running daemon
	// had been started with.
	Hive string `json:"hive,omitempty"`
	Repo string `json:"repo,omitempty"`
	// SuggestedHive and SuggestedRepo are what POST /v1/hive would use if it were
	// called with no body — the defaults the dashboard shows for confirmation
	// before turning the runner on. Present only while orchestration is off.
	SuggestedHive string `json:"suggested_hive,omitempty"`
	SuggestedRepo string `json:"suggested_repo,omitempty"`
	LoopK         int    `json:"loop_k"`
	LoopTMin      int    `json:"loop_t_minutes"`
	ActiveLoops   int    `json:"active_loops"`
	Events        int64  `json:"events"`
	RetentionDays int    `json:"retention_days"`
	// Interrupted is the sessions the last stop of Caprock (or of the
	// machine) cut off and nobody has continued yet. Absent when there are
	// none (FB-038).
	Interrupted *Interrupted `json:"interrupted,omitempty"`
	// Desktop is the Claude desktop app's own plan usage, when it has any on
	// this machine. Omitted entirely otherwise — most people do not use it.
	Desktop *desktop.Reading `json:"desktop,omitempty"`
}

Status is /v1/status.

type StorageReport added in v0.64.0

type StorageReport struct {
	DataDir string `json:"data_dir"`
	// TotalBytes is every file under the data directory, the database
	// included; Files splits it by top-level entry, largest first.
	TotalBytes int64      `json:"total_bytes"`
	Files      []FileSize `json:"files"`
	// Database is the cached composition, absent until it has been measured
	// once; MeasuredAt and MeasureMs say when and how long it took.
	Database   *store.Storage `json:"database,omitempty"`
	MeasuredAt int64          `json:"measured_at,omitempty"`
	MeasureMs  int64          `json:"measure_ms,omitempty"`
	Error      string         `json:"error,omitempty"`
	// ReclaimableBytes is the database's free pages: what a VACUUM would hand
	// back to the disk. Zero until measured.
	ReclaimableBytes int64 `json:"reclaimable_bytes"`
	// GrowthBytesPerDayEst is an estimate, and named as one: the bytes of
	// event payload recorded over the last 30 days, per day, scaled by how
	// many bytes on disk each payload byte has cost so far (the events table
	// and its indexes over the payload they hold). Zero when there is too
	// little to scale by.
	GrowthBytesPerDayEst int64 `json:"growth_bytes_per_day_est"`
	RetentionDays        int   `json:"retention_days"`
}

StorageReport is what GET /v1/storage returns. See 03-contracts.md § Storage.

Jump to

Keyboard shortcuts

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