agentevents

package
v2.6.2 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 16 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 agentevents ingests the push-based lifecycle and usage signals an agent reports about itself — Claude Code's settings-driven hooks and statusline, and (where 0.155 supports it) Codex's hooks.json/notify — and turns them into session state, per contract in docs/agent-events.md section 2. It never launches or scrapes anything; that stays in internal/sessions. The two meet only at the session row and the bus.

Package agentevents' otel.go decodes the OTLP/HTTP JSON payloads Claude Code's own OpenTelemetry exporter sends when CLAUDE_CODE_ENABLE_TELEMETRY=1 and OTEL_EXPORTER_OTLP_PROTOCOL=http/json — see https://code.claude.com/docs/en/monitoring-usage and docs/outcomes.md for the field names this was built against.

Only the shapes lectern reads are declared; OTLP's JSON mapping (the protobuf JSON encoding) serializes every int64/uint64 as a JSON STRING, not a bare number — asInt and timeUnixNano both do this — so otlpInt below tolerates a quoted OR bare number rather than assuming the newer/stricter form.

Index

Constants

View Source
const (
	EnvHookToken = "LECTERN_HOOK_TOKEN"
	EnvHookURL   = "LECTERN_HOOK_URL"
)

Env names injected into every interactive session's process environment at launch (see internal/sessions.Manager.launch), read back by whatever the agent's own hooks/statusline scripts run with. EnvHookURL is the base for one session's hook endpoints — POST $LECTERN_HOOK_URL/<event> and $LECTERN_HOOK_URL/statusline — not a single fixed URL.

View Source
const (
	OTelResourceSessionKey = "lectern.session_id"
	OTelResourceAttemptKey = "lectern.attempt_id"
)

OTelResourceSessionKey/OTelResourceAttemptKey are the resource attribute names OTelEnv uses to correlate a payload with the lectern row that launched it — see OTelEnv's doc comment on why correlation is informational only, not part of the auth boundary.

View Source
const (
	StateWorking           = "working"
	StateWaitingInput      = "waiting_input"
	StateWaitingPermission = "waiting_permission"
	StateIdle              = "idle"
	StateError             = "error"
	StateEnded             = "ended"
)

Session lifecycle states, distinct from the older screen-derived sessions.Status enum (starting|running|waiting|idle|dead). A session can be hook-driven (state_source="hook") or, absent hooks or after a 10-minute silence, screen-derived (state_source="screen") — see poll.go's applyPane.

View Source
const (
	SourceHook   = "hook"
	SourceScreen = "screen"
)

SourceHook and SourceScreen are the values stored in sessions.state_source.

View Source
const (
	EventSessionStart      = "SessionStart"
	EventUserPromptSubmit  = "UserPromptSubmit"
	EventPreToolUse        = "PreToolUse"
	EventPostToolUse       = "PostToolUse"
	EventNotification      = "Notification" // Claude only; codex has no equivalent hook
	EventStop              = "Stop"
	EventStopFailure       = "StopFailure" // Claude only
	EventPreCompact        = "PreCompact"
	EventSessionEnd        = "SessionEnd"
	EventPermissionRequest = "PermissionRequest"
	EventSubagentStart     = "SubagentStart" // codex extension
	EventSubagentStop      = "SubagentStop"  // codex extension
	EventInterrupt         = "Interrupt"     // codex extension
	// EventAgentTurnComplete is not a hooks.json event: it is synthesized by
	// the small notify script codex's `-c notify=[...]` invokes on
	// agent-turn-complete (see settings.go), which lectern maps to the same
	// event name so it flows through the one ingest path below.
	EventAgentTurnComplete = "AgentTurnComplete"
)

Claude/Codex hook event names, exactly as they arrive in hook_event_name (both CLIs use the same vocabulary for the events they share — verified against the codex 0.155.1 binary's embedded hook JSON schemas, which reuse Claude Code's wire format byte-for-byte down to field names).

View Source
const (
	NotificationPermissionPrompt = "permission_prompt"
	NotificationIdlePrompt       = "idle_prompt"
)

Notification.notification_type values (Claude only).

View Source
const (
	MetricCostUsage    = "claude_code.cost.usage"
	MetricTokenUsage   = "claude_code.token.usage"
	MetricLinesOfCode  = "claude_code.lines_of_code.count"
	MetricPullRequests = "claude_code.pull_request.count"
	MetricCommits      = "claude_code.commit.count"
)

Claude Code's own metric names (see the package doc's docs link). Exported so tests and internal/outcomes can build fixtures without repeating the literal strings.

View Source
const CodexHookScript = `#!/usr/bin/env python3
"""lectern codex hook handler (` + codexHookMarker + `) — see
internal/agentevents/codex_settings.go.

Invoked by codex per hooks.json, as "<this file> <event> <timeout>", with the
hook JSON on stdin.
"""
import os
import subprocess
import sys

TOKEN = os.environ.get("LECTERN_HOOK_TOKEN", "")
URL = os.environ.get("LECTERN_HOOK_URL", "").rstrip("/")


def main() -> int:
    event = sys.argv[1] if len(sys.argv) > 1 else ""
    try:
        timeout = int(sys.argv[2]) if len(sys.argv) > 2 else 8
    except ValueError:
        timeout = 8
    if not TOKEN or not URL or not event:
        print("{}")
        return 0
    body = sys.stdin.buffer.read()
    try:
        result = subprocess.run(
            ["curl", "-s", "-m", str(timeout), "-X", "POST",
             "-H", "Authorization: Bearer " + TOKEN,
             "-H", "Content-Type: application/json",
             "--data-binary", "@-", URL + "/" + event],
            input=body, timeout=timeout + 2, capture_output=True,
        )
        out = result.stdout.decode("utf-8", "replace").strip()
        print(out if out else "{}")
    except Exception:
        print("{}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
`

CodexHookScript is the fixed, non-templated program every managed hooks.json entry below invokes. Like CodexNotifyScript, it carries no per-session state of its own — LECTERN_HOOK_TOKEN/LECTERN_HOOK_URL arrive as process environment (confirmed reachable: a hook command's subprocess inherits the full codex process environment, no Claude-style allowedEnvVars allowlist needed) — so ONE copy of this file, written once per target, serves every codex session on it; only the environment differs per invocation.

argv[1] is the hook event name, argv[2] its timeout in seconds. The hook body arrives on stdin and is forwarded byte-for-byte as the POST body (never re-encoded, so lectern's ingest sees exactly what codex sent). lectern's JSON response is printed back to stdout verbatim — this is what lets `additionalContext` (awareness) and PermissionRequest's `decision` reach codex, confirmed for real (see this file's package doc). On any failure (no curl, lectern unreachable, timeout) it prints "{}" and always exits 0: a hook that errors or times out must never be mistaken by codex for a request to block the agent's turn or tool call.

View Source
const CodexHookTrustBypassArg = "--dangerously-bypass-hook-trust"

CodexHookTrustBypassArg is the launch flag added for every builtin codex session once CodexHooksInstallCommand has run: see this file's package doc for why bypassing persisted hook trust, rather than reverse-engineering codex's hash cache, is the deliberate choice here.

View Source
const CodexNotifyScript = `#!/usr/bin/env python3
"""lectern codex notify handler — see internal/agentevents/codex_settings.go.

Invoked by codex as ` + "`notify <json>`" + ` on agent-turn-complete.
"""
import json
import os
import subprocess
import sys

TOKEN = os.environ.get("LECTERN_HOOK_TOKEN", "")
URL = os.environ.get("LECTERN_HOOK_URL", "").rstrip("/")


def main() -> int:
    if not TOKEN or not URL:
        return 0
    try:
        payload = json.loads(sys.argv[-1]) if len(sys.argv) > 1 else {}
    except Exception:
        payload = {}
    body = json.dumps({"hook_event_name": "AgentTurnComplete", "codex_notify": payload}).encode()
    try:
        subprocess.run(
            ["curl", "-s", "-m", "5", "-X", "POST",
             "-H", "Authorization: Bearer " + TOKEN,
             "-H", "Content-Type: application/json",
             "--data-binary", "@-", URL + "/AgentTurnComplete"],
            input=body, timeout=6,
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
        )
    except Exception:
        pass
    return 0


if __name__ == "__main__":
    sys.exit(main())
`

CodexNotifyScript is the notify program lectern installs on a codex session's target. It is a fixed script with no per-session templating — everything it needs (LECTERN_HOOK_TOKEN, LECTERN_HOOK_URL) arrives as process environment, exactly like Claude's statusline wrapper — so it is written once per session under ~/.lectern/hooks/<tmux>-codex-notify.py and referenced from the launch command's `-c notify=[...]` override.

Degrades silently on any error: a notify script must never make codex think a turn failed, and lectern being briefly unreachable is not the agent's problem. If curl is missing, subprocess.run raises and is caught.

View Source
const CodexRolloutEnd = "ADK-CODEX-ROLLOUT-END-v1"

CodexRolloutEnd terminates a CodexRolloutTailCommand snapshot, mirroring poll_wire.go's PollEnd.

View Source
const EventAPIRequest = "api_request"

EventAPIRequest is claude_code.api_request's event.name value.

View Source
const OTelOptOutSetting = "otel_telemetry"

OTelOptOutSetting is the settings row that turns OTel env injection off — default on, same "explicit '0' opts out" convention internal/alerts and internal/awareness already use.

Variables

This section is empty.

Functions

func ClaudeSettingsInstallCommand

func ClaudeSettingsInstallCommand(tmuxName, hookURL string, askPermission bool) string

ClaudeSettingsInstallCommand returns a shell command that, run on a session's target (the same executor.Run seam internal/sessions/agents.go's claudeTrust/codexTrust probes use), writes a per-session Claude settings file plus a statusline script under ~/.lectern/hooks/ and prints the settings file's absolute path on stdout — which the caller passes to `claude --settings <path>`.

Per docs/agent-events.md section 2, `--settings` MERGES with the user's own settings rather than replacing them, so this file only ever adds the hooks/statusLine lectern needs; it never touches ~/.claude/settings.json, which is read-only here (to learn an existing statusLine command so this session's wrapper can still run it — see the generated script).

func CodexHooksInstallCommand

func CodexHooksInstallCommand(askPermission bool) string

CodexHooksInstallCommand returns a shell command that, run on a session's target, writes CodexHookScript once to a fixed, shared path (~/.lectern/hooks/lectern-codex-hook.py — not templated per session, see CodexHookScript's doc) and additively merges lectern's hook groups into the real $CODEX_HOME/hooks.json (default ~/.codex/hooks.json), then prints that file's path. askPermission registers PermissionRequest; a later call with askPermission false removes it again, mirroring ClaudeSettingsInstallCommand's "ask" gate. Every other tool's entries and every other top-level key in hooks.json are preserved untouched — see this file's package doc for why that matters on a machine that already has one.

func CodexNotifyInstallCommand

func CodexNotifyInstallCommand(tmuxName string) string

CodexNotifyInstallCommand returns a shell command that writes CodexNotifyScript under ~/.lectern/hooks/<tmux>-codex-notify.py (mode 0700) and prints its absolute path, for use as the second element of a `-c notify=[...]` config override.

The target path is built with shellq.HomePath, not a bare `shellq.Quote("$HOME/"+...)`: Quote's safeWord charset excludes `$`, so quoting a string that already contains "$HOME" text single-quotes the whole thing and disables the expansion — confirmed against a real shell, see HomePath's own doc for the reproduction. That was the actual rendered form here before this fix.

func CodexRolloutTailCommand

func CodexRolloutTailCommand(threadIDs []string) string

CodexRolloutTailCommand builds one shell command that, for every given thread id, locates that session's exact rollout file under ~/.codex/sessions/*/*/*/rollout-*-<id>.jsonl (the year/month/day glob segments are needed because the reader has no other record of which day a session started — only the id, from the AgentTurnComplete notify payload, is exact) and prints its tail, framed the same base64/marker way poll_wire.go's PollCommand frames tmux panes, so one target round trip covers every codex session on it.

func CodexRolloutTailCommandIn added in v2.6.0

func CodexRolloutTailCommandIn(threadIDs []string, homes map[string]string) string

CodexRolloutTailCommandIn is CodexRolloutTailCommand for sessions whose CODEX_HOME is not ~/.codex (a session on another account, docs/accounts.md): homes maps a thread id to its CODEX_HOME.

func IngestOTelLogsForAttempt

func IngestOTelLogsForAttempt(db *store.DB, attemptID int64, body []byte) error

IngestOTelLogsForAttempt applies one OTLP/HTTP JSON logs export to a headless task attempt. api_request events are additive per request, so unlike the metrics path this ADDS onto whatever cost/tokens are already recorded for the attempt rather than replacing them — the two sources still can't double count each other for the reason IngestOTelLogs documents, and a metrics export that lands afterwards simply reports the same cumulative total these adds summed to.

func IngestOTelMetricsForAttempt

func IngestOTelMetricsForAttempt(db *store.DB, attemptID int64, body []byte) error

IngestOTelMetricsForAttempt applies one OTLP/HTTP JSON metrics export to a headless task attempt. Unlike a session, an attempt's process is one-shot and short-lived, so there is no baseline to diff against: the freshest cumulative reading simply replaces whatever was stored before (see store.UpsertOtelAttemptUsage's own doc comment).

func MapEventState

func MapEventState(event, notificationType string) (state string, ok bool)

MapEventState is the mapping table from docs/agent-events.md section 2. ok is false for an event that is accepted but does not itself imply a state change (SessionStart, PreCompact, SubagentStart/Stop, Interrupt, and a Notification whose notification_type is neither of the two known values) — the caller still records that a hook reached the session (hook_seen_at) without touching agent_state.

func NewHookToken

func NewHookToken() (string, error)

NewHookToken generates a session's hook secret. Hex, not base64: it goes straight into a shell-quoted env value and a JSON settings file, and hex needs no quoting consideration either place.

func OTelEnv

func OTelEnv(otelBaseURL, token, resourceKey string, refID int64) map[string]string

OTelEnv builds the environment Claude Code's own OpenTelemetry exporter reads (docs/outcomes.md, https://code.claude.com/docs/en/monitoring-usage): CLAUDE_CODE_ENABLE_TELEMETRY plus OTLP/HTTP JSON metrics+logs exporters pointed at lectern's own receiver (POST otelBaseURL/v1/metrics and otelBaseURL/v1/logs — see internal/api's hookSessionOTel/hookAttemptOTel), authenticated with the same bearer token as the rest of that session's/attempt's hook group so no second secret needs minting. lectern.session_id or lectern.attempt_id rides as a resource attribute purely for a human reading raw OTLP JSON while debugging — routing itself is by URL path and token, never by this attribute, so a caller that drops it is still authenticated correctly.

Only http/json is offered: lectern's receiver is a small JSON decoder (see internal/agentevents/otel.go), not a full OTLP/gRPC or protobuf server, and http/json is one of Claude Code's three documented exporter protocols.

func ParseCodexRolloutSnapshot

func ParseCodexRolloutSnapshot(output string, threadIDs []string) (map[string][]byte, bool)

ParseCodexRolloutSnapshot decodes CodexRolloutTailCommand's output into a per-thread-id tail (raw bytes, possibly nil when no matching file was found). Like ParsePollSnapshot, a short, malformed, or incomplete snapshot is rejected outright rather than partially trusted.

func StatusForState

func StatusForState(state string) (status string, ok bool)

StatusForState maps the new hook-driven agent_state onto the pre-existing sessions.status enum (sessions.StatusRunning etc., defined in package sessions) so surfaces that only know the old column keep working the moment a hook fires, without waiting for the next screen poll. It returns ok=false for a state with no natural old-status equivalent, in which case the caller leaves status untouched.

This never runs from the screen-scrape path — applyPane keeps deriving status the way it always has (docs/agent-events.md section 2). It only gives hook-driven updates a head start; the next poll tick reconciles status from the pane exactly as before, so there is no way for the two to permanently disagree.

func ValidCodexThreadID

func ValidCodexThreadID(s string) bool

ValidCodexThreadID reports whether s is safe to store and later use to locate a rollout file.

func ValidToken

func ValidToken(sessionToken, supplied string) bool

ValidToken reports whether supplied is this session's hook token, compared in constant time. An empty session token (one launched before this feature, or a "discovered" adopted session that was never handed one) never matches anything, including an empty supplied value.

Types

type CodexRateWindow added in v2.6.0

type CodexRateWindow struct {
	UsedPercent   float64 `json:"used_percent"`
	WindowMinutes int     `json:"window_minutes"`
	ResetsAt      int64   `json:"resets_at"`
}

CodexRateWindow is one of codex's usage windows: how full it is, how long it is, and when it resets (unix seconds).

type CodexUsage

type CodexUsage struct {
	Model         string
	ContextTokens int // cumulative tokens counted against the context window
	ContextSize   int // model_context_window
	ContextPct    int // ContextTokens/ContextSize, capped at 100
	InputTokens   int // cumulative, for usage_daily delta booking
	CachedInput   int // cumulative part of InputTokens served from cache
	OutputTokens  int // cumulative, for usage_daily delta booking
	// RateLimits are the account's usage windows as codex last reported them
	// (docs/accounts.md): the same numbers as Claude's statusline rate_limits.
	RateLimits []CodexRateWindow
}

CodexUsage is what the codex rollout reader extracts from a session's rollout JSONL — the closest codex has to Claude's statusline. Cost has no equivalent field here: docs/agent-events.md calls for showing tokens instead of a dollar figure for codex, so there is deliberately no CostUSD.

func ParseCodexRolloutUsage

func ParseCodexRolloutUsage(data []byte) (*CodexUsage, bool)

ParseCodexRolloutUsage scans a (possibly partial — a tailed read may start mid-line) chunk of a rollout JSONL file for the LAST token_count record, codex's running context gauge, and the most recent turn_context's model. A malformed or truncated leading line is simply skipped like any other unrecognised line rather than failing the whole read — the same tolerance IngestStatusline has for a bad statusline body.

type Ingester

type Ingester struct {
	DB  *store.DB
	Bus *bus.Bus
	// Stop, when set, is told about every Stop (or codex AgentTurnComplete)
	// hook that actually changes a session's state — the trigger a session's
	// check command runs on. Nil is a valid, checks-disabled configuration
	// (every test that builds an Ingester by hand predates this field).
	Stop StopListener
	// OnHookEvent, when set, is called synchronously at the end of every
	// IngestEvent — success, no-op (an event that carries no state, like
	// PreCompact), or an unchanged state — with the raw event name and
	// body. This is how internal/alerts (docs/agent-events.md section 3)
	// observes things that never reach the bus as structured session
	// fields: a PreCompact hook's "trigger" and a Stop hook's
	// "last_assistant_message". Kept fast: it must never block or slow a
	// hook response, so a subscriber only ever queues work here.
	OnHookEvent func(sess *store.Session, event string, body []byte, state string, changed bool)
}

Ingester turns hook payloads and statusline snapshots into session state and usage. It owns no HTTP: internal/api's hook handlers resolve the session and its token, then call in here.

func New

func New(db *store.DB, b *bus.Bus) *Ingester

New builds an Ingester.

func (*Ingester) IngestCodexUsage

func (in *Ingester) IngestCodexUsage(s *store.Session, usage *CodexUsage) error

IngestCodexUsage applies one codex rollout usage reading (see codex_rollout.go) to a session — the codex equivalent of IngestStatusline. Codex's total_token_usage is genuinely cumulative for the whole thread (unlike Claude's confusingly-named total_input_tokens, which is a per-request footprint — see the comment on IngestStatusline), so the same "diff against whatever usage_daily already booked" delta math applies unchanged. Codex reports no cost figure, so sessions.cost_usd is left untouched; when the operator has priced the model (or "codex") in the model price table, the token delta's estimated cost is booked into usage_daily (labelled via estimated_usd) so budgets and the Usage page see the spend.

func (*Ingester) IngestEvent

func (in *Ingester) IngestEvent(s *store.Session, event string, body []byte) (state string, changed bool, err error)

IngestEvent applies one hook event to a session and returns the state it landed in (which may be unchanged, or "" if the event carries no state).

Extension point for a later worker: when event is EventPermissionRequest and the session's permission mode is "ask" (docs/agent-events.md section 3), this is where a broker.Create + hold-for-decision belongs, answering with the real allow/deny decision instead of the unconditional `{}` this pass returns. For now every PermissionRequest is recorded as waiting_permission and answered `{}` (Claude/Codex both then fall back to their own terminal approval prompt), so it is safe to ship ahead of that worker.

func (*Ingester) IngestOTelLogs

func (in *Ingester) IngestOTelLogs(s *store.Session, body []byte) error

IngestOTelLogs applies one Claude Code OTLP/HTTP JSON logs export to a session. Today this only marks the session OTel-active (a claude_code. api_request event proves the exporter is live even before the next 60s metrics tick) and, when a log record carried its own cost/token figures (see OTelAPIRequest's doc comment), books them the same delta way IngestOTelMetrics does for the periodic metric — never both for the same dollar, since api_request cost is additive per discrete request while cost.usage is cumulative, and the two are reconciled the same way any two deltas from different sources would be: whichever arrives first for a given slice of spend books it, and the other's next cumulative reading simply has a smaller delta left over.

func (*Ingester) IngestOTelMetrics

func (in *Ingester) IngestOTelMetrics(s *store.Session, body []byte) error

IngestOTelMetrics applies one Claude Code OTLP/HTTP JSON metrics export to a session (see docs/outcomes.md). Like IngestStatusline, a malformed body degrades to "touch hook_seen_at" rather than erroring: the OTel SDK's own exporter treats a non-2xx as a delivery failure and retries/backs off, which is worse than silently accepting a body lectern could not parse.

cost.usage/lines_of_code.count are genuinely cumulative for the session's whole process lifetime (same shape as Claude's statusline cost.total_cost_usd — see IngestStatusline's comment), so the delta math is the same: diff against the session's own previously-stored value. Once this ever succeeds for a session, otel_active_at is set and stays set — see IngestStatusline's own guard for why that matters.

func (*Ingester) IngestStatusline

func (in *Ingester) IngestStatusline(s *store.Session, body []byte) error

IngestStatusline applies one Claude statusline snapshot: latest values onto the session row, and the DELTA since the session's previous snapshot into today's usage_daily bucket, so repeated statuslines (roughly one per render tick) never double-count the cumulative totals Claude reports.

A malformed body degrades to "touch hook_seen_at and stop" rather than erroring — the statusline script's curl is fire-and-forget from the target's shell prompt, with nothing there to look at a non-2xx response.

type OTelAPIRequest

type OTelAPIRequest struct {
	Model        string
	CostUSD      float64
	InputTokens  int64
	OutputTokens int64
}

OTelAPIRequest is one claude_code.api_request log record's attributes that lectern reads. cost_usd/input_tokens/output_tokens are not documented as standard api_request attributes today, but are read opportunistically (some Claude Code builds/proxies add them) as a secondary cost source — see docs/outcomes.md's precedence note. When absent, CostUSD is 0 and the caller falls back to the cost.usage metric.

type OTelLogsSummary

type OTelLogsSummary struct {
	APIRequests  int
	CostUSD      float64
	InputTokens  int64
	OutputTokens int64
	Model        string
}

OTelLogsSummary is everything internal/outcomes needs out of one OTLP logs export: how many api_request events it carried, and their combined cost/ tokens where the log recorded them.

func ParseOTLPLogs

func ParseOTLPLogs(body []byte) (*OTelLogsSummary, error)

ParseOTLPLogs decodes one OTLP/HTTP JSON logs export request body and summarises its claude_code.api_request events (event.name == "api_request" on the record's attributes — Claude Code puts the event name in an attribute, not in log body text). Every other event (user_prompt/assistant_response/tool_result/tool_decision/...) is ignored: none of them carry cost or outcome information lectern uses today.

type OTelMetricsSummary

type OTelMetricsSummary struct {
	CostUSD      float64
	InputTokens  int64
	OutputTokens int64
	LinesAdded   int64
	LinesRemoved int64
	PullRequests int64
	Commits      int64
	// Model is the most recently seen model attribute across every data
	// point in this payload — good enough for "what was this session/attempt
	// using", not a per-model breakdown (usage_daily already buckets by
	// model on the DELTA this produces, not on this summary).
	Model string
}

OTelMetricsSummary is everything internal/outcomes needs out of one OTLP metrics export. Every *USD/*Tokens/*Lines/*PullRequests/*Commits field is the SUM, across every data point this one payload carried (i.e. across every distinct attribute combination — typically one per model), of that metric's value — which is the correct way to fold multiple cumulative series into one running total. See IngestOTelMetrics for how the caller turns that running total into a delta.

func ParseOTLPMetrics

func ParseOTLPMetrics(body []byte) (*OTelMetricsSummary, error)

ParseOTLPMetrics decodes one OTLP/HTTP JSON metrics export request body. Unknown metric names are ignored — this reads exactly the five Claude Code metrics named above and nothing else, so a future Claude Code adding new metrics never breaks ingestion.

type StatuslinePayload

type StatuslinePayload struct {
	SessionID string `json:"session_id"`
	Model     struct {
		ID          string `json:"id"`
		DisplayName string `json:"display_name"`
	} `json:"model"`
	Cost struct {
		TotalCostUSD      float64 `json:"total_cost_usd"`
		TotalLinesAdded   int     `json:"total_lines_added"`
		TotalLinesRemoved int     `json:"total_lines_removed"`
	} `json:"cost"`
	ContextWindow struct {
		// TotalInputTokens/TotalOutputTokens, despite the "total_" prefix, are
		// NOT lifetime-cumulative: in the reference fixture
		// total_input_tokens (36451) exactly equals current_usage's
		// input_tokens+cache_creation_input_tokens+cache_read_input_tokens
		// (2+13590+22859), and total_output_tokens equals current_usage's
		// output_tokens. Both describe the LAST request's token footprint —
		// which is also what used_percentage is computed from — not a
		// running sum across the conversation. See IngestStatusline for how
		// this is still turned into a usage_daily delta.
		TotalInputTokens  int `json:"total_input_tokens"`
		TotalOutputTokens int `json:"total_output_tokens"`
		ContextWindowSize int `json:"context_window_size"`
		UsedPercentage    int `json:"used_percentage"`
	} `json:"context_window"`
	RateLimits struct {
		FiveHour struct {
			UsedPercentage int     `json:"used_percentage"`
			ResetsAt       float64 `json:"resets_at"`
		} `json:"five_hour"`
		SevenDay struct {
			UsedPercentage int     `json:"used_percentage"`
			ResetsAt       float64 `json:"resets_at"`
		} `json:"seven_day"`
	} `json:"rate_limits"`
}

StatuslinePayload is Claude Code's statusline JSON, as captured live from 2.1.281 in /mnt/bulk/lectern-events-ref/claude-statusline.json. Only the fields lectern uses are declared; everything else is ignored rather than rejected, since a newer Claude Code is free to add fields.

func ParseStatusline

func ParseStatusline(body []byte) (*StatuslinePayload, error)

ParseStatusline decodes a statusline payload. A malformed body is not fatal to the caller — see IngestStatusline, which degrades to "touch hook_seen_at only" rather than erroring the target's background curl.

type StopListener

type StopListener interface {
	OnAgentStop(sessionID int64)
}

StopListener is how the session checks runner (internal/checks) learns that an agent turn ended, without this package needing to import checks — *checks.Runner satisfies this interface structurally, wired up in internal/app. See docs/agent-events.md section 4.

Jump to

Keyboard shortcuts

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