Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: Add support for monitoring Coding agents usage (#1207)

Aman Agarwald4086808e085
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
new file mode 100644
index 00000000..3d8a124f
--- /dev/null
+++ b/.claude-plugin/marketplace.json
@@ -0,0 +1,17 @@
+{
+ "name": "openlit",
+ "owner": {
+ "name": "OpenLit",
+ "email": "[email protected]"
+ },
+ "plugins": [
+ {
+ "name": "openlit-cc",
+ "description": "OpenTelemetry-native session, tool, and edit-decision capture for Claude Code.",
+ "author": {
+ "name": "OpenLit"
+ },
+ "source": "./plugins/claude-code"
+ }
+ ]
+}
diff --git a/.cursor/rules/coding-agents-convention.mdc b/.cursor/rules/coding-agents-convention.mdc
new file mode 100644
index 00000000..15349181
--- /dev/null
+++ b/.cursor/rules/coding-agents-convention.mdc
@@ -0,0 +1,435 @@
+---
+description: Strict attribute and naming convention every coding-agent vendor must follow. Defines the canonical schema (the `coding_agent.*` + `gen_ai.*` keys we own), the per-vendor inbound mappings (Cursor → canonical, Claude Code native OTel → canonical, etc.), the dual-path dedupe rule when a vendor ships its own telemetry AND we ship hook spans for the same session, and the data-type / unit / enum-value contract. Read this before writing or reviewing any adapter, query, materializer change, or collector processor.
+globs: cli/internal/coding/**/*.go,cli/internal/otlp/**/*.go,sdk/go/semconv/coding_agent.go,sdk/go/semconv/genai.go,src/client/src/lib/platform/coding-agents/**/*.ts,src/client/src/lib/platform/agents/materialize.ts,plugins/**/hooks.json,assets/otel-collector*.yaml
+alwaysApply: false
+---
+
+# Coding-Agents Telemetry Convention
+
+This is the **strict** contract between every coding-agent vendor and OpenLit. Every adapter, every native-telemetry mapping, every query has to match it exactly. Drift in either direction (renaming an attribute, switching units, adding ad-hoc vendor-namespaced keys) breaks the `/coding-agents` and `/agents` views in subtle, hard-to-diagnose ways. When in doubt, prefer this document over what any individual vendor's docs claim.
+
+The companion authoring rule is `coding-agents-hook.mdc` (failure modes + checklist). This rule is the **schema**.
+
+---
+
+## 1. Canonical schema (single source of truth)
+
+Everything OpenLit reads or rolls up speaks one of two namespaces:
+
+- **`coding_agent.*`** — OpenLit-owned, defined in `sdk/go/semconv/coding_agent.go` (Go) and `cli/gen/semconv.ts` (TS mirror). Specific to coding agents — no other product surface uses these.
+- **`gen_ai.*`** — OpenTelemetry GenAI semantic conventions (with a few OpenLit-stamped additions in `sdk/go/semconv/genai.go`). Shared with the SDK / LLM observability surface.
+
+**Hard rules:**
+
+1. Adapters MUST stamp `coding_agent.session.id` on every span. No exceptions.
+2. Adapters MUST stamp `coding_agent.client` (vendor identifier) on every span. Allowed values: `cursor`, `claude-code`, `codex`, `windsurf`. Add new values to `sdk/go/semconv/coding_agent.go` AND `src/client/src/types/agents.ts` AND re-run `go generate`.
+3. `gen_ai.system` MUST be the LLM provider, not the agent vendor: `anthropic`, `openai`, `google`, `xai`, `mistral`. Use the `inferProvider(model, vendor)` helper.
+4. Numeric attributes are emitted as numbers, NEVER as strings. Tokens are `int64`. Cost is `float64` in USD. Duration is `int64` in milliseconds.
+5. Timestamps are RFC3339-with-nanos when stamped as strings, or the OTel span's intrinsic start/end when stamped as span time. NEVER unix seconds, never milliseconds-since-epoch.
+6. Enums (capture mode, outcome, edit decision, classification) MUST be exactly one of the defined values. Use the `semconv.CodingAgent*` constants — never inline a literal.
+
+## 2. Attribute matrix — what every adapter MUST set
+
+These keys MUST land on every adapter's spans. Where the value is unknown, leave the key off — DO NOT stamp `""` or `"unknown"` (the only exception is `coding_agent.user.classification = "unknown"`, which is a deliberate fallback).
+
+### Resource attributes (every span the process emits)
+
+| Attribute | Source | Required | Example |
+| -- | -- | -- | -- |
+| `coding_agent.client` | Vendor adapter | ✅ | `claude-code` |
+| `coding_agent.session.id` | Vendor payload | ✅ | UUID string |
+| `coding_agent.agent.parent_id` | Subagent linkage | When subagent | UUID string |
+| `coding_agent.content_capture_mode` | CLI config | ✅ | `minimal` / `metadata_only` / `full` |
+| `coding_agent.hook.cli.version` | CLI build | ✅ | `0.5.3` |
+| `coding_agent.signal_source` | Adapter (see §6) | ✅ | `hook` / `native` |
+| `telemetry.distro.name` | CLI emit layer | ✅ | `openlit-cli` |
+| `telemetry.distro.version` | CLI emit layer | ✅ | `0.5.3` |
+| `code.cwd` | Session probe + `os.Getwd()` fallback | ✅ | `/home/me/repo` |
+| `vcs.repository.url.full` | `git.Snapshot(cwd)` | When repo | `https://github.com/org/repo` |
+| `vcs.ref.head.name` | `git.Snapshot(cwd)` | When repo | `main` |
+| `gen_ai.user.name` | Vendor payload or local OS user | ✅ | `[email protected]` |
+| `gen_ai.request.user` | Mirror of `gen_ai.user.name` | ✅ | Same as above |
+| `gen_ai.conversation.id` | Vendor's chat-thread id | When known | UUID string |
+| `terminal.type` | `resolveTerminalType()` | When known | `iTerm.app` / `vscode` / `tmux` |
+| `host.name` | `os.Hostname()` | ✅ | `alice-mbp` |
+| `service.name` | Vendor identifier | ✅ | `claude-code` |
+| `service.version` | CLI version | ✅ | `0.5.3` |
+| `telemetry.sdk.name` | openlit-go default | ✅ | `opentelemetry` |
+
+### Span attributes per span type
+
+**Session-root span** (`coding_agent.session`, only on session END):
+
+| Attribute | Required | Notes |
+| -- | -- | -- |
+| `coding_agent.session.outcome` | ✅ | One of the `CodingAgentSessionOutcome*` constants |
+| `coding_agent.session.duration_ms` | ✅ | `int64`, wall-clock |
+| `coding_agent.session.cost_usd` | When known | `float64`, USD |
+| `coding_agent.session.tool_call_count` | ✅ | `int64` |
+| `coding_agent.session.subagent_count` | When subagents | `int64` |
+| `coding_agent.session.lines.added` | When edits captured | `int64`. Sum of `coding_agent.edit.lines.added` across the session's edit-decision spans (any decision). |
+| `coding_agent.session.lines.removed` | When edits captured | `int64`. Sum of `coding_agent.edit.lines.removed` across edit-decision spans. |
+| `coding_agent.session.lines.accepted` | When edits captured | `int64`. Sum of `coding_agent.edit.lines.added` for edit-decision spans where `coding_agent.edit.decision IN ('accept', 'auto_accepted')`. |
+| `coding_agent.session.lines.rejected` | When edits captured | `int64`. Same shape as `lines.accepted` but for `decision = 'reject'`. |
+| `coding_agent.session.edit.accept_count` | When edits captured | `int64`. Count of edit-decision spans with decision = accept / auto_accepted. |
+| `coding_agent.session.edit.reject_count` | When edits captured | `int64`. Count of edit-decision spans with decision = reject. |
+| `coding_agent.session.commit_count` | When commits detected | `int64`. Count of `coding_agent.git.commit` spans the adapter emitted for this session. |
+| `coding_agent.session.pr_count` | When PRs detected | `int64`. Count of `coding_agent.git.pull_request` spans. |
+| `gen_ai.usage.input_tokens` | When known | `int64` |
+| `gen_ai.usage.output_tokens` | When known | `int64` |
+| `gen_ai.usage.total_tokens` | When known | `int64` |
+| `gen_ai.usage.cache.read_input_tokens` | When known | `int64` |
+| `gen_ai.usage.cache.creation_input_tokens` | When known | `int64` |
+| `gen_ai.request.model` | When known | Vendor model string |
+| `coding_agent.user.classification` | ✅ | `work` / `personal` / `unknown` |
+| `coding_agent.user.classification.reason` | ✅ | Human-readable reason |
+| `coding_agent.policy.permission_mode` | When set | Vendor permission mode |
+| `coding_agent.vcs.dirty` | When repo present | Boolean |
+
+The eight `coding_agent.session.{lines,edit,commit,pr}*` rollup
+attributes are an additive fast path — they let the per-session
+`listSessions` query render code-impact without scanning every
+`coding_agent.edit.decision` / `coding_agent.git.*` child span.
+For sessions where the rollup is missing (Codex never emits a
+`SessionEnd`; in-flight CC / Cursor sessions also lack the rollup),
+the query layer falls back to per-event aggregation with the
+`greatest(rollup, sum)` pattern documented in `queries.ts`.
+
+**LLM turn span** (`coding_agent.llm.turn`):
+
+| Attribute | Required | Notes |
+| -- | -- | -- |
+| `gen_ai.operation.name` | ✅ | `chat` |
+| `gen_ai.system` | ✅ | Provider — `anthropic`, `openai`, ... |
+| `gen_ai.request.model` | ✅ | Model string |
+| `gen_ai.response.model` | When known | Often equal to request |
+| `gen_ai.usage.input_tokens` | When known | `int64` |
+| `gen_ai.usage.output_tokens` | When known | `int64` |
+| `gen_ai.usage.total_tokens` | When known | `int64` |
+| `gen_ai.usage.cost` | When known | `float64`, USD |
+| `gen_ai.response.id` | When known | Vendor request id |
+| `gen_ai.response.finish_reasons` | When known | String array — `[end_turn]`, `[tool_use]`, etc. |
+| `gen_ai.input.messages` | Capture-mode `full` | JSON-stringified messages |
+| `gen_ai.output.messages` | Capture-mode `full` | JSON-stringified messages |
+| `coding_agent.llm.thought.text` | Capture-mode `full` | Reasoning / extended-thinking text |
+| `coding_agent.llm.thought.duration_ms` | When known | `int64` |
+| `coding_agent.llm.turn.kind` | ✅ | `prompt` / `response` / `thought` |
+
+**Tool call span** (`coding_agent.tool.call`):
+
+| Attribute | Required | Notes |
+| -- | -- | -- |
+| `gen_ai.tool.name` | ✅ | Vendor's tool name |
+| `gen_ai.tool.call.id` | ✅ | Vendor's tool_use_id |
+| `coding_agent.tool.duration_ms` | ✅ | `int64` |
+| `coding_agent.tool.errored` | ✅ | Boolean |
+| `coding_agent.tool.error_message` | When errored, gated | String — only in `full` mode |
+| `coding_agent.tool.iteration` | When known | `int64`, 1-based |
+| `coding_agent.tool.group.id` | When known | Vendor's tool-group id |
+| `coding_agent.tool.triggering_llm_request_id` | When known | LLM turn id that issued the call |
+| `coding_agent.mcp.server.name` | MCP tools only | String |
+| `coding_agent.mcp.scope` | MCP tools only | `user` / `project` / `local` |
+| `coding_agent.mcp.transport` | MCP tools only | `stdio` / `sse` / `http` |
+| `coding_agent.tool.sandboxed` | When known | Boolean |
+| `coding_agent.tool.command` | Shell tools, gated | `metadata_only`+ strips args, `full` keeps full string |
+| `gen_ai.tool.call.arguments` | Capture-mode `full` | JSON-stringified args |
+| `gen_ai.tool.call.result` | Capture-mode `full` | JSON-stringified result |
+
+**Edit decision span** (`coding_agent.edit.decision`):
+
+| Attribute | Required | Notes |
+| -- | -- | -- |
+| `coding_agent.edit.decision` | ✅ | `accept` / `reject` / `auto_accept` / `revert` |
+| `coding_agent.edit.decision.source` | ✅ | `user_interactive` / `policy` / `hook` |
+| `coding_agent.edit.tool.name` | ✅ | Vendor's edit tool name (Edit, Write, MultiEdit, …) |
+| `coding_agent.edit.language` | When known | Programming language guess |
+| `coding_agent.edit.lines.added` | When known | `int64` |
+| `coding_agent.edit.lines.removed` | When known | `int64` |
+| `code.file.path` | When known | Repo-relative path |
+
+**Subagent span** (`coding_agent.subagent`):
+
+| Attribute | Required | Notes |
+| -- | -- | -- |
+| `coding_agent.subagent.type` | ✅ | Vendor's subagent type label |
+| `coding_agent.agent.parent_id` | ✅ | Parent chat id (also as resource attr) |
+| `gen_ai.tool.call.id` | When spawned by Task tool | Tool use id that spawned it |
+
+**Git commit span** (`coding_agent.git.commit`):
+
+Detected by parsing `git commit` invocations out of the Bash /
+shell / local_shell tool's command + stdout (see
+`cli/internal/coding/detect/detect.go`).
+
+| Attribute | Required | Notes |
+| -- | -- | -- |
+| `coding_agent.git.commit.sha` | When stdout has it | Hex SHA from `git commit` stdout. Gated by capture mode (stripped in `metadata_only`). |
+| `coding_agent.git.commit.message` | When command has it | First line of `-m '…'`. Gated. |
+| `coding_agent.tool.name` | ✅ | Originating tool — `Bash`, `local_shell`, `shell`. |
+| `coding_agent.tool.working_dir` | When known | Repo cwd. |
+
+**Git pull-request span** (`coding_agent.git.pull_request`):
+
+Detected by parsing `gh pr create` / `gh pr new` invocations.
+
+| Attribute | Required | Notes |
+| -- | -- | -- |
+| `coding_agent.git.pr.url` | When stdout has it | PR URL from `gh pr` stdout. Gated. |
+| `coding_agent.git.pr.number` | When URL has it | Numeric ID parsed out of the URL. |
+| `coding_agent.git.pr.title` | When command has it | `--title '…'`. Gated. |
+| `coding_agent.tool.name` | ✅ | Originating tool — `Bash`, `local_shell`, `shell`. |
+| `coding_agent.tool.working_dir` | When known | Repo cwd. |
+
+## 3. Inbound mapping — Cursor → canonical
+
+Cursor sends payloads to our hook subcommand; we own the mapping. For full reference see `cli/internal/coding/hook/cursor/handle.go`.
+
+| Cursor payload key | Canonical attribute | Notes |
+| -- | -- | -- |
+| `session_id` | `coding_agent.session.id` | |
+| `conversation_id` | `gen_ai.conversation.id` | |
+| `parent_conversation_id` | `coding_agent.agent.parent_id` | resource attribute |
+| `user_email` | `gen_ai.user.name` + `gen_ai.request.user` | resource attribute, cached |
+| `cwd` / `workspace_roots[0]` | `code.cwd` | resource attribute, cached |
+| `composer_mode` | `coding_agent.policy.permission_mode` | resource attribute |
+| `model` | `gen_ai.request.model` | |
+| `cursor_version` | `coding_agent.client.version` | not always present |
+| `is_background_agent` / `is_parallel_worker` | `coding_agent.session.is_subagent` | boolean string |
+| `prompt` | `gen_ai.input.messages` | full mode only |
+| `text` (assistant response) | `gen_ai.output.messages` | full mode only |
+| `text` (thought) | `coding_agent.llm.thought.text` | full mode only |
+| `duration_ms` | `coding_agent.llm.thought.duration_ms` | for thoughts |
+| `tool_name` | `gen_ai.tool.name` | |
+| `tool_use_id` | `gen_ai.tool.call.id` | |
+| `tool_input` | `gen_ai.tool.call.arguments` | full mode only |
+| `tool_response` | `gen_ai.tool.call.result` | full mode only |
+| `attachments[].file_path` | `coding_agent.llm.turn.attachment.paths` | array |
+
+## 4. Inbound mapping — Claude Code → canonical
+
+Claude Code has **two telemetry paths**:
+
+- **Path A (Hook)** — our CLI plugin sits in `~/.claude/plugins/openlit-cc/` and is invoked on every PreToolUse / PostToolUse / SessionStart / SessionEnd / UserPromptSubmit / Stop / SubagentStop hook event. We emit `coding_agent.*` spans the same way we do for Cursor.
+- **Path B (Native)** — Claude Code's `CLAUDE_CODE_ENABLE_TELEMETRY=1` makes Claude Code itself emit OTel metrics + events + (with `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`) spans, all under `claude_code.*` and `service.name=claude-code`.
+
+OpenLit accepts both. The query layer coalesces. The hard rule on attribute mapping:
+
+### Path A: hook adapter (`cli/internal/coding/hook/claudecode/handle.go`)
+
+| Claude Code hook payload key | Canonical attribute | Notes |
+| -- | -- | -- |
+| `session_id` | `coding_agent.session.id` | |
+| `transcript_path` | `claude_code.transcript.path` (extras) | so we can re-tail in the UI later |
+| `cwd` | `code.cwd` | resource attribute, cached |
+| `hook_event_name` | `coding_agent.hook.event` | |
+| `permission_mode` | `coding_agent.policy.permission_mode` | resource attribute |
+| `tool_name` | `gen_ai.tool.name` | |
+| `tool_use_id` | `gen_ai.tool.call.id` | |
+| `tool_input` | `gen_ai.tool.call.arguments` | full mode only |
+| `tool_response` | `gen_ai.tool.call.result` | full mode only |
+| `source` (SessionStart) | `claude_code.session.source` (extras) | `startup` / `resume` / `continue` |
+| `reason` (SessionEnd) | maps to outcome enum (see §7) | |
+| Transcript tail (last N KB) | session token + cost totals | bounded by `tailfile.Tail` |
+
+The hook adapter MUST stamp `coding_agent.signal_source = "hook"` on every span it emits.
+
+### Path B: native Claude Code telemetry
+
+Claude Code emits its own OTel signals with `service.name = "claude-code"`. We accept it raw. The query layer coalesces both schemas. For symmetry, the canonical equivalents are:
+
+| Claude Code native attribute | Canonical attribute | Notes |
+| -- | -- | -- |
+| `session.id` | `coding_agent.session.id` | also: `OTEL_METRICS_INCLUDE_SESSION_ID=1` |
+| `app.version` | `coding_agent.client.version` | enable with `OTEL_METRICS_INCLUDE_VERSION=1` |
+| `user.email` | `gen_ai.user.name` + `gen_ai.request.user` | resource-level |
+| `user.account_uuid` | not mapped — kept as Anthropic identifier | |
+| `organization.id` | mapped to `gen_ai.organization.id` if set | for org filtering |
+| `terminal.type` | `terminal.type` | already aligned |
+| `model` (cost metric) | `gen_ai.request.model` | |
+| `claude_code.cost.usage` (metric) | `coding_agent.session.cost_usd` (on session span) | metric-to-attribute mapped at query time |
+| `claude_code.token.usage` (metric, by `type`) | `gen_ai.usage.input_tokens` / `output_tokens` / `cache.read_input_tokens` / `cache.creation_input_tokens` | |
+| `claude_code.session.count` (metric) | session count rollup | derived |
+| `claude_code.lines_of_code.count` (metric) | `coding_agent.edit.lines.added` / `removed` | summed per session |
+| `claude_code.commit.count` (metric) | derived UI counter | no canonical attr — `gen_ai.user.commit_count`? Out of scope for v1. |
+| `claude_code.pull_request.count` (metric) | derived UI counter | same |
+| `claude_code.active_time.total` (metric) | `coding_agent.session.active_time_seconds` (future) | not yet wired |
+| `claude_code.user_prompt` event | `coding_agent.llm.turn` span, `kind=prompt` | |
+| `claude_code.tool_result` event | `coding_agent.tool.call` span | |
+| `claude_code.api_request` event | `coding_agent.llm.turn` span, `kind=response` | carries cost/tokens |
+| `claude_code.api_error` event | `coding_agent.llm.turn` span, `errored=true` | |
+| `claude_code.tool_decision` event | `coding_agent.edit.decision` span when tool ∈ {Edit, Write, NotebookEdit, MultiEdit} | otherwise dropped |
+| `claude_code.permission_mode_changed` event | `coding_agent.session.permission_mode_changed` event | |
+| `claude_code.compaction` event | `coding_agent.session.loop.compact` event | |
+| `claude_code.api_retries_exhausted` event | `coding_agent.llm.turn.retry_exhausted` event | |
+| `claude_code.mcp_server_connection` event | `coding_agent.mcp.connection` event | |
+| `claude_code.skill_activated` event | `coding_agent.skill.activated` event | |
+| `claude_code.plugin_loaded` / `plugin_installed` event | dropped at v1 | not modelled |
+| `claude_code.auth` event | dropped at v1 | not relevant to coding-agent analytics |
+| `claude_code.feedback_survey` event | dropped at v1 | |
+| `claude_code.internal_error` event | dropped at v1 | not user-actionable |
+
+Native spans (when traces beta is on) are accepted as-is and joined into our model via the **inbound coalesce in the query layer** (§5). We do NOT rewrite spans at the collector.
+
+The native path's `signal_source` is `native`. We infer this in the query layer:
+
+```sql
+multiIf(
+ SpanAttributes['coding_agent.signal_source'] = 'hook', 'hook',
+ ResourceAttributes['coding_agent.signal_source'] = 'hook', 'hook',
+ SpanName LIKE 'claude_code.%' OR ResourceAttributes['service.name'] = 'claude-code', 'native',
+ ResourceAttributes['service.name'] = 'cursor' AND mapContains(ResourceAttributes, 'coding_agent.session.id'), 'hook',
+ ''
+) AS signal_source
+```
+
+## 5. Query-layer coalesce — the dual-path rule
+
+When both paths are active for the same Claude Code session, we get two writers landing telemetry under the same `session.id`. We dedupe at read time:
+
+### Session-level rollup (cost, tokens, model)
+
+```text
+authoritative_cost = coalesce(
+ native sum(claude_code.cost.usage),
+ hook session.cost_usd -- from transcript-tail estimate
+)
+
+authoritative_tokens = coalesce(
+ native sum(claude_code.token.usage),
+ hook session.{input,output}_tokens
+)
+
+model = coalesce(
+ native gen_ai.request.model (from claude_code.api_request),
+ hook gen_ai.request.model (from transcript tail)
+)
+```
+
+Native always wins when present. Anthropic counts tokens authoritatively from the API response; our hook estimates from a bounded transcript tail. Both estimates may exist for the same session — `coalesce(native, hook)` picks the truthful one.
+
+### Identity (user, cwd, repo)
+
+Hook always wins. The native path doesn't see the developer's repo or cwd; it only sees what Claude Code chose to expose. Our hook stamps `code.cwd`, `vcs.repository.url.full`, `vcs.ref.head.name` as resource attributes from `git.Snapshot(cwd)`.
+
+### Tool calls
+
+Coalesce by `gen_ai.tool.call.id`:
+
+- If both paths emitted for the same tool call: keep the **native** span (it has authoritative duration, retry count, MCP scope) but enrich it with `code.cwd` + `vcs.*` from the hook session's resource bundle.
+- If only one side emitted: keep that one as-is.
+
+### Edit decisions
+
+Hook always wins — the hook sees the actual file diff context; native only sees the decision and `language`.
+
+### Anti-double-count rule
+
+`session_count`, `tool_call_count`, and `subagent_count` are rolled up **per `session.id`**, never per span. As long as the chat_id rollup folds both paths into the same `chat_id`, we don't double-count. The materializer's discovery query (`discoverCodingAgents`) already does this — confirm with:
+
+```sql
+SELECT
+ coalesce(
+ nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),
+ nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),
+ SpanAttributes['coding_agent.session.id'],
+ SpanAttributes['session.id'] -- Claude Code native
+ ) AS chat_id,
+ count() AS spans, uniqExact(coalesce(...)) AS distinct_sessions
+FROM otel_traces
+WHERE Timestamp >= now() - INTERVAL 24 HOUR
+GROUP BY chat_id;
+```
+
+If `distinct_sessions > 1` for one `chat_id`, we have a dedupe leak. Fix by widening the coalesce in `CHAT_ID_EXPR`.
+
+### Is coalesce good enough at scale?
+
+Honest answer:
+
+- Under ~1M spans/day per tenant: coalesce in queries is fine. ClickHouse evaluates the per-row coalesce in a few milliseconds; the query bottleneck is usually the wider session scan, not the attribute lookup.
+- Over ~1M spans/day per tenant: we want a materialized view (`coding_agent_sessions`) that normalizes `claude_code.*` and `coding_agent.*` into one canonical row at ingest time. The view exists as a comment marker in `queries.ts` (the E1 deferral note). When we ship it, the change is single-file: point `OTEL_TRACES_TABLE` at the MV; the chat-id rollup logic stays the same.
+
+Until then, every new attribute MUST be added to the coalesce expression in `queries.ts` so reads still work for both paths.
+
+## 6. The `coding_agent.signal_source` marker
+
+Every span MUST carry this attribute (resource-level, set by the adapter or inferred from `service.name` at query time). Values:
+
+| Value | When |
+| -- | -- |
+| `hook` | OpenLit CLI emitted this span from a vendor hook event |
+| `native` | The vendor's own OTel exporter emitted this span (e.g. Claude Code with `CLAUDE_CODE_ENABLE_TELEMETRY=1`) |
+| `sdk` | A regular OpenLit Go/Python SDK process (NOT a coding agent) |
+
+Adapters MUST stamp `hook` explicitly. The query layer infers `native` from `service.name = 'claude-code'` AND absence of `coding_agent.signal_source`. The materializer's SDK discovery excludes anything that isn't `sdk` (a positive value of `hook` or `native` keeps the row off the SDK side).
+
+## 7. Outcome enum mapping
+
+Both vendors map onto the same six-value enum from `sdk/go/semconv/coding_agent.go`:
+
+| Outcome | When (Cursor) | When (Claude Code hook) | When (Claude Code native) |
+| -- | -- | -- | -- |
+| `completed` | `outcome=completed` on sessionEnd | n/a (no equivalent signal) | n/a |
+| `merged` | (no signal yet) | (no signal yet) | (no signal yet) |
+| `committed` | (no signal yet) | (no signal yet) | (no signal yet) |
+| `abandoned_no_change` | `outcome=abandoned` AND `!vcs.dirty` | SessionEnd `reason in [exit, logout]` AND `!vcs.dirty` | SessionEnd metric AND no recent commit AND clean tree |
+| `abandoned_with_change` | `outcome=abandoned` AND `vcs.dirty` | SessionEnd `reason in [exit, logout]` AND `vcs.dirty` | SessionEnd metric AND dirty tree |
+| `cancelled` | `outcome=cancelled` | SessionEnd `reason=clear` | (no signal yet) |
+
+Never invent a new outcome value. Never leave outcome empty on a session-root span.
+
+## 8. Capture-mode contract
+
+Three modes apply identically across vendors. The matrix in `coding-agents-hook.mdc` §4 governs which attributes are allowed in each mode. Vendors do not get to widen capture beyond the global setting.
+
+Special note on **bodies**:
+
+- `gen_ai.input.messages` / `gen_ai.output.messages` / `gen_ai.tool.call.arguments` / `gen_ai.tool.call.result` / `coding_agent.llm.thought.text` / `coding_agent.tool.command` (full command) are body-bearing. They MUST be gated by `bodyAllowed(mode)` from `cli/internal/otlp/attrs.go`. Adapters that bypass this gate are bugs.
+
+When Claude Code is configured to send native `OTEL_LOG_RAW_API_BODIES`, those bodies arrive under `claude_code.api_request_body.body` / `claude_code.api_response_body.body`. The query layer drops them in `minimal` and `metadata_only` modes via a `WHERE` filter — we trust the deployer's CLI config over what the vendor's native exporter chose to send.
+
+## 9. Identity / privacy guardrails
+
+These guardrails are absolute. No vendor adapter and no native-telemetry mapping may relax them.
+
+1. **Cohort floor**. Per-user breakdowns suppress users with fewer than `COHORT_K_FLOOR` (default 5) sessions in the working window, unless the viewer is an admin. Apply this at query time in `queries.ts`, NEVER in the materializer.
+2. **Email visibility**. `gen_ai.user.name` is the developer's email when OAuth is configured. It MUST be queryable for admins and MUST be masked behind the cohort floor for non-admins.
+3. **Dispute trail**. Classification labels can be disputed via `POST /api/coding-agents/classification/dispute`. Disputed sessions are flagged but not deleted. Never re-classify a disputed session automatically — defer to the human reviewer.
+4. **Body retention**. When `OPENLIT_CODING_CONTENT_CAPTURE != "full"`, no prompt body / tool result / file diff may land in `otel_traces`. The collector does not redact post-hoc; the adapter MUST gate at emit time.
+5. **Cross-account leakage**. The `whereScope` helper in `queries.ts` enforces `organization.id` matching when `OPENLIT_REQUIRE_ORG_FILTER` is set. New queries MUST go through `whereScope`.
+
+## 10. Adding a new vendor (worked example: opencode)
+
+If we add OpenCode (or any other vendor):
+
+1. **semconv** — add the vendor identifier to `sdk/go/semconv/coding_agent.go`'s vendor list AND to `src/client/src/types/agents.ts`'s `CodingAgentVendor` union. Run `go generate ./cli/...` to regenerate `cli/gen/semconv.ts`.
+2. **Adapter** — create `cli/internal/coding/hook/opencode/handle.go`. Mirror the structure of `cursor/handle.go` or `claudecode/handle.go`. Map every payload key to the canonical attribute matrix in §2 — DO NOT introduce a new `opencode.*` namespace for facts that already have a canonical key.
+3. **`peekContext`** — `cli/internal/coding/hook/hook.go`. Add the vendor's payload key names to `pickString`. The function MUST resolve `session_id`, `user`, `cwd`, `permission_mode`, `model`, and (when applicable) `parent_conversation_id` from this vendor's payload format.
+4. **Plugin manifest** — `plugins/opencode/`. Mirror `plugins/cursor/` for VS-Code-style hooks or `plugins/claude-code/` for Anthropic-style. The plugin invokes `openlit coding hook --vendor=opencode --event=<EventName>`.
+5. **Native telemetry mapping** — if the vendor ships its own OTel signals, write §4's equivalent for it. Add the inbound coalesce to `queries.ts` and document the dual-path rules.
+6. **Icon** — add a tiny inline SVG component to `src/client/src/components/svg/coding-agents.tsx` and wire `case "opencode":` into `CodingAgentVendorIcon`. The hard-coded `=== "cursor"` checks in `coding-agents-table.tsx`, `signal-records.tsx`, and `trace-detail-page.tsx` should be replaced with a "ask the icon component, fall back to Bot" pattern so new vendors pick up icons automatically.
+7. **Onboarding doc** — `docs/features/coding-agents/onboarding.mdx`. Add a tab for the vendor.
+8. **Sanity check** — fire one session end to end, then run the verification SQL in `coding-agents-hook.mdc` §10.
+
+## 11. Things the convention WILL bite you on
+
+These are the rules that, when violated, make the UI silently render `0` / blank / wrong:
+
+- Stamping cost as a string (`"0.15"` instead of `0.15`). The UI's `(row.cost ?? 0).toFixed(2)` returns `"NaN"` and we render `$NaN`.
+- Stamping cost in cents (`15` for $0.15). Multiplies the dashboard total by 100.
+- Stamping `gen_ai.system = "claude-code"`. The provider rollup over-counts Anthropic + misses correct provider attribution. Use `anthropic`.
+- Stamping `coding_agent.session.outcome = ""`. The session-list query filters on outcome being one of the enum values; empty becomes "unknown" in the UI but breaks DORA-style queries.
+- Forgetting to stamp `coding_agent.signal_source` AND `telemetry.distro.name = "openlit-cli"`. The materializer's SDK discovery picks the spans up as SDK telemetry and the agent detail page flips between layouts on refresh. Both stamps are mandatory and live in `cli/internal/otlp/exporter.go`. See `coding-agents-hook.mdc` §10 for the full three-barrier exclusion chain.
+- Adding a vendor-namespaced attribute (`claude_code.foo`) that duplicates a canonical attribute (`coding_agent.foo`). The query layer reads canonical, the row will look empty even though the data is there.
+- Inventing new outcome / decision / classification values. The UI checks are explicit enum comparisons; new values render as blank.
+- Stamping ResourceAttributes with `service.name = "openlit-cli"`. Use the vendor identifier so the materializer's coding discovery picks it up. (The `openlit-cli` value goes on `telemetry.distro.name`, not on `service.name`.)
+- **`ORDER BY agent_key` dedup trap**. `openlit_agents_summary` is a `ReplacingMergeTree(updated_at) ORDER BY agent_key`. Once a phantom row exists for the same agent_key but a different `source` value, FINAL picks whichever has the higher `updated_at` — which can flip back and forth across materialize ticks. The mitigation lives at the *write side* (three barriers in `discoverAgents`, see hook rule §10); the long-term schema fix is widening the ORDER BY to `(agent_key, source)` so SDK and coding rows can coexist for the same service.
+
+## 12. Documented limitations (vendor data doesn't let us fold)
+
+These are known limits where the data the vendor sends prevents perfect rollup. Do not pretend they're fixed; surface them to the operator instead.
+
+- **Cursor: no stable chat-thread id across CLI processes**. When the user suspends a chat (laptop sleep, IDE restart) and resumes, Cursor spawns a fresh CLI process with a fresh `session_id` AND a fresh `conversation_id`. There is no field in the hook payload that links the new session to the previous one. Result: one user-perceived chat shows as N sessions in the OpenLit UI. The chat rollup is doing the right thing per the data it received; the limitation is upstream. Possible future fixes (in order of robustness): Cursor adds a `composer_thread_id` field to the payload, OR we read Cursor's local SQLite at `~/Library/Application Support/Cursor/User/globalStorage/state.vscdb` to map session_id → thread_id (version-fragile, not recommended without coordination with Cursor).
+- **Claude Code: no `cwd` / `repo` in native OTel telemetry**. The native exporter only knows what Claude Code itself sees. When the user runs Claude Code outside a Git repo, or when `CLAUDE_PROJECT_DIR` isn't set, those resource attributes will be empty even in the dual-path scenario.
+
+When in doubt: grep for the canonical attribute name in `queries.ts` and `materialize.ts`. If a reader doesn't already coalesce your new key, your data will be invisible to the UI no matter how cleanly it lands in ClickHouse.
diff --git a/.cursor/rules/coding-agents-hook.mdc b/.cursor/rules/coding-agents-hook.mdc
new file mode 100644
index 00000000..f81d16d1
--- /dev/null
+++ b/.cursor/rules/coding-agents-hook.mdc
@@ -0,0 +1,172 @@
+---
+description: Authoring or modifying a coding-agent hook adapter (Cursor, Claude Code, Codex, Windsurf, generic). Covers payload probing, session-state caching, OTel attribute emission, head sampling, capture modes, and the ClickHouse query patterns that consume them. Read before adding a new vendor or changing what we stamp on coding-agent spans.
+globs: cli/internal/coding/**/*.go,sdk/go/semconv/coding_agent.go,src/client/src/lib/platform/coding-agents/**/*.ts,src/client/src/lib/platform/agents/materialize.ts,plugins/**/hooks.json
+alwaysApply: false
+---
+
+# Coding-Agent Hook Authoring Guide
+
+This is the **authoring + failure-mode rule** for coding-agent hook code. The companion rule `.cursor/rules/coding-agents-convention.mdc` is the **schema contract** — start there if you're adding a new vendor or coalescing native vendor telemetry into our canonical attributes. This rule covers process, gotchas, and end-to-end verification.
+
+This rule is the contract between three pieces that have to stay in lock-step or the `/agents` and `/coding-agents` views go silently empty:
+
+1. **CLI hook adapter** — `cli/internal/coding/hook/<vendor>/handle.go`. Receives a JSON payload from the vendor, normalises it onto our schema, calls `Emit*` on the OTLP emitter.
+2. **OTel emission layer** — `cli/internal/otlp/{exporter,attrs,sampler,tracecontext}.go` and `sdk/go/openlit.go`. Stamps resource + span attributes, derives the deterministic TraceID, applies head sampling.
+3. **ClickHouse readers** — `src/client/src/lib/platform/coding-agents/queries.ts` and `src/client/src/lib/platform/agents/materialize.ts`. Roll up by chat thread, surface the hub row, drive the Sessions / Users / Overview pages.
+
+If you add a new vendor, change a span attribute, or touch the materializer, walk this rule top-to-bottom.
+
+---
+
+## 1. The chat-thread rollup contract
+
+Every coding-agent span MUST carry `coding_agent.session.id`. That is the **per-process** identifier. The chat thread the user actually sees is `chat_id`:
+
+```text
+chat_id = coalesce(
+ ResourceAttributes['coding_agent.agent.parent_id'],
+ SpanAttributes['coding_agent.agent.parent_id'],
+ SpanAttributes['coding_agent.session.id']
+)
+```
+
+When a vendor reports a parent conversation id on subagent payloads (Cursor's `parent_conversation_id`, Codex's similar field, etc.), `hook.go` promotes it to the resource attribute `coding_agent.agent.parent_id` so every span the subagent emits folds under the parent's chat row. If you skip this stamp, parent + N subagents will appear as N+1 separate sessions in the UI.
+
+When adding a new vendor:
+
+- Wire its parent-id field into `peekContext` (`hook.go`) so it lands in `cached.ParentConversationID`.
+- Confirm the resource attribute is added in the `sessionAttrs` block that's handed to `NewEmitter`.
+- Do **not** change `CHAT_ID_EXPR` in `queries.ts` — fold new keys into the coalesce there only if the vendor uses a brand-new attribute name.
+
+## 2. Session-state cache: persist, don't probe-only
+
+The CLI is short-lived (one process per hook event), so anything the vendor only ships on lifecycle events (sessionStart, prompt-submit) MUST be cached at `$XDG_CACHE_HOME/openlit/sessions/<sid>.json` and replayed on every later event in the same session. Otherwise per-tool / per-edit spans land without identity, cwd, repo, branch, model, or permission mode — and the trace-detail header pills go empty.
+
+Persist into `cached.*` and let `hook.go` re-write the cache:
+
+- `User` — vendor-provided email (Cursor's `user_email`, Claude Code transcript author, …).
+- `CWD` — first from payload (`cwd` / `workspace_roots[0]`), then `os.Getwd()` fallback. **Always persist** the resolved value so non-lifecycle events inherit it.
+- `RepoURL` + `Branch` — derived from `git.Snapshot(ctx, cwd)`. Best-effort, idempotent once cached.
+- `Model` / `PermissionMode` — vendor-supplied; persist verbatim.
+- `ConversationID` + `ParentConversationID` — chat-thread + subagent linkage.
+- `IsBackgroundAgent` — collapses Cursor's `is_background_agent` and `is_parallel_worker`.
+
+Things to **not** cache:
+
+- Tool call payloads, prompt bodies, file diffs. Those are per-event and capture-mode-gated.
+- Anything redacted by `redact.ForCapture(...)`.
+
+Always re-save (`sessionstate.Save`) when ANY of the cached fields change. The gate in `hook.go` keys off "is any field non-empty"; preserve that.
+
+## 3. Resource attributes vs span attributes
+
+These rules cover the most common confusion when reviewing a new adapter:
+
+- **Resource attributes** ride on *every span* this process emits. Use them for facts that are stable per session: `gen_ai.user.name`, `terminal.type`, `code.cwd`, `vcs.repository.url.full`, `vcs.ref.head.name`, `coding_agent.session.permission_mode`, `coding_agent.session.id`, `gen_ai.conversation.id`, `coding_agent.agent.parent_id`, `coding_agent.content_capture_mode`, `coding_agent.hook.cli.version`.
+- **Span attributes** belong to a single event. Examples: `coding_agent.tool.name`, `gen_ai.usage.input_tokens`, `coding_agent.edit.lines.added`, `coding_agent.session.model.from` / `…to`.
+
+When the trace-detail header pills go empty for a non-lifecycle span, the cause is almost always a fact that's emitted as a span attribute on lifecycle events but never as a resource attribute. Promote it.
+
+## 4. Capture modes
+
+Three modes, controlled per-deployment via `OPENLIT_CODING_CONTENT_CAPTURE`:
+
+| Mode | What lands on spans |
+| --------------- | ---------------------------------------------------------- |
+| `minimal` | Counters and identifiers only. No bodies. Single session-root span per session. Per-event spans suppressed. |
+| `metadata_only` | Adds tool names, file paths (sanitised), classification labels. Still no message bodies, no file diffs, no shell commands. |
+| `full` | Everything `metadata_only` has, plus prompt/completion bodies, tool results, edit diffs. Both redaction tiers active. |
+
+Centralised in `cli/internal/otlp/attrs.go`:
+
+- `setStr(span, key, val, scrub)` — runs every string through `redact.ForCapture(mode)` before stamping.
+- `perEventSpansAllowed(mode)` — gates per-event span emission for `minimal` mode.
+- Adapters must use these helpers; never call `span.SetAttributes` directly with a value that might contain a body.
+
+When adding a new attribute, decide which capture mode tier it belongs to and gate accordingly. Don't add a body-bearing attribute that lands in `metadata_only`.
+
+## 5. Deterministic trace/span IDs
+
+`cli/internal/otlp/tracecontext.go` derives the trace and root-span IDs from the session id, salted with `OPENLIT_TRACEID_SALT` via HMAC-SHA256. The salt is optional; without it the ID is deterministic but more easily reverse-engineerable. Don't change the derivation function — readers (UI hierarchy explorer, the materializer's rollup logic) all rely on `(sessionID) → traceID` being stable across hook processes.
+
+If you must extend it (e.g. to support per-tenant salts), update both the CLI derivation and the UI's session-resolution helpers in the same change.
+
+## 6. Head sampling
+
+`cli/internal/otlp/sampler.go` reads `OPENLIT_CODING_SAMPLE_EVENTS`. Today the only configured rule is `drop_requested`, which drops `coding_agent.tool.requested`, `coding_agent.shell.requested`, and similar high-frequency "about to happen" events when an operator wants only completed events. When you add a new noisy event type:
+
+- Add the span name to the sampler's drop list under a named rule.
+- Document the rule in the onboarding mdx so operators know which knob to flip.
+
+Do **not** add a sampler that silently drops session-root spans or LLM turns. Those are the trustable backbone of the data model.
+
+## 7. ClickHouse query patterns and the `any()`-in-GROUP-BY trap
+
+ClickHouse aggressively inlines `WITH` CTEs and explicit subqueries. Two patterns will silently break a query:
+
+1. **Aggregate inside `GROUP BY`**. Anything like
+ ```sql
+ GROUP BY coalesce(any(SpanAttributes['…parent_id']), SpanAttributes['…session.id'])
+ ```
+ fails with `ILLEGAL_AGGREGATION`. Solution: derive the rollup key per-row (no `any()` / `argMax()`), then GROUP BY the alias.
+
+2. **Aggregate-of-an-aggregate after inlining**. If `per_user.last_seen = max(Timestamp)` and `users_raw.last_seen = max(last_seen)`, the inliner sees `max(max(Timestamp))` and rejects it. Solution: alias each layer's aggregates with distinct names (e.g. `session_last_ts`, `per_user_last_ts`, `user_last_ts`) and format/round only at the outermost SELECT.
+
+When writing or reviewing a new query in `queries.ts` / `materialize.ts`, run it directly against ClickHouse first:
+
+```bash
+curl -s -u 'default:OPENLIT' 'http://localhost:8123/?database=openlit' --data-binary @query.sql
+```
+
+Don't trust the route's `processed: N` counter — it can succeed for other rows while silently swallowing the coding-agent rollup via a logger.error.
+
+## 8. Cohort floor: privacy at *read* time, not materialize time
+
+`COHORT_K_FLOOR` (currently 5) masks per-user breakdowns for non-admins. Apply it:
+
+- ✅ In `queries.ts` for `/coding-agents/users` and similar per-user breakdowns, inside the SQL projection so masking happens *before* `LIMIT` and pagination stays consistent.
+- ❌ Never in the materializer (`materialize.ts`). The materialized table is internal; if you apply the floor at write time, a single-developer OSS install will always show 0 active users on the hub. The masking belongs at the auth-aware query boundary.
+
+## 9. Vendor-adding checklist
+
+When adding `claude-code`, `codex`, or any new vendor:
+
+1. **Adapter** — `cli/internal/coding/hook/<vendor>/handle.go`. Map vendor events onto `normalize.{Session, ToolCall, LLMTurn, EditDecision, …}` and call the matching `emit.Emit*` method. Stamp `Vendor`, `SessionID`, `ConversationID`, `ParentConversationID` on every payload.
+2. **Probe extension** — `peekContext` in `hook.go`. Add the vendor's key names to `pickString` so user / cwd / model / permission_mode resolve from the payload.
+3. **Plugin manifest** — `plugins/<vendor>/...`. Register the hook subcommands the vendor exposes. Mirror the schema Cursor uses for consistency.
+4. **Onboarding doc** — `docs/features/coding-agents/onboarding.mdx`. Add the vendor's install snippet and the list of hooks it ships.
+5. **Queries** — usually no change. `VENDOR_EXPR`, `CHAT_ID_EXPR`, `USER_EXPR` already coalesce across the standard semantic-conv keys. Touch them only if the vendor uses a brand-new attribute name.
+6. **Materializer** — usually no change. The single-pass GROUP BY in `discoverCodingAgents` covers any vendor that sets `coding_agent.client` and `coding_agent.session.id`.
+7. **Sanity check** — fire a hook event end-to-end, then verify:
+ ```sql
+ SELECT count() FROM otel_traces
+ WHERE SpanAttributes['coding_agent.client'] = '<vendor>';
+ ```
+ then trigger the materializer (`curl -X POST … -H 'X-CRON-JOB: true'`) and confirm a row lands in `openlit_agents_summary` with `source='coding'` and `coding_agent_vendor='<vendor>'`.
+
+## 10. Things that have bitten us — do not regress
+
+- **Empty Coding-Agents tab**. Caused by `any()` inside `GROUP BY` in `discoverCodingAgents`. Always rewrite to a per-row rollup key.
+- **Empty Repository / Working Folder pills on non-lifecycle spans**. Caused by `os.Getwd()` fallback not being persisted to `cached.CWD`. Persist it.
+- **`active_users_24h` always 0**. Caused by applying `COHORT_K_FLOOR` at materialize time. Move it to query time.
+- **Duplicate session rows**. Caused by emitting a session-root span on both `sessionStart` and `sessionEnd`. Only emit on `End`; treat `started` / `in_progress` outcomes as a no-op (see `EmitSession` in `exporter.go`).
+- **OOM / latency spikes on big transcripts**. Caused by reading entire Claude transcript or Codex rollout files. Use `tailfile.Tail(path, cap)` with a sane byte cap.
+- **Span attributes carrying secrets**. Caused by adapters bypassing `setStr(..., scrub)`. Always pipe strings through the scrubber.
+- **Agent detail page flips between the coding view and the generic SDK Overview/Dashboard/Monitoring view on refresh**. Caused by the SDK discovery in `materialize.ts:discoverAgents` picking up the CLI's spans (the CLI sets `service.name = '<vendor>'` and emits via the openlit-go SDK), writing an `source='sdk'` row that shares the agent_key with the `source='coding'` row. `openlit_agents_summary` is a `ReplacingMergeTree(updated_at) ORDER BY agent_key`, so whichever tick wrote most recently wins on `FINAL`, and the detail page chooses its layout from `agent.source`. The structural fix has THREE independent barriers, all of which must stay in place:
+
+ 1. **`telemetry.distro.name = 'openlit-cli'`** stamped on every CLI span as a resource attribute (set in `cli/internal/otlp/exporter.go`). This is the *positive* identifier of the emitting distribution — the same hook OTel itself uses (`opentelemetry-ebpf-instrumentation`, `opentelemetry-auto-instrumentation`, …). Once set on the resource, it rides on every span emitted by that process.
+ 2. **`discoverAgents` excludes by distro name AND by service-name anti-join** against any service that ever emitted an `openlit-cli` distro span in the lookback window. A future regression that strips `coding_agent.session.id` from one span won't leak — the service is still excluded.
+ 3. **Legacy `coding_agent.session.id` per-span filter** kept as a backstop for spans emitted before barrier #1 shipped. Remove only after the retention window has rolled past the distro cutover.
+
+ Do **not** add a new coding vendor without confirming all three barriers cover it. A pending one-time cleanup is also needed when the bug DID slip through: `ALTER TABLE openlit_agents_summary DELETE WHERE service_name IN (SELECT service_name FROM openlit_agents_summary WHERE source = 'coding') AND source != 'coding'`. The dedup key being just `agent_key` (not `(agent_key, source)`) means once a phantom SDK row exists, the next coding tick will eventually overwrite it on `FINAL`, but only if its `updated_at` is strictly newer — a future schema migration to widen the dedup key to `(agent_key, source)` would let both rows coexist and end this category of bug for good.
+
+ A **fourth** structural failure mode lived independently of the three barriers above and was the actual cause of the repeated "SDK Overview tabs on my Cursor agent" sightings: `materializeAgents({ scope })`, called by `/api/agents/[agentKey]/refresh` whenever the operator clicks the Refresh button on the agent detail page, only looked the agent up via `discoverAgents` (SDK pipeline). For a coding agent the lookup correctly missed, the code fell through to a `source: 'sdk'` placeholder, and inserted that phantom row directly — sidestepping every discovery-side barrier. Two new safeguards live in [src/client/src/lib/platform/agents/materialize.ts](src/client/src/lib/platform/agents/materialize.ts):
+
+ - The scoped branch now consults BOTH `discoverAgents` AND `discoverCodingAgents`, and refuses to manufacture an SDK placeholder when neither matches. A refresh hitting before any spans arrive is a no-op; it does NOT invent a row.
+ - Right before the `INSERT INTO openlit_agents_summary`, any row whose `source !== 'coding'` is checked against the table; if an existing `source='coding'` row already lives at the same `agent_key`, the would-be clobberer is dropped and the materializer logs `materializer_blocked_coding_clobber`. This is the final safety net — any future code path that tries to write a non-coding row over a coding row is caught at the insert site.
+
+- **Two distinct Cursor "session_id"s for what the user remembers as one chat**. Cursor's hook payload exposes `session_id` (per CLI process), `conversation_id` (per Cursor chat thread, but in current Cursor builds it equals `session_id` for non-subagent chats), and `parent_conversation_id` (set only on subagent payloads). When a chat is suspended (laptop sleep) and resumed, or when the user opens a previous chat from history, Cursor may spawn a new CLI process with a fresh `session_id` AND a fresh `conversation_id`. There is **no stable chat-thread identifier in the hook payload** that survives this. Our chat rollup folds by `coalesce(parent_conversation_id, session_id)`, so two un-linked Cursor sessions land as two chats — even if the user thinks of them as one. This is a documented limitation, not a bug; we can close it only by:
+ 1. Reading Cursor's local SQLite DB at `~/Library/Application Support/Cursor/User/globalStorage/state.vscdb` to map session_id → composer_thread_id (brittle, version-specific schema), OR
+ 2. Cursor surfacing a stable `composer_thread_id` on the hook payload (upstream change we'd file with Cursor).
+
+ Until then, when investigating "I have N chats but the UI shows N+1": confirm `gen_ai.conversation.id` across the spans for the two presumed-equal sessions. If Cursor sent different conversation_ids, our rollup is doing the right thing.
diff --git a/.github/workflows/cli-release.yml b/.github/workflows/cli-release.yml
new file mode 100644
index 00000000..4b63581a
--- /dev/null
+++ b/.github/workflows/cli-release.yml
@@ -0,0 +1,221 @@
+name: openlit CLI Release
+
+on:
+ push:
+ tags:
+ - 'cli-*.*.*'
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: 'Tag to release (cli-X.Y.Z)'
+ required: true
+
+permissions:
+ contents: write
+ packages: write
+
+jobs:
+ build:
+ name: Build ${{ matrix.os }} / ${{ matrix.arch }}
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { os: linux, arch: amd64, ext: "" }
+ - { os: linux, arch: arm64, ext: "" }
+ - { os: darwin, arch: amd64, ext: "" }
+ - { os: darwin, arch: arm64, ext: "" }
+ - { os: windows, arch: amd64, ext: ".exe" }
+ - { os: windows, arch: arm64, ext: ".exe" }
+ steps:
+ - uses: actions/checkout@v6
+ with: { fetch-depth: 0 }
+ - uses: actions/setup-go@v6
+ with:
+ go-version-file: cli/go.mod
+ check-latest: true
+ - name: Resolve version
+ id: ver
+ # Single source of truth: prefer workflow_dispatch's `tag` input
+ # (stripping any leading `cli-` so the user can pass either
+ # `cli-1.2.0` or `1.2.0`), otherwise derive from GITHUB_REF for
+ # the tag-push trigger. We then validate the result matches a
+ # semver-ish shape — without the guard, a dispatch run with an
+ # empty `tag` input previously produced `VERSION=refs/heads/main`
+ # which got silently stamped into the release name *and* the
+ # binary's `--version` output.
+ run: |
+ if [ -n "${{ github.event.inputs.tag }}" ]; then
+ VERSION="$(echo '${{ github.event.inputs.tag }}' | sed 's/^cli-//')"
+ else
+ VERSION="${GITHUB_REF#refs/tags/cli-}"
+ fi
+ if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+([-+][A-Za-z0-9._-]+)?$'; then
+ echo "::error::Could not resolve a semver release version (got '${VERSION}'). Pass a 'tag' input like 'cli-1.2.0' on workflow_dispatch, or push a 'cli-X.Y.Z' tag."
+ exit 1
+ fi
+ echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT
+ - name: Build
+ working-directory: ./cli
+ env:
+ GOOS: ${{ matrix.os }}
+ GOARCH: ${{ matrix.arch }}
+ CGO_ENABLED: 0
+ run: |
+ mkdir -p dist
+ VERSION="${{ steps.ver.outputs.VERSION }}"
+ COMMIT="$(git rev-parse --short HEAD)"
+ # The version vars live in cli/internal/version, not in
+ # `main`. The earlier `-X main.Version=...` flag silently
+ # had no effect — every release binary printed `dev` from
+ # the package default. -X must target the fully-qualified
+ # package path or Go's linker quietly ignores it.
+ PKG="github.com/openlit/openlit/cli/internal/version"
+ go build -trimpath -ldflags "-s -w -X ${PKG}.Version=$VERSION -X ${PKG}.Commit=$COMMIT" \
+ -o dist/openlit-${GOOS}-${GOARCH}${{ matrix.ext }} ./cmd/openlit
+ - name: Package
+ working-directory: ./cli
+ run: |
+ NAME="openlit-${{ matrix.os }}-${{ matrix.arch }}"
+ BIN="dist/${NAME}${{ matrix.ext }}"
+ cd dist
+ if [ "${{ matrix.os }}" = "windows" ]; then
+ zip "${NAME}.zip" "$(basename "$BIN")" ../README.md ../../LICENSE
+ sha256sum "${NAME}.zip" > "${NAME}.zip.sha256"
+ else
+ tar -czf "${NAME}.tar.gz" "$(basename "$BIN")" -C ../ README.md -C ../../ LICENSE
+ sha256sum "${NAME}.tar.gz" > "${NAME}.tar.gz.sha256"
+ fi
+ - uses: actions/upload-artifact@v4
+ with:
+ name: openlit-${{ matrix.os }}-${{ matrix.arch }}
+ path: cli/dist/*
+
+ release:
+ name: GitHub Release
+ needs: build
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ with: { fetch-depth: 0 }
+ - name: Resolve version
+ id: ver
+ # Mirror the build job's resolver so workflow_dispatch runs
+ # produce a release named after the user-supplied tag rather
+ # than `vrefs/heads/main` (GITHUB_REF on a dispatched run).
+ run: |
+ if [ -n "${{ github.event.inputs.tag }}" ]; then
+ VERSION="$(echo '${{ github.event.inputs.tag }}' | sed 's/^cli-//')"
+ else
+ VERSION="${GITHUB_REF#refs/tags/cli-}"
+ fi
+ if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+([-+][A-Za-z0-9._-]+)?$'; then
+ echo "::error::Could not resolve a semver release version (got '${VERSION}')."
+ exit 1
+ fi
+ echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT
+ - uses: actions/download-artifact@v4
+ with: { path: artifacts }
+ - name: Flatten artifacts
+ run: |
+ mkdir -p release
+ find artifacts -type f \( -name "*.tar.gz" -o -name "*.zip" -o -name "*.sha256" \) -exec cp {} release/ \;
+ ls -la release
+ # Pinned to a full commit SHA per supply-chain hardening guidance.
+ # `softprops/action-gh-release` writes the release artifacts that
+ # users install via curl|sh and brew — a moving `@v3` tag could be
+ # repointed at a malicious commit by a compromised maintainer.
+ # Bump via Dependabot (see .github/dependabot.yml).
+ - uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0
+ with:
+ name: openlit CLI v${{ steps.ver.outputs.VERSION }}
+ files: release/*
+ draft: false
+ prerelease: false
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
+ docker:
+ name: Container image
+ needs: build
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ # The three Docker actions below are pinned to commit SHAs (instead
+ # of `@v3` / `@v5`) so a future repoint of the tag can't slip a
+ # backdoored buildx or login step into the GHCR push pipeline. The
+ # SHAs are kept fresh by Dependabot via .github/dependabot.yml.
+ - uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
+ - name: Log in to GHCR
+ uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Resolve version
+ id: ver
+ run: |
+ if [ -n "${{ github.event.inputs.tag }}" ]; then
+ VERSION="$(echo '${{ github.event.inputs.tag }}' | sed 's/^cli-//')"
+ else
+ VERSION="${GITHUB_REF#refs/tags/cli-}"
+ fi
+ if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+([-+][A-Za-z0-9._-]+)?$'; then
+ echo "::error::Could not resolve a semver release version (got '${VERSION}')."
+ exit 1
+ fi
+ echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT
+ - name: Build and push image
+ # docker/build-push-action is the action that actually produces
+ # and pushes the multi-arch container image. Pinned to a SHA so
+ # a compromised tag can't ship a backdoored image to GHCR.
+ # NOTE: v5 is the last release of the v5 series (v5.4.0); v7 is
+ # current upstream. Stay on v5 here until we test the v7 input
+ # changes — the bump is tracked in Dependabot.
+ uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0
+ with:
+ context: .
+ file: cli/Dockerfile
+ push: true
+ platforms: linux/amd64,linux/arm64
+ build-args: |
+ VERSION=${{ steps.ver.outputs.VERSION }}
+ COMMIT=${{ github.sha }}
+ tags: |
+ ghcr.io/${{ github.repository_owner }}/openlit-cli:${{ steps.ver.outputs.VERSION }}
+ ghcr.io/${{ github.repository_owner }}/openlit-cli:latest
+
+ homebrew:
+ name: Update Homebrew tap
+ needs: release
+ runs-on: ubuntu-latest
+ if: ${{ secrets.HOMEBREW_TAP_TOKEN != '' }}
+ steps:
+ - name: Resolve version
+ id: ver
+ run: |
+ if [ -n "${{ github.event.inputs.tag }}" ]; then
+ VERSION="$(echo '${{ github.event.inputs.tag }}' | sed 's/^cli-//')"
+ else
+ VERSION="${GITHUB_REF#refs/tags/cli-}"
+ fi
+ if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+([-+][A-Za-z0-9._-]+)?$'; then
+ echo "::error::Could not resolve a semver release version (got '${VERSION}')."
+ exit 1
+ fi
+ echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT
+ - name: Update tap formula
+ # `dawidd6/action-homebrew-bump-formula` is the lone-maintainer
+ # action with the highest blast radius in this workflow: its
+ # token can push commits into the homebrew tap that mints what
+ # `brew install openlit` resolves to. Pinning to a SHA is the
+ # whole point — a tag repoint here directly compromises every
+ # user who runs `brew upgrade`.
+ uses: dawidd6/action-homebrew-bump-formula@baf2b60c51fc1f8453c884b0c61052668a71bd1d # v3.11.0
+ with:
+ token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
+ tap: openlit/homebrew-openlit
+ formula: openlit
+ tag: cli-${{ steps.ver.outputs.VERSION }}
diff --git a/.github/workflows/cli-tests.yml b/.github/workflows/cli-tests.yml
new file mode 100644
index 00000000..be3884ce
--- /dev/null
+++ b/.github/workflows/cli-tests.yml
@@ -0,0 +1,98 @@
+name: openlit CLI tests
+
+# Runs go-test + the plugin-tree drift check for the openlit CLI.
+# Splits out from cli-release.yml so test failures don't have to wait
+# for a tag push: every PR that touches cli/ or plugins/ gets the
+# same signal the release workflow would.
+
+on:
+ push:
+ branches: ["main"]
+ paths:
+ - 'cli/**'
+ - 'plugins/**'
+ - 'sdk/go/**'
+ - '.github/workflows/cli-tests.yml'
+ pull_request:
+ branches: ["main"]
+ paths:
+ - 'cli/**'
+ - 'plugins/**'
+ - 'sdk/go/**'
+ - '.github/workflows/cli-tests.yml'
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: go test
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-go@v6
+ with:
+ go-version-file: cli/go.mod
+ check-latest: true
+ - name: go mod download
+ working-directory: cli
+ run: go mod download
+ - name: go build
+ working-directory: cli
+ run: go build -trimpath ./...
+ - name: go test
+ working-directory: cli
+ # -race catches concurrency bugs in sessionstate / OTLP
+ # batching paths. -count=1 disables the test cache so
+ # flaky-on-purpose retries (rate-limit windows, etc.)
+ # don't get a free pass.
+ run: go test -race -count=1 ./...
+
+ cross-compile:
+ name: cross-compile (${{ matrix.os }} / ${{ matrix.arch }})
+ runs-on: ubuntu-latest
+ needs: test
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { os: windows, arch: amd64 }
+ - { os: darwin, arch: arm64 }
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-go@v6
+ with:
+ go-version-file: cli/go.mod
+ check-latest: true
+ - name: Build
+ working-directory: cli
+ env:
+ GOOS: ${{ matrix.os }}
+ GOARCH: ${{ matrix.arch }}
+ CGO_ENABLED: 0
+ # We don't ship these here — just confirm the build tags
+ # (flock_windows.go, etc.) keep cross-compile green.
+ run: go build -trimpath -o /dev/null ./cmd/openlit
+
+ plugin-sync-drift:
+ name: .claude-plugin/ + plugins/ in-sync with cli/internal/coding/install/marketplace
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ - name: Sync into a temp dir and diff
+ run: |
+ set -euo pipefail
+ # Capture the embedded marketplace tree before re-running sync,
+ # then diff the sync result against it. Drift here means
+ # somebody edited .claude-plugin/ or plugins/ at the repo root
+ # but forgot to run cli/scripts/sync-plugins.sh.
+ BEFORE=$(mktemp -d)
+ cp -R cli/internal/coding/install/marketplace/. "$BEFORE/"
+ bash cli/scripts/sync-plugins.sh
+ if ! diff -ru "$BEFORE" cli/internal/coding/install/marketplace; then
+ echo
+ echo "::error::.claude-plugin/ or plugins/ has drifted from cli/internal/coding/install/marketplace/."
+ echo "Run \`bash cli/scripts/sync-plugins.sh\` locally and commit the result."
+ exit 1
+ fi
+ echo "embedded marketplace tree is in sync"
diff --git a/.gitignore b/.gitignore
index 6331bbc9..19b77e30 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,10 @@ logs/
**.env
.vscode/
.idea/
+.cursor-rules/
+.cursorrules
+# Local Cursor hook config has machine-specific binary paths
+.cursor/hooks.json
**.pem
**certs/index.txt
**.csr
diff --git a/README.md b/README.md
index 4d1f381d..cfe2304d 100644
--- a/README.md
+++ b/README.md
@@ -175,6 +175,49 @@ Just head over to OpenLIT at `127.0.0.1:3000` on your browser to start exploring
![](https://github.com/openlit/.github/blob/main/profile/assets/openlit-client-1.png?raw=true)
![](https://github.com/openlit/.github/blob/main/profile/assets/openlit-client-2.png?raw=true)
+## 🤖 AI Coding Agents (Claude Code, Cursor, Codex)
+
+OpenLIT also ships a CLI that brings the same observability story to your
+**local coding agents** — Claude Code, Cursor, and Codex. No SDK to import:
+the CLI installs vendor hooks that emit OpenTelemetry traces for every
+session, prompt, tool call, file edit, subagent spawn, and code-impact event.
+
+### Install the CLI
+
+```bash
+# macOS + Linux
+curl -fsSL https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/install.sh | sh
+
+# Windows (PowerShell)
+iwr -useb https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/install.ps1 | iex
+```
+
+### Wire it into your agents
+
+```bash
+openlit configure --endpoint http://127.0.0.1:4318 [--api-key <key>]
+openlit coding install --vendor=all # or: cursor / claude-code / codex
+```
+
+### Inspect what's running
+
+```bash
+openlit doctor # config + OTLP reachability + installed plugins
+```
+
+Sessions, prompts, costs, and per-vendor breakdowns appear in the OpenLIT
+dashboard at `http://127.0.0.1:3000/coding-agents`. To detach later:
+
+```bash
+openlit coding uninstall --vendor=all
+```
+
+> Coding-agent observability is OTel-native end-to-end: traces use the
+> [`gen_ai.*`](https://opentelemetry.io/docs/specs/semconv/gen-ai/) semantic
+> conventions alongside an `coding_agent.*` extension namespace. Anything
+> that speaks OTLP (Datadog, Honeycomb, Grafana Tempo, raw OTel Collector)
+> can consume the same data — OpenLIT is just one possible viewer.
+
## 📦 Supported Integrations
OpenLIT auto-instruments **50+ LLM providers, AI frameworks, and vector databases** with a single line of code. Each integration produces [OpenTelemetry-native](https://opentelemetry.io/) traces and metrics. Click any card to view the integration docs.
diff --git a/assets/pricing.json b/assets/pricing.json
index 1880c1bb..76610818 100644
--- a/assets/pricing.json
+++ b/assets/pricing.json
@@ -257,6 +257,166 @@
"promptPrice": 0.00025,
"completionPrice": 0.00125
},
+ "claude-3-5-sonnet-20240620": {
+ "promptPrice": 0.003,
+ "completionPrice": 0.015
+ },
+ "claude-3-5-sonnet-20241022": {
+ "promptPrice": 0.003,
+ "completionPrice": 0.015
+ },
+ "claude-3-5-haiku-20241022": {
+ "promptPrice": 0.0008,
+ "completionPrice": 0.004
+ },
+ "claude-3-7-sonnet-20250219": {
+ "promptPrice": 0.003,
+ "completionPrice": 0.015
+ },
+ "claude-haiku-4-5-20251001": {
+ "promptPrice": 0.001,
+ "completionPrice": 0.005
+ },
+ "claude-haiku-4-5": {
+ "promptPrice": 0.001,
+ "completionPrice": 0.005
+ },
+ "claude-sonnet-4-0": {
+ "promptPrice": 0.003,
+ "completionPrice": 0.015
+ },
+ "claude-sonnet-4-5": {
+ "promptPrice": 0.003,
+ "completionPrice": 0.015
+ },
+ "claude-sonnet-4-6": {
+ "promptPrice": 0.003,
+ "completionPrice": 0.015
+ },
+ "claude-sonnet-4-7": {
+ "promptPrice": 0.003,
+ "completionPrice": 0.015
+ },
+ "claude-opus-4-0": {
+ "promptPrice": 0.015,
+ "completionPrice": 0.075
+ },
+ "claude-opus-4-1": {
+ "promptPrice": 0.015,
+ "completionPrice": 0.075
+ },
+ "claude-opus-4-5": {
+ "promptPrice": 0.005,
+ "completionPrice": 0.025
+ },
+ "claude-opus-4-6": {
+ "promptPrice": 0.005,
+ "completionPrice": 0.025
+ },
+ "claude-opus-4-7": {
+ "promptPrice": 0.005,
+ "completionPrice": 0.025
+ },
+ "claude-opus-4-7-thinking-xhigh": {
+ "promptPrice": 0.005,
+ "completionPrice": 0.025
+ },
+ "claude-opus-4-7-thinking-high": {
+ "promptPrice": 0.005,
+ "completionPrice": 0.025
+ },
+ "claude-opus-4-7-thinking-medium": {
+ "promptPrice": 0.005,
+ "completionPrice": 0.025
+ },
+ "claude-opus-4-7-thinking-low": {
+ "promptPrice": 0.005,
+ "completionPrice": 0.025
+ },
+ "gpt-5": {
+ "promptPrice": 0.00125,
+ "completionPrice": 0.01
+ },
+ "gpt-5-codex": {
+ "promptPrice": 0.00125,
+ "completionPrice": 0.01
+ },
+ "gpt-5-mini": {
+ "promptPrice": 0.00025,
+ "completionPrice": 0.002
+ },
+ "gpt-5-nano": {
+ "promptPrice": 0.00005,
+ "completionPrice": 0.0004
+ },
+ "gpt-5-pro": {
+ "promptPrice": 0.015,
+ "completionPrice": 0.12
+ },
+ "gpt-5.1": {
+ "promptPrice": 0.00125,
+ "completionPrice": 0.01
+ },
+ "gpt-5.1-codex": {
+ "promptPrice": 0.00125,
+ "completionPrice": 0.01
+ },
+ "gpt-5.1-codex-max": {
+ "promptPrice": 0.00125,
+ "completionPrice": 0.01
+ },
+ "gpt-5.2": {
+ "promptPrice": 0.00175,
+ "completionPrice": 0.014
+ },
+ "gpt-5.2-codex": {
+ "promptPrice": 0.00175,
+ "completionPrice": 0.014
+ },
+ "gpt-5.2-pro": {
+ "promptPrice": 0.021,
+ "completionPrice": 0.168
+ },
+ "gpt-5.3-codex": {
+ "promptPrice": 0.00175,
+ "completionPrice": 0.014
+ },
+ "gpt-5.4": {
+ "promptPrice": 0.0025,
+ "completionPrice": 0.015
+ },
+ "gpt-5.4-mini": {
+ "promptPrice": 0.00075,
+ "completionPrice": 0.0045
+ },
+ "gpt-5.4-nano": {
+ "promptPrice": 0.0002,
+ "completionPrice": 0.00125
+ },
+ "gpt-5.4-pro": {
+ "promptPrice": 0.03,
+ "completionPrice": 0.18
+ },
+ "gpt-5.5": {
+ "promptPrice": 0.005,
+ "completionPrice": 0.03
+ },
+ "gpt-5.5-pro": {
+ "promptPrice": 0.03,
+ "completionPrice": 0.18
+ },
+ "o3": {
+ "promptPrice": 0.002,
+ "completionPrice": 0.008
+ },
+ "o3-mini": {
+ "promptPrice": 0.0011,
+ "completionPrice": 0.0044
+ },
+ "o4-mini": {
+ "promptPrice": 0.0011,
+ "completionPrice": 0.0044
+ },
"command": {
"promptPrice": 0.001,
"completionPrice": 0.002
@@ -421,6 +581,26 @@
"promptPrice": 0.00125,
"completionPrice": 0.01
},
+ "gemini-2.5-pro-preview": {
+ "promptPrice": 0.00125,
+ "completionPrice": 0.01
+ },
+ "gemini-3-flash": {
+ "promptPrice": 0.0005,
+ "completionPrice": 0.003
+ },
+ "gemini-3.1-flash-lite": {
+ "promptPrice": 0.00025,
+ "completionPrice": 0.0015
+ },
+ "gemini-3.1-pro": {
+ "promptPrice": 0.002,
+ "completionPrice": 0.012
+ },
+ "gemini-3.1-pro-preview": {
+ "promptPrice": 0.002,
+ "completionPrice": 0.012
+ },
"text-bison": {
"promptPrice": 0.001,
"completionPrice": 0.002
diff --git a/cli/Dockerfile b/cli/Dockerfile
new file mode 100644
index 00000000..aff72ae5
--- /dev/null
+++ b/cli/Dockerfile
@@ -0,0 +1,46 @@
+# Multi-stage build for the openlit CLI.
+#
+# Stage 1 produces a statically-linked binary so the runtime image needs no
+# Go toolchain. Stage 2 ships a tiny distroless image with git + bash so the
+# survival-rework + scan-repo workers can shell out to git locally.
+
+ARG GO_VERSION=1.25
+
+FROM golang:${GO_VERSION}-alpine AS build
+RUN apk add --no-cache git ca-certificates
+WORKDIR /src
+
+# Copy the cli and sdk modules together so the `replace` directive can
+# resolve sdk/go locally.
+COPY cli/ ./cli
+COPY sdk/go/ ./sdk/go
+WORKDIR /src/cli
+RUN go mod download
+ARG VERSION=dev
+ARG COMMIT=unknown
+# Version vars live in cli/internal/version, not in `main`. Targeting
+# main.Version made -X a silent no-op — every image printed `dev`.
+ARG VERSION_PKG=github.com/openlit/openlit/cli/internal/version
+RUN CGO_ENABLED=0 GOOS=linux \
+ go build -trimpath -ldflags "-s -w -X ${VERSION_PKG}.Version=${VERSION} -X ${VERSION_PKG}.Commit=${COMMIT}" \
+ -o /out/openlit ./cmd/openlit
+
+FROM debian:bookworm-slim AS runtime
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends git ca-certificates bash \
+ && rm -rf /var/lib/apt/lists/*
+# Optional: install gitleaks + semgrep so `openlit scan-repo` works out of the
+# box. They are large so we keep them optional via the BUILD_WITH_SCANNERS arg.
+ARG BUILD_WITH_SCANNERS=false
+RUN if [ "$BUILD_WITH_SCANNERS" = "true" ]; then \
+ apt-get update && apt-get install -y --no-install-recommends curl python3-pip \
+ && curl -sSL https://github.com/gitleaks/gitleaks/releases/latest/download/gitleaks_8.21.2_linux_x64.tar.gz \
+ | tar -xz -C /usr/local/bin gitleaks \
+ && pip3 install --no-cache-dir --break-system-packages semgrep \
+ && apt-get purge -y curl python3-pip \
+ && apt-get autoremove -y \
+ && rm -rf /var/lib/apt/lists/*; \
+ fi
+COPY --from=build /out/openlit /usr/local/bin/openlit
+ENTRYPOINT ["/usr/local/bin/openlit"]
+CMD ["--help"]
diff --git a/cli/cmd/openlit/main.go b/cli/cmd/openlit/main.go
new file mode 100644
index 00000000..9dd90b6f
--- /dev/null
+++ b/cli/cmd/openlit/main.go
@@ -0,0 +1,89 @@
+// openlit is the OpenLit command-line tool. v1 ships the `coding`
+// subcommand group for AI-coding-agent observability (Claude Code, Cursor,
+// Codex). Future subcommand groups (prompts, traces, eval,
+// migrate) plug in by registering on the root in `registerSubcommands`.
+//
+// Crash-isolation guardrails (see internal/coding/hook):
+// - hook subcommand never blocks the developer (always exits 0)
+// - 5s hard timeout per invocation; 3s of that for OTLP flush
+// - never writes to stdout (Claude Code parses stdout for JSON)
+// - panic-recover wrapper around every command body
+package main
+
+import (
+ "os"
+
+ "github.com/openlit/openlit/cli/internal/coding"
+ "github.com/openlit/openlit/cli/internal/configure"
+ "github.com/openlit/openlit/cli/internal/doctor"
+ "github.com/openlit/openlit/cli/internal/version"
+ "github.com/spf13/cobra"
+)
+
+func main() {
+ root := newRootCmd()
+ if err := root.Execute(); err != nil {
+ // cobra already prints to stderr; just set the exit code.
+ // We never use os.Exit on telemetry-path errors; those swallow
+ // inside the command handlers themselves so the agent never
+ // sees a non-zero exit. Errors here are misuse (bad flags,
+ // unknown subcommands) where exiting non-zero is correct.
+ os.Exit(1)
+ }
+}
+
+func newRootCmd() *cobra.Command {
+ root := &cobra.Command{
+ Use: "openlit",
+ Short: "OpenLit command-line tool",
+ Long: `openlit is the OpenLit command-line tool.
+
+v1 ships the 'coding' subcommand group for AI-coding-agent observability:
+
+ openlit coding install --vendor=all
+ openlit coding launch claude
+ openlit coding hook --vendor=cc --event=SessionStart
+
+Run 'openlit doctor' to diagnose configuration, OTLP reachability,
+and installed plugins in one shot.
+
+Future subcommand groups (prompts, traces, eval) will plug in alongside.
+
+Configure the OTLP endpoint and (optional) API key via:
+ - flags: --otlp-endpoint, --api-key
+ - env: OPENLIT_OTLP_ENDPOINT, OPENLIT_API_KEY
+ - or std: OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS
+ - or file: ~/.config/openlit/config.env (allow-listed keys)
+`,
+ // Suppress cobra's default usage spam on errors that bubble up
+ // from subcommands; the subcommands handle their own messaging.
+ SilenceUsage: true,
+ // Errors are printed by cobra by default. We keep that for misuse
+ // errors (bad flags) but swallow telemetry-path errors inside the
+ // subcommand handlers so they never leak to stdout/stderr at all.
+ SilenceErrors: false,
+ }
+
+ registerSubcommands(root)
+ return root
+}
+
+// registerSubcommands wires each top-level subcommand group on the root.
+// Adding a new group (e.g. `prompts`) is one line here plus a new package
+// under cli/internal/<group>/.
+func registerSubcommands(root *cobra.Command) {
+ root.AddCommand(coding.NewCmd())
+ root.AddCommand(configure.NewCmd())
+ root.AddCommand(doctor.NewCmd())
+ root.AddCommand(version.NewCmd())
+
+ // Future slots — left here intentionally as comments so contributors
+ // can see the shape we're building toward without scaffolding empty
+ // subtrees that confuse code search:
+ //
+ // root.AddCommand(prompts.NewCmd()) // openlit prompts {pull,push,list,diff}
+ // root.AddCommand(traces.NewCmd()) // openlit traces {tail,query,export}
+ // root.AddCommand(eval.NewCmd()) // openlit eval {run,list}
+ // root.AddCommand(migrate.NewCmd()) // openlit migrate
+ // root.AddCommand(fleet.NewCmd()) // openlit fleet {status,list}
+}
diff --git a/cli/gen/doc.go b/cli/gen/doc.go
new file mode 100644
index 00000000..e9f365f5
--- /dev/null
+++ b/cli/gen/doc.go
@@ -0,0 +1,5 @@
+// Package gen holds generated artifacts consumed by the dashboard
+// (`semconv.ts`). The Go source of truth lives in sdk/go/semconv/.
+//
+//go:generate go run ../internal/semconvgen
+package gen
diff --git a/cli/gen/semconv.ts b/cli/gen/semconv.ts
new file mode 100644
index 00000000..fd9b6df5
--- /dev/null
+++ b/cli/gen/semconv.ts
@@ -0,0 +1,359 @@
+// Code generated by cli/internal/semconvgen. DO NOT EDIT.
+// Source: sdk/go/semconv/coding_agent.go
+//
+// Run `go generate ./...` from the cli/ module to regenerate.
+
+// Vendor identifiers (used as `gen_ai.agent.name` value).
+export const CodingAgentVendorClaudeCode = "claude-code";
+
+export const CodingAgentVendorCursor = "cursor";
+
+export const CodingAgentVendorCodex = "codex";
+
+export const CodingAgentVendorWindsurf = "windsurf";
+
+// CodingAgentSessionID identifies a single coding-agent session.
+// Used as the join key across all spans/events emitted for that session.
+export const CodingAgentSessionID = "coding_agent.session.id";
+
+// CodingAgentClient is the vendor identifier; mirror of gen_ai.agent.name.
+// Carried separately so dashboard widgets can filter without
+// pulling in the full gen_ai.* attribute set.
+export const CodingAgentClient = "coding_agent.client";
+
+// CodingAgentClientVersion is the vendor's client version.
+export const CodingAgentClientVersion = "coding_agent.client.version";
+
+// CodingAgentSessionOutcome captures how the session ended.
+// One of: merged | committed | abandoned_no_change | abandoned_with_change | cancelled.
+export const CodingAgentSessionOutcome = "coding_agent.session.outcome";
+
+// CodingAgentSessionDurationMs is wall-clock duration in milliseconds.
+export const CodingAgentSessionDurationMs = "coding_agent.session.duration_ms";
+
+// CodingAgentSessionToolCallCount totals tool invocations during the session.
+export const CodingAgentSessionToolCallCount = "coding_agent.session.tool_call_count";
+
+// CodingAgentSessionSubagentCount totals child/subagent spawns.
+export const CodingAgentSessionSubagentCount = "coding_agent.session.subagent_count";
+
+// CodingAgentSessionCostUSD is the realized USD cost.
+export const CodingAgentSessionCostUSD = "coding_agent.session.cost_usd";
+
+// Per-session code-change rollups stamped on the
+// `coding_agent.session` root span at SessionEnd. They aggregate
+// edit / accept / reject / line counts the adapter observed
+// across the session so dashboards don't have to fan out into
+// every `coding_agent.edit.decision` span.
+//
+// Mirrors Claude Code's native `claude_code.lines_of_code.count`
+// metric shape — when the operator ships both paths (hook + native
+// OTel exporter), the query layer coalesces.
+export const CodingAgentSessionLinesAdded = "coding_agent.session.lines.added";
+
+// Session structure attributes.
+export const CodingAgentSessionLinesRemoved = "coding_agent.session.lines.removed";
+
+export const CodingAgentSessionLinesAccepted = "coding_agent.session.lines.accepted";
+
+export const CodingAgentSessionLinesRejected = "coding_agent.session.lines.rejected";
+
+export const CodingAgentSessionEditAcceptCount = "coding_agent.session.edit.accept_count";
+
+export const CodingAgentSessionEditRejectCount = "coding_agent.session.edit.reject_count";
+
+export const CodingAgentSessionCommitCount = "coding_agent.session.commit_count";
+
+export const CodingAgentSessionPRCount = "coding_agent.session.pr_count";
+
+// CodingAgentSessionOutcomeCompleted — the agent reported a
+// successful end of the session (Cursor's reason="completed",
+// Claude Code's "stop", etc). The user may or may not have
+// merged anything; we stay agnostic on downstream VCS state.
+export const CodingAgentSessionOutcomeCompleted = "completed";
+
+// Session outcome values.
+export const CodingAgentSessionOutcomeMerged = "merged";
+
+export const CodingAgentSessionOutcomeCommitted = "committed";
+
+export const CodingAgentSessionOutcomeAbandonedNoChange = "abandoned_no_change";
+
+export const CodingAgentSessionOutcomeAbandonedWithChange = "abandoned_with_change";
+
+export const CodingAgentSessionOutcomeCancelled = "cancelled";
+
+// CodingAgentAgentID is a stable id for this agent instance within the
+// session (root or subagent). Use parent_id to walk the tree.
+export const CodingAgentAgentID = "coding_agent.agent.id";
+
+// CodingAgentAgentParentID points at the spawning agent's id.
+export const CodingAgentAgentParentID = "coding_agent.agent.parent_id";
+
+// CodingAgentAgentType is one of: main | subagent | task_tool.
+export const CodingAgentAgentType = "coding_agent.agent.type";
+
+// CodingAgentSubagentType is the vendor-specific subagent kind
+// (e.g. Claude Code's named subagents, Codex spawn types).
+export const CodingAgentSubagentType = "coding_agent.subagent.type";
+
+// CodingAgentLinkageConfidence reports how reliable the parent_id
+// linkage is for this vendor: high | medium | low.
+// Codex subagent linkage is often medium because parent is
+// inferred via process metadata rather than carried by the protocol.
+export const CodingAgentLinkageConfidence = "coding_agent.linkage_confidence";
+
+export const CodingAgentAgentTypeMain = "main";
+
+export const CodingAgentAgentTypeSubagent = "subagent";
+
+export const CodingAgentAgentTypeTaskTool = "task_tool";
+
+export const CodingAgentLinkageConfidenceHigh = "high";
+
+export const CodingAgentLinkageConfidenceMedium = "medium";
+
+export const CodingAgentLinkageConfidenceLow = "low";
+
+// CodingAgentEditDecision is one of: accept | reject | modify | auto_accepted.
+export const CodingAgentEditDecision = "coding_agent.edit.decision";
+
+// CodingAgentEditDecisionSource is the trigger:
+// user_interactive | user_permanent_rule | hook | config | policy.
+export const CodingAgentEditDecisionSource = "coding_agent.edit.decision.source";
+
+// CodingAgentEditLinesAdded is the count of added lines.
+export const CodingAgentEditLinesAdded = "coding_agent.edit.lines.added";
+
+// CodingAgentEditLinesRemoved is the count of removed lines.
+export const CodingAgentEditLinesRemoved = "coding_agent.edit.lines.removed";
+
+// CodingAgentEditLanguage is the detected programming language.
+export const CodingAgentEditLanguage = "coding_agent.edit.language";
+
+// CodingAgentEditToolName is the tool that produced the edit
+// (e.g. "Edit", "Write", "Apply Patch").
+export const CodingAgentEditToolName = "coding_agent.edit.tool.name";
+
+export const CodingAgentEditDecisionAccept = "accept";
+
+export const CodingAgentEditDecisionReject = "reject";
+
+export const CodingAgentEditDecisionModify = "modify";
+
+export const CodingAgentEditDecisionAutoAccepted = "auto_accepted";
+
+export const CodingAgentEditDecisionSourceUserInteractive = "user_interactive";
+
+export const CodingAgentEditDecisionSourceUserPermanentRule = "user_permanent_rule";
+
+export const CodingAgentEditDecisionSourceHook = "hook";
+
+export const CodingAgentEditDecisionSourceConfig = "config";
+
+export const CodingAgentEditDecisionSourcePolicy = "policy";
+
+// CodingAgentToolTriggeringLLMRequestID is the LLM response id
+// whose tool_calls produced this invocation.
+export const CodingAgentToolTriggeringLLMRequestID = "coding_agent.tool.triggering_llm_request_id";
+
+// CodingAgentToolIteration is the loop index for retried/iterated tools.
+export const CodingAgentToolIteration = "coding_agent.tool.iteration";
+
+// CodingAgentToolGroupID groups tools fired in the same model turn.
+export const CodingAgentToolGroupID = "coding_agent.tool.group.id";
+
+// CodingAgentToolGroupType describes the group's intent
+// (e.g. "file_edit", "search", "bash").
+export const CodingAgentToolGroupType = "coding_agent.tool.group.type";
+
+// CodingAgentMCPServerName is the MCP server identifier.
+export const CodingAgentMCPServerName = "coding_agent.mcp.server.name";
+
+// CodingAgentMCPScope is one of: user | project | local | enterprise.
+export const CodingAgentMCPScope = "coding_agent.mcp.scope";
+
+// CodingAgentMCPTransport is one of: stdio | sse | streamable_http.
+export const CodingAgentMCPTransport = "coding_agent.mcp.transport";
+
+// CodingAgentMCPSource is one of: builtin | plugin | marketplace.
+export const CodingAgentMCPSource = "coding_agent.mcp.source";
+
+export const CodingAgentMCPScopeUser = "user";
+
+export const CodingAgentMCPScopeProject = "project";
+
+export const CodingAgentMCPScopeLocal = "local";
+
+export const CodingAgentMCPScopeEnterprise = "enterprise";
+
+export const CodingAgentMCPTransportStdio = "stdio";
+
+export const CodingAgentMCPTransportSSE = "sse";
+
+export const CodingAgentMCPTransportStreamableHTTP = "streamable_http";
+
+export const CodingAgentMCPSourceBuiltin = "builtin";
+
+export const CodingAgentMCPSourcePlugin = "plugin";
+
+export const CodingAgentMCPSourceMarketplace = "marketplace";
+
+// CodingAgentVCSDirty indicates the working tree has uncommitted changes
+// when the agent started. Boolean serialized as "true"/"false".
+export const CodingAgentVCSDirty = "coding_agent.vcs.dirty";
+
+// CodingAgentUserClassification is one of: personal | work | disputed | unknown.
+// Stamped at hook-time using API-key allowlist + repo-origin allowlist.
+export const CodingAgentUserClassification = "coding_agent.user.classification";
+
+// CodingAgentUserClassificationReason explains the classification
+// (e.g. "api_key_allowlist", "repo_origin_match", "no_signal").
+export const CodingAgentUserClassificationReason = "coding_agent.user.classification.reason";
+
+// CodingAgentPolicyPermissionMode captures how permissive the run is
+// (e.g. "interactive", "auto_accept", "dangerously_skip_permissions").
+export const CodingAgentPolicyPermissionMode = "coding_agent.policy.permission_mode";
+
+// CodingAgentContentCaptureMode is the active capture posture:
+// minimal | metadata_only | full. See `cli/internal/otlp/attrs.go`
+// for the per-mode attribute matrix.
+export const CodingAgentContentCaptureMode = "coding_agent.content_capture_mode";
+
+export const CodingAgentUserClassificationPersonal = "personal";
+
+export const CodingAgentUserClassificationWork = "work";
+
+export const CodingAgentUserClassificationDisputed = "disputed";
+
+export const CodingAgentUserClassificationUnknown = "unknown";
+
+// CodingAgentContentCaptureMinimal — only session bookends and
+// rolled-up counters. No per-event spans. Cheapest tier; for
+// enterprises that want budget visibility without per-prompt
+// content. See Phase C of the coding-agents plan.
+export const CodingAgentContentCaptureMinimal = "minimal";
+
+// CodingAgentContentCaptureMetadataOnly — per-event spans with
+// counts/timings/cost/repo but redacted bodies (no prompts, no
+// tool args, no shell flags). Recommended default.
+export const CodingAgentContentCaptureMetadataOnly = "metadata_only";
+
+// CodingAgentContentCaptureFull — everything metadata mode has
+// plus prompts, responses, thoughts, tool args, tool results.
+// Tier-2 PII redaction still runs. For trust+safety reviews.
+export const CodingAgentContentCaptureFull = "full";
+
+// CodingAgentLoopDetected is true when an in-session loop is detected.
+export const CodingAgentLoopDetected = "coding_agent.loop.detected";
+
+// CodingAgentLoopPattern names the pattern (e.g. "edit_revert_edit",
+// "tool_retry").
+export const CodingAgentLoopPattern = "coding_agent.loop.pattern";
+
+// CodingAgentHookEvent names the originating hook event (e.g. "PreToolUse").
+export const CodingAgentHookEvent = "coding_agent.hook.event";
+
+// CodingAgentHookCLIVersion identifies the openlit CLI version.
+export const CodingAgentHookCLIVersion = "coding_agent.hook.cli.version";
+
+// CodingAgentHookSchemaVersion is the wire-format schema version.
+// Bump when a breaking change is necessary; receivers read this to
+// stay forward-compatible with the latest CLIs.
+export const CodingAgentHookSchemaVersion = "coding_agent.hook.schema.version";
+
+// Span names emitted by the CLI normalizer. Keep these as constants so
+// dashboard SQL can match against a small, stable set.
+export const CodingAgentSpanSession = "coding_agent.session";
+
+export const CodingAgentSpanToolCall = "coding_agent.tool.call";
+
+export const CodingAgentSpanEditDecision = "coding_agent.edit.decision";
+
+export const CodingAgentSpanSubagent = "coding_agent.subagent";
+
+export const CodingAgentSpanLLMTurn = "coding_agent.llm.turn";
+
+// CodingAgentSpanGitCommit is emitted when the agent's Bash /
+// shell tool ran a `git commit` invocation. One span per detected
+// commit, child of the session-root trace.
+export const CodingAgentSpanGitCommit = "coding_agent.git.commit";
+
+// CodingAgentSpanGitPullRequest is emitted when the agent's
+// Bash / shell tool created a pull / merge request (`gh pr
+// create`, `git push -u origin <branch>` that produced a PR URL,
+// etc.).
+export const CodingAgentSpanGitPullRequest = "coding_agent.git.pull_request";
+
+// Git commit / pull-request attributes — attached to the matching
+// `coding_agent.git.commit` / `coding_agent.git.pull_request` span.
+// The body-bearing values (commit message, PR title) are stamped only
+// under `full` content capture; the SHA / URL / number are always
+// safe to stamp.
+export const CodingAgentGitCommitSHA = "coding_agent.git.commit.sha";
+
+export const CodingAgentGitCommitMessage = "coding_agent.git.commit.message";
+
+export const CodingAgentGitPRURL = "coding_agent.git.pull_request.url";
+
+export const CodingAgentGitPRNumber = "coding_agent.git.pull_request.number";
+
+export const CodingAgentGitPRTitle = "coding_agent.git.pull_request.title";
+
+// Event names — emitted as span events for high-cardinality moments
+// where a separate span would be overkill.
+export const CodingAgentEventSessionStart = "coding_agent.session.start";
+
+export const CodingAgentEventSessionEnd = "coding_agent.session.end";
+
+export const CodingAgentEventEditDecision = "coding_agent.edit.decision";
+
+export const CodingAgentEventLoopDetected = "coding_agent.loop.detected";
+
+export const CodingAgentEventSubagentSpawned = "coding_agent.subagent.spawned";
+
+export const CodingAgentEventSubagentDone = "coding_agent.subagent.completed";
+
+export const CodingAgentEventMCPInvoked = "coding_agent.mcp.tool.invoked";
+
+// Metric names — additions on top of gen_ai.* metrics.
+//
+// The `coding_agent.lines_of_code.count`, `coding_agent.code_edit_tool.decision`,
+// `coding_agent.commit.count`, and `coding_agent.pull_request.count`
+// counters mirror Claude Code's native exporter shape
+// (`claude_code.lines_of_code.count` …) under our canonical namespace.
+// They are emitted alongside the matching span so backends that consume
+// metrics (Prometheus / Mimir) see the same numbers traces backends do.
+export const CodingAgentMetricSessionDuration = "coding_agent.session.duration";
+
+export const CodingAgentMetricSessionCostUSD = "coding_agent.session.cost_usd";
+
+export const CodingAgentMetricSessionToolCalls = "coding_agent.session.tool_call_count";
+
+export const CodingAgentMetricSessionSubagents = "coding_agent.session.subagent_count";
+
+export const CodingAgentMetricToolDuration = "coding_agent.tool.duration";
+
+export const CodingAgentMetricEditDecisions = "coding_agent.edit.decision.count";
+
+// CodingAgentMetricLinesOfCode is a counter of added / removed
+// lines tagged with `type=added|removed`, `decision`, `vendor`, `user`.
+export const CodingAgentMetricLinesOfCode = "coding_agent.lines_of_code.count";
+
+// CodingAgentMetricEditDecisionCnt is a counter of edit
+// decisions tagged with `decision`, `vendor`, `tool_name`,
+// `language`, `user`. Renamed under our namespace from
+// `claude_code.code_edit_tool.decision`.
+export const CodingAgentMetricEditDecisionCnt = "coding_agent.code_edit_tool.decision";
+
+// CodingAgentMetricCommit is a counter of agent-attributed
+// git commits tagged with `vendor`, `user`.
+export const CodingAgentMetricCommit = "coding_agent.commit.count";
+
+// CodingAgentMetricPullRequest is a counter of agent-attributed
+// pull / merge requests tagged with `vendor`, `user`.
+export const CodingAgentMetricPullRequest = "coding_agent.pull_request.count";
+
+// Schema version of the coding_agent.* wire format. Bump on breaking changes.
+export const CodingAgentSchemaVersion = "1";
+
diff --git a/cli/go.mod b/cli/go.mod
new file mode 100644
index 00000000..34070f9d
--- /dev/null
+++ b/cli/go.mod
@@ -0,0 +1,38 @@
+module github.com/openlit/openlit/cli
+
+go 1.25.0
+
+require (
+ github.com/openlit/openlit/sdk/go v0.0.0
+ github.com/spf13/cobra v1.10.1
+ go.opentelemetry.io/otel v1.43.0
+ go.opentelemetry.io/otel/metric v1.43.0
+ go.opentelemetry.io/otel/sdk v1.43.0
+ go.opentelemetry.io/otel/trace v1.43.0
+ golang.org/x/sys v0.42.0
+)
+
+require (
+ github.com/cenkalti/backoff/v5 v5.0.3 // indirect
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/go-logr/logr v1.4.3 // indirect
+ github.com/go-logr/stdr v1.2.2 // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/spf13/pflag v1.0.9 // indirect
+ go.opentelemetry.io/auto/sdk v1.2.1 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 // indirect
+ go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
+ go.opentelemetry.io/proto/otlp v1.10.0 // indirect
+ golang.org/x/net v0.52.0 // indirect
+ golang.org/x/text v0.35.0 // indirect
+ google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
+ google.golang.org/grpc v1.80.0 // indirect
+ google.golang.org/protobuf v1.36.11 // indirect
+)
+
+replace github.com/openlit/openlit/sdk/go => ../sdk/go
diff --git a/cli/go.sum b/cli/go.sum
new file mode 100644
index 00000000..e6e11ea7
--- /dev/null
+++ b/cli/go.sum
@@ -0,0 +1,72 @@
+github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
+github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s=
+github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0=
+github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
+go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
+go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
+go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0 h1:w1K+pCJoPpQifuVpsKamUdn9U0zM3xUziVOqsGksUrY=
+go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0/go.mod h1:HBy4BjzgVE8139ieRI75oXm3EcDN+6GhD88JT1Kjvxg=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 h1:3iZJKlCZufyRzPzlQhUIWVmfltrXuGyfjREgGP3UUjc=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0/go.mod h1:/G+nUPfhq2e+qiXMGxMwumDrP5jtzU+mWN7/sjT2rak=
+go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
+go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
+go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
+go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
+go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
+go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
+go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
+go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
+go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
+go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
+golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
+golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
+golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
+golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
+golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
+google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA=
+google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 h1:m8qni9SQFH0tJc1X0vmnpw/0t+AImlSvp30sEupozUg=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM=
+google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4=
+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/cli/internal/coding/classify/classify.go b/cli/internal/coding/classify/classify.go
new file mode 100644
index 00000000..9503b63d
--- /dev/null
+++ b/cli/internal/coding/classify/classify.go
@@ -0,0 +1,182 @@
+// Package classify decides whether a coding-agent session is "work" or
+// "personal" based on high-confidence signals only.
+//
+// Two inputs:
+//
+// 1. API-key identity. If the openlit API key sending this telemetry
+// is on the org's allowlist (configured in OpenLit's settings),
+// the user is recognized as a work identity.
+//
+// 2. Repo origin. If the repo's remote URL matches one of the org's
+// allowlist patterns (e.g. github.com/our-org/*), the code is
+// work code.
+//
+// Surveillance-grade signals (keystroke timing, hours-of-day) explicitly
+// NOT used. The classification reason is stamped alongside the
+// classification so users can see why and dispute it.
+package classify
+
+import (
+ "strings"
+)
+
+// Classification is the result for one session.
+type Classification struct {
+ Value string // "work" | "personal" | "disputed" | "unknown"
+ Reason string // human-readable signal name, e.g. "api_key_allowlist+repo_origin_match"
+}
+
+// Inputs are the signals we have at hook time.
+//
+// Both API-key fields are tristate-encoded across two booleans to avoid
+// the classic "is `false` an answer or a missing signal?" ambiguity:
+//
+// - APIKeyAllowlistKnown=false → we don't know either way. Treat the
+// API-key signal as absent and lean on the repo signal.
+// - APIKeyAllowlistKnown=true → APIKeyOnAllowlist is authoritative.
+type Inputs struct {
+ // APIKeyOnAllowlist is true when the request's API key is
+ // registered as a "work identity" at the OpenLit deployment.
+ // Only meaningful when APIKeyAllowlistKnown is also true.
+ //
+ // In v1 the CLI cannot determine this on its own — there is no
+ // path from the local hook to the org's API-key allowlist — so
+ // per-vendor adapters set both fields to false and the classifier
+ // falls back to the repo signal. The server-side classifier in
+ // src/client/src/lib/platform/coding-agents/ may re-classify
+ // authoritatively once the org has registered its keys.
+ APIKeyOnAllowlist bool
+
+ // APIKeyAllowlistKnown distinguishes "we asked and the key is not
+ // on the allowlist" (true + false) from "we have no way to know
+ // yet" (false). Without this flag the classifier would treat
+ // "no allowlist infrastructure" the same as "key explicitly
+ // rejected", which produced a regression where every session
+ // ended up labelled `personal` regardless of repo origin.
+ APIKeyAllowlistKnown bool
+
+ // RepoURL is the canonical remote URL collected by internal/coding/git.
+ // May be empty if the session ran outside any repo.
+ RepoURL string
+
+ // RepoAllowlist is the user's local override for "what counts as
+ // my work repo". Read from OPENLIT_CODING_REPO_ALLOWLIST as a
+ // comma-separated list of substring patterns. Authoritative
+ // allowlists live server-side; this is just a hint the CLI
+ // stamps so the dashboard can pre-classify before the server
+ // re-classifies.
+ RepoAllowlist []string
+}
+
+// Classify returns the work/personal/disputed/unknown classification.
+//
+// Design constraints:
+//
+// - We must NEVER classify a session as "personal" without explicit
+// evidence of a non-work signal. "no API-key allowlist configured"
+// is NOT evidence — it's an absence of signal.
+// - "no_signal" must be distinguishable from "explicit allowlist
+// mismatch" so the dashboard can render them differently.
+// - When only one of the two signals (API key, repo origin) is
+// authoritative, we still produce the best classification that
+// signal supports rather than defaulting to "unknown".
+// - Authoritative classification happens server-side; the CLI's job
+// is to stamp the strongest signal it observed locally so the UI
+// can pre-classify before the server's allowlist is applied.
+func Classify(in Inputs) Classification {
+ repoMatch := matchAllowlist(in.RepoURL, in.RepoAllowlist)
+ hasRepoAllowlist := len(in.RepoAllowlist) > 0
+ hasRepo := in.RepoURL != ""
+ keyKnown := in.APIKeyAllowlistKnown
+ keyAllow := in.APIKeyAllowlistKnown && in.APIKeyOnAllowlist
+ keyDeny := in.APIKeyAllowlistKnown && !in.APIKeyOnAllowlist
+
+ // Strongest signal: both allowlists agree this is work.
+ if keyAllow && repoMatch {
+ return Classification{Value: "work", Reason: "api_key_allowlist+repo_origin_match"}
+ }
+
+ // API key allowlisted but no repo (running outside any git tree).
+ if keyAllow && !hasRepo {
+ return Classification{Value: "work", Reason: "api_key_allowlist_only"}
+ }
+
+ // Conflict: work identity on a non-allowlisted repo. This could
+ // mean the engineer is running corp keys on a personal repo, OR
+ // that the allowlist is simply missing entries. We do NOT classify
+ // as personal here — that's the call the dispute UI exists to
+ // resolve. The reason makes the conflict legible on the dashboard.
+ if keyAllow && hasRepo && hasRepoAllowlist && !repoMatch {
+ return Classification{Value: "unknown", Reason: "api_key_work_on_non_allowlisted_repo"}
+ }
+
+ // Personal-on-work: identity is positively NOT on the API-key
+ // allowlist (and we know that because keyKnown=true), but the repo
+ // is. Only meaningful when an API-key allowlist actually exists;
+ // otherwise we can't make this call without false-flagging every
+ // session.
+ if keyDeny && repoMatch {
+ return Classification{Value: "personal", Reason: "api_key_personal_on_work_repo"}
+ }
+
+ // Repo IS on allowlist and the API-key allowlist is unknown — this
+ // is the common v1 case (no API-key allowlist infrastructure yet).
+ // The repo signal is strong on its own: the user has explicitly
+ // declared this remote as a work repo via OPENLIT_CODING_REPO_ALLOWLIST.
+ if repoMatch && !keyKnown {
+ return Classification{Value: "work", Reason: "repo_origin_match"}
+ }
+
+ // Repo URL exists, allowlist exists, and the URL did not match: the
+ // org has explicitly declared this repo non-work. This is the
+ // only branch where "personal" is safe without API-key data.
+ if hasRepo && hasRepoAllowlist && !repoMatch {
+ return Classification{Value: "personal", Reason: "repo_origin_no_match"}
+ }
+
+ // Nothing actionable: either no repo at all and no API key, or the
+ // only signal we have is "API key allowlist is unknown" without an
+ // allowlist to compare against. Don't pretend confidence.
+ if !hasRepo && !keyKnown {
+ return Classification{Value: "unknown", Reason: "no_signal"}
+ }
+ if hasRepo && !hasRepoAllowlist {
+ return Classification{Value: "unknown", Reason: "no_repo_allowlist_configured"}
+ }
+ return Classification{Value: "unknown", Reason: "ambiguous"}
+}
+
+// matchAllowlist returns true if any allowlist substring is present in url.
+// Patterns are matched case-insensitively against the bare URL.
+func matchAllowlist(url string, patterns []string) bool {
+ if url == "" || len(patterns) == 0 {
+ return false
+ }
+ low := strings.ToLower(url)
+ for _, p := range patterns {
+ p = strings.ToLower(strings.TrimSpace(p))
+ if p == "" {
+ continue
+ }
+ if strings.Contains(low, p) {
+ return true
+ }
+ }
+ return false
+}
+
+// SplitAllowlist parses the comma-separated form of OPENLIT_CODING_REPO_ALLOWLIST.
+func SplitAllowlist(s string) []string {
+ if s == "" {
+ return nil
+ }
+ parts := strings.Split(s, ",")
+ out := make([]string, 0, len(parts))
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if p != "" {
+ out = append(out, p)
+ }
+ }
+ return out
+}
diff --git a/cli/internal/coding/classify/classify_test.go b/cli/internal/coding/classify/classify_test.go
new file mode 100644
index 00000000..e166d449
--- /dev/null
+++ b/cli/internal/coding/classify/classify_test.go
@@ -0,0 +1,149 @@
+package classify
+
+import "testing"
+
+func TestClassify(t *testing.T) {
+ cases := []struct {
+ name string
+ in Inputs
+ want string
+ wantReason string
+ }{
+ {
+ name: "no_signal",
+ in: Inputs{},
+ want: "unknown",
+ wantReason: "no_signal",
+ },
+ {
+ // Strongest signal: API-key allowlist + repo origin both
+ // agree.
+ name: "work_full_match",
+ in: Inputs{
+ APIKeyAllowlistKnown: true,
+ APIKeyOnAllowlist: true,
+ RepoURL: "https://github.com/my-org/api.git",
+ RepoAllowlist: []string{"github.com/my-org/"},
+ },
+ want: "work",
+ wantReason: "api_key_allowlist+repo_origin_match",
+ },
+ {
+ name: "work_api_key_only",
+ in: Inputs{
+ APIKeyAllowlistKnown: true,
+ APIKeyOnAllowlist: true,
+ RepoURL: "",
+ },
+ want: "work",
+ wantReason: "api_key_allowlist_only",
+ },
+ {
+ // New v1 default path: no API-key allowlist infrastructure
+ // (APIKeyAllowlistKnown=false), but the user's repo IS on
+ // the allowlist. Repo signal is strong on its own — return
+ // "work" instead of falsely flagging "personal".
+ name: "work_repo_only_no_key_data",
+ in: Inputs{
+ APIKeyAllowlistKnown: false,
+ APIKeyOnAllowlist: false,
+ RepoURL: "https://github.com/my-org/api.git",
+ RepoAllowlist: []string{"github.com/my-org/"},
+ },
+ want: "work",
+ wantReason: "repo_origin_match",
+ },
+ {
+ // Repo URL exists, allowlist exists, and the URL did NOT
+ // match. Org has explicitly declared this repo non-work.
+ name: "personal_repo_not_on_allowlist",
+ in: Inputs{
+ APIKeyAllowlistKnown: false,
+ APIKeyOnAllowlist: false,
+ RepoURL: "https://github.com/random-user/side-project.git",
+ RepoAllowlist: []string{"github.com/my-org/"},
+ },
+ want: "personal",
+ wantReason: "repo_origin_no_match",
+ },
+ {
+ // Governance signal: API-key allowlist EXISTS and the key
+ // is positively NOT on it, but the user is committing to a
+ // work repo. Worth flagging.
+ name: "personal_api_on_work_repo",
+ in: Inputs{
+ APIKeyAllowlistKnown: true,
+ APIKeyOnAllowlist: false,
+ RepoURL: "https://github.com/my-org/api.git",
+ RepoAllowlist: []string{"github.com/my-org/"},
+ },
+ want: "personal",
+ wantReason: "api_key_personal_on_work_repo",
+ },
+ {
+ // Conflict: work identity (API-key allowlisted) on a
+ // non-allowlisted repo. Could be a missing entry or a
+ // genuine policy violation — let the dispute UI decide.
+ name: "ambiguous_api_on_unknown_repo",
+ in: Inputs{
+ APIKeyAllowlistKnown: true,
+ APIKeyOnAllowlist: true,
+ RepoURL: "https://github.com/random-user/side.git",
+ RepoAllowlist: []string{"github.com/my-org/"},
+ },
+ want: "unknown",
+ wantReason: "api_key_work_on_non_allowlisted_repo",
+ },
+ {
+ // Regression guard: this was the bug that motivated the
+ // rewrite. A user with OPENLIT_CODING_REPO_ALLOWLIST set to
+ // their work repo, NO API-key allowlist infrastructure, and
+ // committing to that very repo was getting labelled
+ // "personal" — exactly the opposite of the truth. Now
+ // returns "work" via the repo-only branch.
+ name: "regression_repo_only_no_key_known_returns_work_not_personal",
+ in: Inputs{
+ APIKeyAllowlistKnown: false,
+ APIKeyOnAllowlist: false,
+ RepoURL: "https://github.com/openlit/openlit.git",
+ RepoAllowlist: []string{"github.com/openlit/openlit"},
+ },
+ want: "work",
+ wantReason: "repo_origin_match",
+ },
+ {
+ // "Has repo but no allowlist configured" — we can't say
+ // either way. Don't pretend confidence.
+ name: "no_repo_allowlist_returns_unknown_not_personal",
+ in: Inputs{
+ APIKeyAllowlistKnown: false,
+ APIKeyOnAllowlist: false,
+ RepoURL: "https://github.com/anyone/anything.git",
+ RepoAllowlist: nil,
+ },
+ want: "unknown",
+ wantReason: "no_repo_allowlist_configured",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := Classify(tc.in)
+ if got.Value != tc.want {
+ t.Errorf("Classify(%+v).Value = %s; want %s (reason: %s)", tc.in, got.Value, tc.want, got.Reason)
+ }
+ if tc.wantReason != "" && got.Reason != tc.wantReason {
+ t.Errorf("Classify(%+v).Reason = %s; want %s", tc.in, got.Reason, tc.wantReason)
+ }
+ if got.Reason == "" {
+ t.Errorf("expected non-empty reason; got empty")
+ }
+ })
+ }
+}
+
+func TestSplitAllowlist(t *testing.T) {
+ got := SplitAllowlist("github.com/foo, github.com/bar , ,[email protected]:baz/")
+ if len(got) != 3 {
+ t.Errorf("expected 3 entries; got %v", got)
+ }
+}
diff --git a/cli/internal/coding/cmd.go b/cli/internal/coding/cmd.go
new file mode 100644
index 00000000..f4a78b36
--- /dev/null
+++ b/cli/internal/coding/cmd.go
@@ -0,0 +1,52 @@
+// Package coding hosts the `openlit coding ...` subcommand group.
+//
+// v1 ships the following children:
+//
+// openlit coding hook --vendor=cc|cursor|codex --event=...
+// openlit coding install --vendor=all|<single>
+// openlit coding uninstall --vendor=all|<single> [--purge]
+// openlit coding launch <claude|cursor|codex>
+//
+// All children share the resolved config from internal/config and the
+// OTLP exporter from internal/otlp. The hook subcommand is the hot path
+// invoked once per agent event and follows the crash-isolation rules
+// documented on cmd/openlit/main.go.
+package coding
+
+import (
+ "github.com/openlit/openlit/cli/internal/coding/hook"
+ "github.com/openlit/openlit/cli/internal/coding/install"
+ "github.com/openlit/openlit/cli/internal/coding/launch"
+ "github.com/openlit/openlit/cli/internal/coding/uninstall"
+ "github.com/spf13/cobra"
+)
+
+// NewCmd returns the `coding` cobra command tree.
+func NewCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "coding",
+ Short: "Coding-agent observability (Claude Code, Cursor, Codex)",
+ Long: `Send telemetry from AI coding agents into OpenLit.
+
+Three install paths land at the same plugin manifests under plugins/:
+ A) openlit coding launch <claude|cursor|codex> # one-liner
+ B) openlit coding install --vendor=all # write manifests, no agent TUI
+ C) From inside the agent: /plugin marketplace add openlit/openlit, then install.
+
+To stop tracking, use 'openlit coding uninstall --vendor=<v>' (add
+--purge to also drop ~/.config/openlit and the session-state cache).
+
+The 'hook' subcommand is invoked by the host plugin manifests once per
+agent event and is the hot path. It always exits 0 on telemetry-path
+failure so a broken pipeline never blocks a developer's prompt.`,
+ SilenceUsage: true,
+ SilenceErrors: true,
+ }
+
+ cmd.AddCommand(hook.NewCmd())
+ cmd.AddCommand(install.NewCmd())
+ cmd.AddCommand(uninstall.NewCmd())
+ cmd.AddCommand(launch.NewCmd())
+
+ return cmd
+}
diff --git a/cli/internal/coding/detect/detect.go b/cli/internal/coding/detect/detect.go
new file mode 100644
index 00000000..c95b10d7
--- /dev/null
+++ b/cli/internal/coding/detect/detect.go
@@ -0,0 +1,372 @@
+// Package detect contains tiny, dependency-free string helpers the
+// per-vendor hook adapters use to recognise high-signal patterns in
+// shell commands and code patches:
+//
+// - `git commit` invocations (and the SHA written to stdout)
+// - pull / merge request creation (`gh pr create`, the URL printed
+// by `git push -u origin <branch>`, GitLab equivalents)
+// - unified-diff patch bodies (apply_patch on Codex, MultiEdit on
+// Claude Code) → per-file lines-added / lines-removed
+// - inline before / after text diffs (Claude Code Edit, Cursor
+// afterFileEdit) → lines-added / lines-removed
+//
+// The helpers are best-effort by design: every vendor formats its
+// payload slightly differently, and the dashboards downstream prefer
+// "directionally honest" numbers over none. When in doubt the helpers
+// return zero and let the caller fall through to a vendor-specific
+// fallback.
+package detect
+
+import (
+ "regexp"
+ "strings"
+)
+
+// IsGitCommit reports whether `cmd` is (or contains) a `git commit`
+// invocation by the agent's shell tool. Recognises the common forms:
+//
+// git commit -m "..."
+// git commit --message="..."
+// GIT_EDITOR=true git commit
+// git -C subdir commit ...
+//
+// Quick exclusions:
+// - `git commit --help` / `-h`
+// - `git commit-tree` (plumbing; not a user commit)
+// - `git commit ... --dry-run`
+//
+// The match is intentionally loose — false positives only inflate the
+// commit count, never lose data. Dashboards rely on the SHA span
+// attribute being present to dedupe against repeated invocations.
+func IsGitCommit(cmd string) bool {
+ if cmd == "" {
+ return false
+ }
+ low := strings.ToLower(cmd)
+ if !strings.Contains(low, "git") || !strings.Contains(low, "commit") {
+ return false
+ }
+ if strings.Contains(low, "git commit-tree") {
+ return false
+ }
+ if strings.Contains(low, "--dry-run") {
+ return false
+ }
+ if strings.Contains(low, "--help") || gitCommitDashHRe.MatchString(low) {
+ return false
+ }
+ // Accept any token sequence that has `git ... commit` with
+ // optional `-C <dir>` / `-c key=val` between them. The simplest
+ // reliable form is a regex over the tokenised command.
+ return gitCommitRe.MatchString(low)
+}
+
+// gitCommitRe matches `git [opts] commit` allowing `-C <path>`,
+// `-c key=val`, and env-var prefixes before `git`.
+var gitCommitRe = regexp.MustCompile(`(?:^|\s|;|&&|\|\||\()(?:[a-z_][a-z0-9_]*=\S+\s+)*git(?:\s+-[cCp]\s+\S+|\s+--[a-zA-Z-]+(?:=\S+)?|\s+-[a-zA-Z]+)*\s+commit(?:\s|$|;|&&|\|\|)`)
+
+// gitCommitDashHRe matches `git commit -h` invocations and is checked
+// alongside `--help` to skip help-only commands. Compiled once at
+// package init — the previous in-function MustCompile cost ~200 ns
+// per IsGitCommit call on the shell hook hot path.
+var gitCommitDashHRe = regexp.MustCompile(`\bgit\s+commit\s+-h\b`)
+
+// shaRe matches a 7-40 char hex SHA, the common short / full forms
+// printed by `git commit`'s stdout (e.g. `[main 1a2b3c4] message`).
+var shaRe = regexp.MustCompile(`\b([0-9a-f]{7,40})\b`)
+
+// commitOutputSHARe captures the SHA from the typical commit summary
+// line: `[<branch> <sha>] <message>`.
+var commitOutputSHARe = regexp.MustCompile(`\[[^\]]+\s+([0-9a-f]{7,40})\]`)
+
+// ExtractCommitSHA pulls the commit SHA out of the stdout/stderr of a
+// completed `git commit` invocation. Returns "" when no SHA-shaped
+// token is present. Vendors that don't surface the tool's stdout
+// (Codex's `local_shell` aggregated output) end up with "" and the
+// emitter falls back to the at-emit timestamp.
+func ExtractCommitSHA(output string) string {
+ if output == "" {
+ return ""
+ }
+ if m := commitOutputSHARe.FindStringSubmatch(output); len(m) > 1 {
+ return m[1]
+ }
+ // `git commit-tree` style fallback — the SHA is the only token on
+ // the line. Walk the lines and return the first 7+ hex run that
+ // looks like a SHA (avoids matching long hex blobs in diff
+ // output).
+ for _, line := range strings.Split(output, "\n") {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+ if m := shaRe.FindStringSubmatch(line); len(m) > 1 {
+ // Heuristic: only accept if the SHA is the whole line
+ // OR the line starts with one (the common
+ // commit-tree output shape).
+ if line == m[1] || strings.HasPrefix(line, m[1]) {
+ return m[1]
+ }
+ }
+ }
+ return ""
+}
+
+// ExtractCommitMessage tries to recover the `-m`-supplied message
+// from a commit command. Returns "" when no quoted message is found.
+// This is best-effort and intentionally cheap — we don't try to
+// reconstruct heredoc-supplied or editor-supplied messages.
+func ExtractCommitMessage(cmd string) string {
+ if cmd == "" {
+ return ""
+ }
+ if m := firstGroup(dashMRe, cmd); m != "" {
+ return strings.TrimSpace(m)
+ }
+ if m := firstGroup(messageEqRe, cmd); m != "" {
+ return strings.TrimSpace(m)
+ }
+ return ""
+}
+
+// firstGroup returns the first non-empty capture group from
+// re.FindStringSubmatch(s). Lets us write one regex with several
+// quote-style alternatives and pick whichever matched.
+func firstGroup(re *regexp.Regexp, s string) string {
+ m := re.FindStringSubmatch(s)
+ for i := 1; i < len(m); i++ {
+ if m[i] != "" {
+ return m[i]
+ }
+ }
+ return ""
+}
+
+var (
+ dashMRe = regexp.MustCompile(`-m\s+(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|(\S+))`)
+ messageEqRe = regexp.MustCompile(`--message=(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|(\S+))`)
+)
+
+// IsPullRequest reports whether `cmd` is a PR / MR creation
+// invocation. Covers:
+//
+// - `gh pr create ...` (GitHub CLI)
+// - `gh pr create --base ...` etc.
+// - `glab mr create ...` (GitLab CLI)
+// - `tea pr create ...` (Gitea CLI)
+//
+// Closing / listing / viewing PRs are NOT counted — only creation.
+func IsPullRequest(cmd string) bool {
+ if cmd == "" {
+ return false
+ }
+ low := strings.ToLower(cmd)
+ if strings.Contains(low, "gh pr create") {
+ return true
+ }
+ if strings.Contains(low, "glab mr create") {
+ return true
+ }
+ if strings.Contains(low, "tea pr create") {
+ return true
+ }
+ return false
+}
+
+// prURLRe matches a typical GitHub / GitLab / Bitbucket PR/MR URL.
+// We accept the form printed by `gh pr create` (always full URL) and
+// by `git push -u origin <branch>` (PR-creation hint URL).
+var prURLRe = regexp.MustCompile(`https?://[^\s\)]+/(?:pull|pull-request|pull-requests|merge_requests|merge-requests|pulls)/(\d+)\b`)
+
+// prURLCompareRe matches the PR-create-hint URL git prints after
+// `git push -u origin <branch>` (`/pull/new/<branch>`) and the
+// GitLab "create new MR" URL (`-/merge_requests/new?...`).
+var prURLCompareRe = regexp.MustCompile(`https?://[^\s\)]+/(?:pull/new/\S+|compare/\S+|-/merge_requests/new\?\S+)`)
+
+// ExtractPRURLAndNumber returns the PR URL and number embedded in the
+// command's stdout/stderr. Returns ("",0) when no URL is found.
+func ExtractPRURLAndNumber(output string) (string, int) {
+ if output == "" {
+ return "", 0
+ }
+ if m := prURLRe.FindStringSubmatch(output); len(m) > 1 {
+ url := strings.TrimRight(m[0], ".,;:)")
+ var n int
+ for _, c := range m[1] {
+ if c < '0' || c > '9' {
+ break
+ }
+ n = n*10 + int(c-'0')
+ }
+ return url, n
+ }
+ if m := prURLCompareRe.FindStringSubmatch(output); len(m) > 0 {
+ return strings.TrimRight(m[0], ".,;:)"), 0
+ }
+ return "", 0
+}
+
+// ExtractPRTitle returns the value passed to `--title`, when present.
+// Best-effort, mirrors ExtractCommitMessage.
+func ExtractPRTitle(cmd string) string {
+ if cmd == "" {
+ return ""
+ }
+ if m := firstGroup(titleEqRe, cmd); m != "" {
+ return strings.TrimSpace(m)
+ }
+ if m := firstGroup(titleFlagRe, cmd); m != "" {
+ return strings.TrimSpace(m)
+ }
+ return ""
+}
+
+var (
+ titleEqRe = regexp.MustCompile(`--title=(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|(\S+))`)
+ titleFlagRe = regexp.MustCompile(`--title\s+(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|(\S+))`)
+)
+
+// PatchLineCounts is the output of CountPatchLines: per-file totals of
+// added / removed lines. The slice preserves the order the files
+// appeared in the patch so callers can attribute each file as its
+// own EditDecision.
+type PatchLineCounts struct {
+ FilePath string
+ LinesAdded int
+ LinesRemoved int
+}
+
+// CountPatchLines walks a unified-diff patch (the body Codex passes
+// to `apply_patch`, or the output of `git diff`) and returns one
+// row per file with added/removed line counts.
+//
+// Recognises both standard `diff --git a/x b/x` headers and the
+// `*** Update File: x` / `*** Add File: x` / `*** Delete File: x`
+// markers Codex's `apply_patch` uses.
+//
+// The counter ignores hunk header lines (`@@ ... @@`) and the patch
+// header lines themselves; only lines starting with `+` (added) or
+// `-` (removed) inside a hunk are counted.
+func CountPatchLines(patch string) []PatchLineCounts {
+ if patch == "" {
+ return nil
+ }
+ out := make([]PatchLineCounts, 0, 4)
+ var cur *PatchLineCounts
+ flush := func() {
+ if cur != nil {
+ out = append(out, *cur)
+ cur = nil
+ }
+ }
+ startFile := func(path string) {
+ flush()
+ cur = &PatchLineCounts{FilePath: path}
+ }
+ for _, line := range strings.Split(patch, "\n") {
+ switch {
+ case strings.HasPrefix(line, "diff --git "):
+ // `diff --git a/foo b/bar` — prefer the b/ side
+ fields := strings.Fields(line)
+ if len(fields) >= 4 {
+ startFile(stripABPrefix(fields[3]))
+ } else {
+ startFile("")
+ }
+ case strings.HasPrefix(line, "*** Update File: "):
+ startFile(strings.TrimSpace(strings.TrimPrefix(line, "*** Update File: ")))
+ case strings.HasPrefix(line, "*** Add File: "):
+ startFile(strings.TrimSpace(strings.TrimPrefix(line, "*** Add File: ")))
+ case strings.HasPrefix(line, "*** Delete File: "):
+ startFile(strings.TrimSpace(strings.TrimPrefix(line, "*** Delete File: ")))
+ case strings.HasPrefix(line, "+++ "):
+ // Standard unified-diff "to" header. Use it as the
+ // fallback file name if we never saw a `diff --git`.
+ if cur == nil || cur.FilePath == "" {
+ startFile(stripABPrefix(strings.TrimSpace(strings.TrimPrefix(line, "+++ "))))
+ }
+ case strings.HasPrefix(line, "--- "):
+ // "from" header — ignore; the `+++` header
+ // supersedes when present.
+ case strings.HasPrefix(line, "@@"):
+ // hunk header — skip
+ case strings.HasPrefix(line, "+") && !strings.HasPrefix(line, "+++"):
+ if cur == nil {
+ startFile("")
+ }
+ cur.LinesAdded++
+ case strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "---"):
+ if cur == nil {
+ startFile("")
+ }
+ cur.LinesRemoved++
+ }
+ }
+ flush()
+ return out
+}
+
+func stripABPrefix(s string) string {
+ if strings.HasPrefix(s, "a/") || strings.HasPrefix(s, "b/") {
+ return s[2:]
+ }
+ return s
+}
+
+// CountInlineDiff returns lines-added / lines-removed for a vendor's
+// "old text → new text" edit payload (Claude Code's Edit tool with
+// `old_string` + `new_string`; Cursor's afterFileEdit `before` /
+// `after`). The counts are line-based: the helper splits both blobs
+// into newline-delimited lines, drops trailing empty lines, and
+// counts the deltas.
+//
+// Empty `old` with non-empty `new` reports (len(new lines), 0). A
+// non-empty `old` with empty `new` reports (0, len(old lines)).
+// Otherwise: max(0, len(new)-len(old)) added, max(0,
+// len(old)-len(new)) removed.
+//
+// This is intentionally simple — not a true LCS diff — because the
+// hot path runs inside every PreToolUse / afterFileEdit hook
+// invocation and dashboards only need order-of-magnitude correctness.
+func CountInlineDiff(oldText, newText string) (added, removed int) {
+ oldLines := splitLines(oldText)
+ newLines := splitLines(newText)
+ switch {
+ case len(oldLines) == 0:
+ return len(newLines), 0
+ case len(newLines) == 0:
+ return 0, len(oldLines)
+ }
+ if d := len(newLines) - len(oldLines); d > 0 {
+ added = d
+ } else if d < 0 {
+ removed = -d
+ }
+ // For each in-range line that changed content, count it as
+ // add + remove pair so dashboards see real movement instead of
+ // "0 lines changed" when the edit is purely an in-place rewrite.
+ min := len(oldLines)
+ if len(newLines) < min {
+ min = len(newLines)
+ }
+ for i := 0; i < min; i++ {
+ if oldLines[i] != newLines[i] {
+ added++
+ removed++
+ }
+ }
+ return added, removed
+}
+
+func splitLines(s string) []string {
+ if s == "" {
+ return nil
+ }
+ // Strip a single trailing newline (common in shell-quoted blobs)
+ // before splitting so a value of `"a\n"` reports one line, not
+ // two ("a" + "").
+ if strings.HasSuffix(s, "\n") {
+ s = s[:len(s)-1]
+ }
+ return strings.Split(s, "\n")
+}
diff --git a/cli/internal/coding/detect/detect_test.go b/cli/internal/coding/detect/detect_test.go
new file mode 100644
index 00000000..e5b5b833
--- /dev/null
+++ b/cli/internal/coding/detect/detect_test.go
@@ -0,0 +1,186 @@
+package detect
+
+import "testing"
+
+func TestIsGitCommit(t *testing.T) {
+ cases := []struct {
+ in string
+ want bool
+ }{
+ {`git commit -m "fix bug"`, true},
+ {`git commit --message="fix bug"`, true},
+ {`GIT_EDITOR=true git commit`, true},
+ {`git -C subdir commit -m foo`, true},
+ {`git -c user.email=a@b commit -m foo`, true},
+ {`cd /tmp && git commit -m foo`, true},
+ {`git commit --dry-run`, false},
+ {`git commit --help`, false},
+ {`git commit-tree -m foo`, false},
+ {`git status`, false},
+ {``, false},
+ }
+ for _, c := range cases {
+ got := IsGitCommit(c.in)
+ if got != c.want {
+ t.Errorf("IsGitCommit(%q) = %v, want %v", c.in, got, c.want)
+ }
+ }
+}
+
+func TestExtractCommitSHA(t *testing.T) {
+ cases := []struct {
+ in string
+ want string
+ }{
+ {`[main 1a2b3c4] fix bug`, "1a2b3c4"},
+ {`[feature/foo abcdef0123456789] msg`, "abcdef0123456789"},
+ {`abc1234`, "abc1234"},
+ {`abc1234\n`, "abc1234"},
+ {`no commit info here`, ""},
+ {``, ""},
+ }
+ for _, c := range cases {
+ got := ExtractCommitSHA(c.in)
+ if got != c.want {
+ t.Errorf("ExtractCommitSHA(%q) = %q, want %q", c.in, got, c.want)
+ }
+ }
+}
+
+func TestExtractCommitMessage(t *testing.T) {
+ cases := []struct {
+ in, want string
+ }{
+ {`git commit -m "hello world"`, "hello world"},
+ {`git commit -m 'hi there'`, "hi there"},
+ {`git commit --message="docs: tweak"`, "docs: tweak"},
+ {`git commit -m bare`, "bare"},
+ {`git commit`, ""},
+ }
+ for _, c := range cases {
+ got := ExtractCommitMessage(c.in)
+ if got != c.want {
+ t.Errorf("ExtractCommitMessage(%q) = %q, want %q", c.in, got, c.want)
+ }
+ }
+}
+
+func TestIsPullRequest(t *testing.T) {
+ cases := []struct {
+ in string
+ want bool
+ }{
+ {`gh pr create --title "feat: x" --body "..."`, true},
+ {`gh pr create --base main`, true},
+ {`glab mr create --target-branch main`, true},
+ {`tea pr create --title foo`, true},
+ {`gh pr list`, false},
+ {`gh pr view 123`, false},
+ {``, false},
+ }
+ for _, c := range cases {
+ got := IsPullRequest(c.in)
+ if got != c.want {
+ t.Errorf("IsPullRequest(%q) = %v, want %v", c.in, got, c.want)
+ }
+ }
+}
+
+func TestExtractPRURLAndNumber(t *testing.T) {
+ cases := []struct {
+ in string
+ wantURL string
+ wantNum int
+ }{
+ {
+ in: `https://github.com/foo/bar/pull/123`,
+ wantURL: "https://github.com/foo/bar/pull/123",
+ wantNum: 123,
+ },
+ {
+ in: `Created: https://gitlab.com/foo/bar/-/merge_requests/45.`,
+ wantURL: "https://gitlab.com/foo/bar/-/merge_requests/45",
+ wantNum: 45,
+ },
+ {
+ in: `Visit https://github.com/foo/bar/compare/main...feat?expand=1 to create`,
+ wantURL: "https://github.com/foo/bar/compare/main...feat?expand=1",
+ wantNum: 0,
+ },
+ {
+ in: "no url",
+ wantURL: "",
+ wantNum: 0,
+ },
+ }
+ for _, c := range cases {
+ gotURL, gotNum := ExtractPRURLAndNumber(c.in)
+ if gotURL != c.wantURL || gotNum != c.wantNum {
+ t.Errorf("ExtractPRURLAndNumber(%q) = (%q, %d), want (%q, %d)", c.in, gotURL, gotNum, c.wantURL, c.wantNum)
+ }
+ }
+}
+
+func TestCountPatchLines(t *testing.T) {
+ patch := `*** Begin Patch
+*** Update File: a.txt
+@@ -1,2 +1,3 @@
+-old
++new1
++new2
+ ctx
+*** Add File: b.txt
++only_new
+*** End Patch
+`
+ got := CountPatchLines(patch)
+ if len(got) != 2 {
+ t.Fatalf("got %d files, want 2: %+v", len(got), got)
+ }
+ if got[0].FilePath != "a.txt" || got[0].LinesAdded != 2 || got[0].LinesRemoved != 1 {
+ t.Errorf("file[0] = %+v", got[0])
+ }
+ if got[1].FilePath != "b.txt" || got[1].LinesAdded != 1 || got[1].LinesRemoved != 0 {
+ t.Errorf("file[1] = %+v", got[1])
+ }
+}
+
+func TestCountPatchLinesUnifiedDiff(t *testing.T) {
+ patch := `diff --git a/x.go b/x.go
+index abc..def 100644
+--- a/x.go
++++ b/x.go
+@@ -1,3 +1,4 @@
+ keep
+-drop
++add1
++add2
+ keep2
+`
+ got := CountPatchLines(patch)
+ if len(got) != 1 {
+ t.Fatalf("got %d files, want 1: %+v", len(got), got)
+ }
+ if got[0].FilePath != "x.go" || got[0].LinesAdded != 2 || got[0].LinesRemoved != 1 {
+ t.Errorf("file[0] = %+v", got[0])
+ }
+}
+
+func TestCountInlineDiff(t *testing.T) {
+ cases := []struct {
+ old, new string
+ wantAdd, wantRemove int
+ }{
+ {"", "abc", 1, 0},
+ {"abc", "", 0, 1},
+ {"a\nb\nc\n", "a\nb\nc\nd\n", 1, 0},
+ {"a\nb\nc\n", "a\nx\nc\n", 1, 1},
+ {"", "", 0, 0},
+ }
+ for _, c := range cases {
+ add, rem := CountInlineDiff(c.old, c.new)
+ if add != c.wantAdd || rem != c.wantRemove {
+ t.Errorf("CountInlineDiff(%q,%q) = (%d,%d), want (%d,%d)", c.old, c.new, add, rem, c.wantAdd, c.wantRemove)
+ }
+ }
+}
diff --git a/cli/internal/coding/git/git.go b/cli/internal/coding/git/git.go
new file mode 100644
index 00000000..08190e2e
--- /dev/null
+++ b/cli/internal/coding/git/git.go
@@ -0,0 +1,157 @@
+// Package git collects the minimal VCS context every hook adapter
+// stamps on its spans (vcs.repository.url.full, vcs.ref.head.revision,
+// vcs.ref.head.name, coding_agent.vcs.dirty).
+//
+// Why we shell out to `git` rather than parse `.git/` ourselves: git's
+// CLI is universally installed on developer machines, handles edge
+// cases (worktrees, submodules, the GIT_DIR / GIT_WORK_TREE env vars),
+// and is a small fraction of the hook's overall budget. Each call here
+// has an explicit deadline; failures are silently dropped (we'd rather
+// emit a span without VCS context than wedge the hook).
+package git
+
+import (
+ "context"
+ "errors"
+ "net/url"
+ "os/exec"
+ "strings"
+ "time"
+)
+
+// perSubcommandBudget bounds how long any single `git` invocation can
+// take. The original hook deadline (a couple of seconds, see the
+// caller) is shared across roughly 4 git calls per Snapshot, so a
+// hung clone or a flaky filesystem can swallow the entire budget and
+// starve the actual span emission. 500ms is more than enough for a
+// healthy local repo and short enough that a hung call fails fast.
+const perSubcommandBudget = 500 * time.Millisecond
+
+// Context is the VCS snapshot captured at hook time. All fields are
+// best-effort — empty values mean "not in a repo" or "git not on PATH".
+type Context struct {
+ // RepoURL is the canonical remote URL (https://… or git@…), pulled
+ // from the configured upstream of HEAD or, failing that, `origin`.
+ RepoURL string
+ // HeadSHA is the full HEAD commit SHA.
+ HeadSHA string
+ // Branch is the current branch name; empty in detached-HEAD state.
+ Branch string
+ // Dirty is true if the working tree has uncommitted changes
+ // (porcelain output non-empty).
+ Dirty bool
+}
+
+// Empty reports whether the snapshot is entirely empty (no VCS context
+// available). Callers can use this to decide whether to stamp the
+// vcs.dirty boolean.
+func (c Context) Empty() bool {
+ return c.RepoURL == "" && c.HeadSHA == "" && c.Branch == ""
+}
+
+// Snapshot returns the VCS context for `dir`. If `dir` is empty, the
+// process's current working directory is used.
+func Snapshot(ctx context.Context, dir string) Context {
+ if _, err := exec.LookPath("git"); err != nil {
+ return Context{}
+ }
+
+ out := Context{}
+ out.HeadSHA = run(ctx, dir, "rev-parse", "HEAD")
+ out.Branch = strings.TrimSpace(run(ctx, dir, "rev-parse", "--abbrev-ref", "HEAD"))
+ if out.Branch == "HEAD" {
+ out.Branch = "" // detached HEAD
+ }
+
+ out.RepoURL = NormalizeRepoURL(remoteURL(ctx, dir))
+
+ // `git status --porcelain` is empty iff the worktree is clean.
+ if status := run(ctx, dir, "status", "--porcelain"); strings.TrimSpace(status) != "" {
+ out.Dirty = true
+ }
+ return out
+}
+
+// remoteURL prefers the upstream of HEAD; falls back to `origin`. Both
+// queries are cheap and non-network-touching.
+func remoteURL(ctx context.Context, dir string) string {
+ upstream := strings.TrimSpace(run(ctx, dir, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"))
+ if upstream != "" {
+ // upstream looks like "origin/main"; the remote is the prefix.
+ if i := strings.IndexByte(upstream, '/'); i > 0 {
+ remote := upstream[:i]
+ if url := strings.TrimSpace(run(ctx, dir, "remote", "get-url", remote)); url != "" {
+ return url
+ }
+ }
+ }
+ if url := strings.TrimSpace(run(ctx, dir, "remote", "get-url", "origin")); url != "" {
+ return url
+ }
+ return ""
+}
+
+// run executes a git subcommand in `dir` (or cwd if empty) and returns
+// stdout trimmed of trailing whitespace. Errors and non-zero exits map
+// to the empty string — git's stderr is intentionally ignored because
+// we never want to surface "fatal: not a git repository" to the user.
+//
+// Each invocation is wrapped in its own perSubcommandBudget so a
+// single hung call can't starve the surrounding hook deadline.
+func run(ctx context.Context, dir string, args ...string) string {
+ if ctx.Err() != nil {
+ return ""
+ }
+ subCtx, cancel := context.WithTimeout(ctx, perSubcommandBudget)
+ defer cancel()
+ cmd := exec.CommandContext(subCtx, "git", args...)
+ if dir != "" {
+ cmd.Dir = dir
+ }
+ out, err := cmd.Output()
+ if err != nil {
+ // Distinguish "not a repo" (exit code 128) from a real error
+ // only when we want to log; here we drop both to keep the
+ // hook silent on stderr.
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ return ""
+ }
+ return ""
+ }
+ return strings.TrimRight(string(out), "\n\r")
+}
+
+// NormalizeRepoURL coerces remote URLs to the canonical https form so
+// dashboards group sessions from `[email protected]:org/repo.git`,
+// `https://github.com/org/repo.git`, and `ssh://[email protected]/org/repo`
+// into the same VCS bucket. Returns the input untouched when it
+// doesn't look like a recognisable git URL.
+//
+// F10: this is the single source of truth — adapters call into here
+// rather than rolling their own normalisation.
+func NormalizeRepoURL(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return ""
+ }
+ // scp-style (`git@host:path`) — convert to https.
+ if !strings.Contains(raw, "://") && strings.Contains(raw, "@") && strings.Contains(raw, ":") {
+ at := strings.IndexByte(raw, '@')
+ colon := strings.IndexByte(raw[at+1:], ':')
+ if colon > 0 {
+ host := raw[at+1 : at+1+colon]
+ path := raw[at+1+colon+1:]
+ raw = "https://" + host + "/" + path
+ }
+ }
+ // Strip trailing .git so https://github.com/o/r and the same with
+ // .git produce identical keys.
+ if u, err := url.Parse(raw); err == nil && u.Scheme != "" {
+ u.Scheme = "https"
+ u.User = nil
+ u.Path = strings.TrimSuffix(u.Path, ".git")
+ return u.String()
+ }
+ return raw
+}
diff --git a/cli/internal/coding/git/git_test.go b/cli/internal/coding/git/git_test.go
new file mode 100644
index 00000000..5a4dc6f6
--- /dev/null
+++ b/cli/internal/coding/git/git_test.go
@@ -0,0 +1,86 @@
+package git
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+// initRepo runs git init + initial commit in dir.
+func initRepo(t *testing.T, dir string) {
+ t.Helper()
+ for _, args := range [][]string{
+ {"init", "-q", "-b", "main"},
+ {"config", "user.email", "[email protected]"},
+ {"config", "user.name", "Test User"},
+ } {
+ c := exec.Command("git", args...)
+ c.Dir = dir
+ if out, err := c.CombinedOutput(); err != nil {
+ t.Fatalf("git %v: %s: %v", args, out, err)
+ }
+ }
+ // Add a file and commit.
+ if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("# test\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ for _, args := range [][]string{
+ {"add", "README.md"},
+ {"commit", "-q", "-m", "init"},
+ } {
+ c := exec.Command("git", args...)
+ c.Dir = dir
+ if out, err := c.CombinedOutput(); err != nil {
+ t.Fatalf("git %v: %s: %v", args, out, err)
+ }
+ }
+}
+
+func TestSnapshotInRepo(t *testing.T) {
+ if _, err := exec.LookPath("git"); err != nil {
+ t.Skip("git not on PATH")
+ }
+ dir := t.TempDir()
+ initRepo(t, dir)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ got := Snapshot(ctx, dir)
+ if got.HeadSHA == "" {
+ t.Errorf("expected HeadSHA; got empty")
+ }
+ if got.Branch != "main" {
+ t.Errorf("expected branch=main; got %q", got.Branch)
+ }
+ if got.Dirty {
+ t.Errorf("expected clean worktree right after commit; got dirty=true")
+ }
+
+ // Make a working-tree change; expect Dirty=true.
+ if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("hello"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ got2 := Snapshot(ctx, dir)
+ if !got2.Dirty {
+ t.Errorf("expected dirty after untracked file; got false")
+ }
+}
+
+func TestSnapshotOutsideRepo(t *testing.T) {
+ if _, err := exec.LookPath("git"); err != nil {
+ t.Skip("git not on PATH")
+ }
+ dir := t.TempDir()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ got := Snapshot(ctx, dir)
+ if !got.Empty() {
+ t.Errorf("expected empty context outside repo; got %+v", got)
+ }
+}
diff --git a/cli/internal/coding/hook/claudecode/claudecode.go b/cli/internal/coding/hook/claudecode/claudecode.go
new file mode 100644
index 00000000..aa654efe
--- /dev/null
+++ b/cli/internal/coding/hook/claudecode/claudecode.go
@@ -0,0 +1,36 @@
+// Package claudecode implements the Claude Code hook adapter.
+//
+// Claude Code invokes the hook by name (SessionStart, UserPromptSubmit,
+// PreToolUse, PostToolUse, Stop, SubagentStop, SessionEnd) with a JSON
+// payload on stdin. We additionally tail the per-session transcript
+// file (`transcript_path` in the payload) for authoritative token
+// usage and cost on SessionEnd, and for an early model attribution on
+// SessionStart.
+//
+// Claude Code also exposes its own OTel exporter via
+// `CLAUDE_CODE_ENABLE_TELEMETRY=1`. When the user has both paths on,
+// the query layer dedupes per `session.id` (see
+// `.cursor/rules/coding-agents-convention.mdc` §5). This adapter is
+// responsible for the hook path only; it stamps
+// `coding_agent.signal_source = "hook"` (via the resource attribute
+// set in `cli/internal/otlp/exporter.go`) so the dual-path coalesce
+// can tell them apart.
+package claudecode
+
+import (
+ "context"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+// New returns a new Claude Code adapter.
+func New() normalize.Adapter { return &adapter{} }
+
+type adapter struct{}
+
+func (a *adapter) Vendor() string { return semconv.CodingAgentVendorClaudeCode }
+
+func (a *adapter) Handle(ctx context.Context, in normalize.Input) error {
+ return handle(ctx, in)
+}
diff --git a/cli/internal/coding/hook/claudecode/handle.go b/cli/internal/coding/hook/claudecode/handle.go
new file mode 100644
index 00000000..0fdfaf1f
--- /dev/null
+++ b/cli/internal/coding/hook/claudecode/handle.go
@@ -0,0 +1,983 @@
+package claudecode
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/classify"
+ "github.com/openlit/openlit/cli/internal/coding/detect"
+ "github.com/openlit/openlit/cli/internal/coding/git"
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/pricing"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/cli/internal/coding/tailfile"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+// claudePayload covers the fields Claude Code sends across all hook
+// events. Unknown fields are ignored. See
+// https://code.claude.com/docs/en/hooks for the event-level schema and
+// `.cursor/rules/coding-agents-convention.mdc` §4 for the mapping
+// onto our canonical attributes.
+type claudePayload struct {
+ SessionID string `json:"session_id"`
+ TranscriptPath string `json:"transcript_path"`
+ CWD string `json:"cwd"`
+ HookEventName string `json:"hook_event_name"`
+ PermissionMode string `json:"permission_mode"`
+ ToolName string `json:"tool_name"`
+ ToolUseID string `json:"tool_use_id"`
+ ToolInput json.RawMessage `json:"tool_input"`
+ ToolResponse json.RawMessage `json:"tool_response"`
+ StopHookActive bool `json:"stop_hook_active"`
+ Source string `json:"source"` // SessionStart subtypes (startup, resume, ...)
+ Reason string `json:"reason"` // SessionEnd reason
+
+ // UserPromptSubmit specific. Claude Code sends the entire user
+ // prompt verbatim on this event. We only stamp the body when
+ // content_capture_mode == "full" — otherwise just the length.
+ Prompt string `json:"prompt"`
+
+ // SubagentStop adds these (matcher + a short blurb). Documented
+ // at https://code.claude.com/docs/en/hooks#subagentstop-input.
+ SubagentType string `json:"subagent_type"`
+ TaskID string `json:"task_id"`
+}
+
+// handle is the per-invocation entry point. Claude Code passes events
+// over stdin; we route each event to a span emitter using the same
+// canonical types so the dashboard treats them uniformly.
+func handle(ctx context.Context, in normalize.Input) error {
+ var p claudePayload
+ if err := json.Unmarshal(in.Payload, &p); err != nil {
+ // Malformed payload — drop silently. The hook subcommand
+ // already logs the parse error to stderr above us.
+ return nil
+ }
+
+ event := in.Event
+ if event == "" {
+ event = p.HookEventName
+ }
+
+ vcs := git.Snapshot(ctx, p.CWD)
+ // See cursor/handle.go for the rationale — v1 has no API-key
+ // allowlist surface, so we flag the key signal as unknown.
+ cls := classify.Classify(classify.Inputs{
+ APIKeyAllowlistKnown: false,
+ APIKeyOnAllowlist: false,
+ RepoURL: vcs.RepoURL,
+ RepoAllowlist: classify.SplitAllowlist(os.Getenv("OPENLIT_CODING_REPO_ALLOWLIST")),
+ })
+
+ // Every event is a chance to drain new assistant turns from the
+ // transcript. Stop fires after every assistant turn, so this gives
+ // us per-turn LLM-turn spans (with output text + tokens) without
+ // waiting for SessionEnd. PreToolUse / PostToolUse also drain so
+ // long sessions don't accumulate unread tail.
+ drainAssistantTurns(in, p)
+
+ switch event {
+ case "SessionStart":
+ return emitSession(in, p, vcs, cls, "started", time.Time{})
+ case "UserPromptSubmit":
+ // Drain any leftover pending edits as rejections — Claude
+ // Code skipped the matching PostToolUse, which most often
+ // means the user denied the edit at the diff-review prompt
+ // and the assistant moved on. This is the same heuristic
+ // Anthropic's own monitoring docs describe under
+ // `claude_code.code_edit_tool.decision = reject`.
+ drainRejectedPendingEdits(in, p.SessionID)
+ return emitUserPrompt(in, p)
+ case "Stop":
+ // Stop fires after every assistant turn — many times per
+ // session. We emit a low-cost loop event here so dashboards
+ // can count turns without inflating the session-span count.
+ //
+ // We also stamp `coding_agent.session.outcome = "completed"`
+ // on this event-span so the sessions list reflects "agent
+ // finished its loop" instead of remaining on the "running"
+ // pill forever. Claude Code's `SessionEnd` only fires on
+ // graceful exits (`/exit`, logout, clear) — closing VS Code
+ // or starting a new chat skips it, leaving the row stuck.
+ // The sessions rollup uses `argMaxIf(outcome, Timestamp,
+ // non-empty)` so a later SessionEnd verdict (cancelled /
+ // abandoned_with_change) still wins over this "completed"
+ // stamp, which matches the user-visible truth: the chat
+ // completed each turn, and the *terminal* outcome is
+ // whatever SessionEnd reports.
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: p.SessionID,
+ Name: "coding_agent.session.loop.stop",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "coding_agent.hook.event": event,
+ "coding_agent.session.loop.kind": "assistant_turn_end",
+ "coding_agent.session.outcome": semconv.CodingAgentSessionOutcomeCompleted,
+ },
+ })
+ case "SessionEnd":
+ // Drain any leftover pending edits as rejections — see the
+ // UserPromptSubmit branch for the rationale. Doing this both
+ // places ensures we attribute rejections whether the session
+ // ended gracefully or via a fresh user prompt.
+ drainRejectedPendingEdits(in, p.SessionID)
+ // Authoritative session-close. Emit the full session span
+ // with token rollups, realized cost, and outcome.
+ return emitSession(in, p, vcs, cls, "ended", time.Now())
+ case "PreToolUse":
+ // Stash the proposed edit for the rejection heuristic when
+ // the tool is an edit tool. PostToolUse will either resolve
+ // it as an accept (and remove the entry) or UserPromptSubmit /
+ // SessionEnd will drain it as a reject. Bash invocations are
+ // passed through to the standard compact event below; git
+ // commit / PR detection happens at PostToolUse where we have
+ // the tool's stdout.
+ if isEditTool(p.ToolName) {
+ stashPendingEdit(in, p)
+ }
+ // Cache Task tool spawns so the matching SubagentStop can
+ // echo `gen_ai.tool.call.id`. Claude Code does not fire
+ // PreToolUse / PostToolUse hooks for actions taken *inside*
+ // a subagent, so the only handle we have to bracket
+ // subagent activity is the (Task tool call, SubagentStop)
+ // pair. The chat view uses the shared id to render the two
+ // spans as one collapsible "Subagent" block.
+ if p.ToolName == "Task" && p.ToolUseID != "" && p.SessionID != "" {
+ st := sessionstate.Load(p.SessionID, "claude-code")
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ st.ActiveTaskToolUseID = p.ToolUseID
+ sessionstate.Save(p.SessionID, "claude-code", st)
+ }
+ // Pre-event only; the full tool span is emitted at PostToolUse
+ // time so we don't double-count. Still log a compact event so
+ // dashboards can show the in-flight tool list.
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: p.SessionID,
+ Name: "coding_agent.tool.requested",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "gen_ai.tool.name": p.ToolName,
+ "gen_ai.tool.call.id": p.ToolUseID,
+ "code.cwd": p.CWD,
+ },
+ })
+ case "PostToolUse":
+ return emitToolCall(in, p, vcs, cls)
+ case "SubagentStop":
+ // Echo the spawning Task tool-use id onto the subagent
+ // span so the chat view can group (Task tool call,
+ // subagent) into one block, then clear the cache. Best-effort
+ // — if PreToolUse(Task) didn't fire for this session (e.g.
+ // the user started in mid-stream or sessionstate was
+ // missing), we still emit the span with the linkage
+ // fields we do have.
+ var toolUseID string
+ if st := sessionstate.Load(p.SessionID, "claude-code"); st != nil {
+ toolUseID = st.ActiveTaskToolUseID
+ if toolUseID != "" {
+ st.ActiveTaskToolUseID = ""
+ sessionstate.Save(p.SessionID, "claude-code", st)
+ }
+ }
+ return in.Emit.EmitSubagent(normalize.Subagent{
+ SessionID: p.SessionID,
+ SubagentID: p.TaskID,
+ SubagentType: p.SubagentType,
+ Vendor: in.Vendor,
+ ToolCallID: toolUseID,
+ Status: "completed",
+ StartedAt: time.Now(),
+ EndedAt: time.Now(),
+ })
+ default:
+ // Unknown event — emit a low-cost span event so we have a
+ // record in case we need to debug a vendor change.
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: p.SessionID,
+ Name: "coding_agent.hook.unknown_event",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.hook.event": event,
+ "coding_agent.client": in.Vendor,
+ },
+ })
+ }
+}
+
+// drainAssistantTurns reads any new assistant turns from Claude Code's
+// transcript JSONL since the last hook invocation and emits one
+// `coding_agent.llm.turn` per *complete* turn (assistant message with a
+// non-empty `stop_reason`). Streaming fragments sharing a RequestID are
+// coalesced. Incomplete trailing turns leave the offset unchanged so the
+// next invocation picks them up.
+
+func drainAssistantTurns(in normalize.Input, p claudePayload) {
+ sessionID := p.SessionID
+ if sessionID == "" {
+ return
+ }
+
+ transcriptPath := strings.TrimSpace(p.TranscriptPath)
+ st := sessionstate.Load(sessionID, "claude-code")
+ if transcriptPath == "" {
+ transcriptPath = st.TranscriptPath
+ }
+ if transcriptPath == "" {
+ return
+ }
+ if strings.HasPrefix(transcriptPath, "~/") {
+ if home, err := os.UserHomeDir(); err == nil {
+ transcriptPath = filepath.Join(home, strings.TrimPrefix(transcriptPath, "~/"))
+ }
+ }
+
+ lines, newOffset, err := readTranscript(transcriptPath, st.TranscriptOffset)
+ if err != nil || len(lines) == 0 {
+ // Persist the path even if nothing new — later events without
+ // a `transcript_path` field in the payload can still resume.
+ if transcriptPath != st.TranscriptPath {
+ st.TranscriptPath = transcriptPath
+ sessionstate.Save(sessionID, "claude-code", st)
+ }
+ return
+ }
+
+ // Whether or not we end up emitting new turns, we can always
+ // promote the transcript's `entrypoint` to a sessionstate-cached
+ // `terminal.type`. This is the only signal that survives
+ // Anthropic's env-scrubbed hook subprocess — the env / process-
+ // tree detection in cli/internal/otlp/exporter.go runs without
+ // it. Pick the first line that carries the field and persist;
+ // re-reads on later events are cheap because the offset means
+ // we touch at most the new tail.
+ for _, line := range lines {
+ if v := strings.TrimSpace(line.Entrypoint); v != "" {
+ if host := hostFromEntrypoint(v); host != "" && st.TerminalType != host {
+ st.TerminalType = host
+ }
+ break
+ }
+ }
+
+ turns, safeOffset := coalesceAssistants(lines)
+ if len(turns) == 0 {
+ // Persist transcript path + terminal so a later event can resume.
+ st.TranscriptPath = transcriptPath
+ sessionstate.Save(sessionID, "claude-code", st)
+ _ = newOffset
+ return
+ }
+
+ // User-typed prompts are emitted by the UserPromptSubmit hook
+ // (see emitUserPrompt). The transcript's user line for the same
+ // turn carries Claude Code's *wrapped* prompt — prefixed with
+ // `<ide_opened_file>…` and similar context envelopes the IDE
+ // injects before dispatching to the model — which is a different
+ // string than what UserPromptSubmit captured, so re-emitting it
+ // here surfaced a duplicate "User" bubble next to the raw one.
+ // We rely on UserPromptSubmit as the single source of truth for
+ // user prompts and skip the transcript-side prompt entirely.
+
+ seenIDs := make(map[string]struct{}, len(st.EmittedAssistantTurnIDs))
+ for _, id := range st.EmittedAssistantTurnIDs {
+ seenIDs[id] = struct{}{}
+ }
+
+ emittedNew := false
+ for _, t := range turns {
+ turnKey := t.line.RequestID
+ if turnKey == "" {
+ turnKey = t.line.UUID
+ }
+ if _, ok := seenIDs[turnKey]; ok {
+ continue
+ }
+ emitOneAssistantTurn(in, p, t)
+ seenIDs[turnKey] = struct{}{}
+ st.EmittedAssistantTurnIDs = append(st.EmittedAssistantTurnIDs, turnKey)
+ emittedNew = true
+ }
+
+ if len(st.EmittedAssistantTurnIDs) > 256 {
+ st.EmittedAssistantTurnIDs = st.EmittedAssistantTurnIDs[len(st.EmittedAssistantTurnIDs)-256:]
+ }
+
+ st.TranscriptPath = transcriptPath
+ if safeOffset > st.TranscriptOffset {
+ st.TranscriptOffset = safeOffset
+ }
+ if emittedNew {
+ sessionstate.Save(sessionID, "claude-code", st)
+ } else if transcriptPath != "" {
+ // Even with no new turns, persist transcript path so future
+ // events know where to resume.
+ sessionstate.Save(sessionID, "claude-code", st)
+ }
+}
+
+// emitOneAssistantTurn produces a single `coding_agent.llm.turn` span
+// from a fully-coalesced assistant turn read out of the transcript.
+//
+// The span carries only the assistant's text reply, thinking text,
+// and per-turn usage / tags. The user-prompt that triggered the turn
+// is NOT stamped here — UserPromptSubmit's hook is the canonical
+// source for that string. Tool calls + tool results that bracket the
+// turn are emitted as their own `coding_agent.tool.call` spans.
+func emitOneAssistantTurn(in normalize.Input, p claudePayload, t coalescedTurn) {
+ completedAt, _ := time.Parse(time.RFC3339Nano, t.line.Timestamp)
+ if completedAt.IsZero() {
+ completedAt = time.Now()
+ }
+
+ turn := normalize.LLMTurn{
+ SessionID: p.SessionID,
+ ConversationID: p.SessionID,
+ GenerationID: strings.TrimSpace(t.line.RequestID),
+ Vendor: in.Vendor,
+ Model: t.msg.Model,
+ StartedAt: completedAt,
+ EndedAt: completedAt,
+ InputTokens: t.msg.Usage.InputTokens + t.msg.Usage.CacheReadInputTokens + t.msg.Usage.CacheCreationInputTokens,
+ OutputTokens: t.msg.Usage.OutputTokens,
+ CacheReadTokens: t.msg.Usage.CacheReadInputTokens,
+ CacheCreationTokens: t.msg.Usage.CacheCreationInputTokens,
+ }
+ turn.TotalTokens = turn.InputTokens + turn.OutputTokens
+ if t.msg.StopReason != "" {
+ turn.FinishReasons = []string{t.msg.StopReason}
+ }
+ if t.msg.Model != "" {
+ rate := pricing.Lookup(t.msg.Model)
+ // Anthropic prompt caching has *two* rates: cache reads (~10%
+ // of input) and cache writes (~125% of input). Pass them
+ // through separately so the pricing layer can apply the
+ // correct premium — bundling them under the read rate
+ // silently under-bills cache-write-heavy turns by up to 12x.
+ turn.CostUSD = rate.Cost(turn.InputTokens, turn.OutputTokens, turn.CacheReadTokens, turn.CacheCreationTokens)
+ }
+ // Per-turn tags — surface the high-signal transcript fields
+ // adapters used to drop. We namespace them under `claude_code.*`
+ // so the same `coding_agent.llm.turn` schema can host them
+ // alongside Cursor / Codex turns without colliding.
+ turn.Extras = map[string]string{}
+ if v := strings.TrimSpace(t.line.Version); v != "" {
+ turn.Extras["claude_code.client.version"] = v
+ }
+ if v := strings.TrimSpace(t.line.Entrypoint); v != "" {
+ turn.Extras["claude_code.entrypoint"] = v
+ // drainAssistantTurns already cached this into sessionstate.
+ // We still stamp it on the LLM turn span so a single span
+ // detail panel renders the same host the resource attr does.
+ if host := hostFromEntrypoint(v); host != "" {
+ turn.Extras["terminal.type"] = host
+ }
+ }
+ if v := strings.TrimSpace(t.line.GitBranch); v != "" {
+ turn.Extras["vcs.ref.head.name"] = v
+ }
+ if v := strings.TrimSpace(t.line.CWD); v != "" {
+ turn.Extras["code.cwd"] = v
+ }
+ if t.line.IsSidechain {
+ turn.Extras["claude_code.is_sidechain"] = "true"
+ }
+ if len(turn.Extras) == 0 {
+ turn.Extras = nil
+ }
+
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ // Adapter pre-flattens the assistant turn into the fields
+ // LLMTurn declares. The emitter (cli/internal/otlp/attrs.go)
+ // builds the OTel-canonical `gen_ai.{input,output}.messages`
+ // envelopes from these — adapters never construct that JSON
+ // themselves, so the shape is guaranteed identical across
+ // Cursor, Claude Code, and Codex.
+ //
+ // Tool calls + tool results that bracket this turn are
+ // emitted separately as `coding_agent.tool.call` spans by
+ // the PreToolUse / PostToolUse hooks, so we deliberately
+ // drop them here — folding them into the LLM-turn messages
+ // would balloon the JSON past the span-attribute cap.
+ text, thinking := splitAssistantContent(t.msg.Content)
+ turn.Response = text
+ turn.ThoughtText = thinking
+ }
+
+ _ = in.Emit.EmitLLMTurn(turn)
+}
+
+// splitAssistantContent returns the assistant turn split into:
+// - text : concatenated `text` blocks (the chat answer)
+// - think : concatenated `thinking` blocks (separate attribute)
+//
+// `tool_use` blocks are intentionally skipped: their canonical record
+// is the matching `coding_agent.tool.call` span emitted by the
+// PreToolUse / PostToolUse hooks.
+func splitAssistantContent(blocks []assistantContentBlock) (text, think string) {
+ var textParts, thoughtParts []string
+ for _, b := range blocks {
+ switch b.Type {
+ case "text":
+ if strings.TrimSpace(b.Text) != "" {
+ textParts = append(textParts, b.Text)
+ }
+ case "thinking":
+ if strings.TrimSpace(b.Thinking) != "" {
+ thoughtParts = append(thoughtParts, b.Thinking)
+ }
+ }
+ }
+ return strings.Join(textParts, "\n\n"), strings.Join(thoughtParts, "\n\n")
+}
+
+// emitUserPrompt fires on Claude Code's UserPromptSubmit hook. We
+// produce a `coding_agent.llm.turn` span with `kind=prompt` so the
+// session's chat view can render the user's intent without needing
+// to tail the transcript on every read. The prompt body itself is
+// gated by the content-capture mode — `full` keeps it verbatim,
+// `metadata_only` and `minimal` keep only the length. See
+// `.cursor/rules/coding-agents-convention.mdc` §4.
+func emitUserPrompt(in normalize.Input, p claudePayload) error {
+ now := time.Now()
+ turn := normalize.LLMTurn{
+ SessionID: p.SessionID,
+ ConversationID: p.SessionID,
+ Vendor: in.Vendor,
+ StartedAt: now,
+ EndedAt: now,
+ }
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull && p.Prompt != "" {
+ turn.Prompt = p.Prompt
+ }
+ return in.Emit.EmitLLMTurn(turn)
+}
+
+func emitSession(
+ in normalize.Input,
+ p claudePayload,
+ vcs git.Context,
+ cls classify.Classification,
+ kind string,
+ endedAt time.Time,
+) error {
+ // Resolve StartedAt with a real wall-clock when we can. On
+ // `started` we cache `time.Now()` so the matching `ended` event
+ // (which runs in a different hook subprocess) can reload it and
+ // compute a real duration. Previously both events used
+ // `time.Now()` directly, producing ~0ms sessions in the Sessions
+ // list and dragging duration averages to zero.
+ now := time.Now()
+ startedAt := now
+ if p.SessionID != "" {
+ if st := sessionstate.Load(p.SessionID, "claude-code"); st != nil && !st.SessionStartedAt.IsZero() {
+ startedAt = st.SessionStartedAt
+ }
+ if kind == "started" {
+ st := sessionstate.Load(p.SessionID, "claude-code")
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ if st.SessionStartedAt.IsZero() {
+ st.SessionStartedAt = now
+ sessionstate.Save(p.SessionID, "claude-code", st)
+ }
+ startedAt = st.SessionStartedAt
+ }
+ }
+
+ s := normalize.Session{
+ SessionID: p.SessionID,
+ ConversationID: p.SessionID,
+ Vendor: in.Vendor,
+ StartedAt: startedAt,
+ EndedAt: endedAt,
+ PermissionMode: p.PermissionMode,
+ CWD: p.CWD,
+ RepoURL: vcs.RepoURL,
+ HeadSHA: vcs.HeadSHA,
+ BranchName: vcs.Branch,
+ VCSDirty: vcs.Dirty,
+ UserClassification: cls.Value,
+ ClassificationReason: cls.Reason,
+ Extras: map[string]string{
+ "coding_agent.hook.event": p.HookEventName,
+ "claude_code.transcript.path": p.TranscriptPath,
+ "claude_code.session.lifecycle": kind,
+ },
+ }
+ if p.Source != "" {
+ s.Extras["claude_code.session.source"] = p.Source
+ }
+
+ // Tail the transcript for both kinds. On `started`, this gives
+ // us an early model attribution (so the session row shows a
+ // provider/model immediately after the first turn instead of
+ // waiting for SessionEnd). On `ended`, this gives us the
+ // authoritative token + cost totals.
+ if model, cost, in0, out0, total := tailTranscript(p.TranscriptPath); total > 0 || cost > 0 || model != "" {
+ if model != "" {
+ s.Model = model
+ }
+ if kind == "ended" {
+ s.CostUSD = cost
+ s.InputTokens = in0
+ s.OutputTokens = out0
+ s.TotalTokens = total
+ }
+ }
+
+ if kind == "ended" {
+ s.Outcome = outcomeFromReason(p.Reason, vcs.Dirty)
+ }
+
+ return in.Emit.EmitSession(s)
+}
+
+// outcomeFromReason maps Claude Code's SessionEnd reason onto our
+// session-outcome enum. Without GitHub-App context we cannot know
+// "merged" or "committed"; we report the closest local signal.
+func outcomeFromReason(reason string, vcsDirty bool) string {
+ switch reason {
+ case "exit", "logout":
+ if vcsDirty {
+ return semconv.CodingAgentSessionOutcomeAbandonedWithChange
+ }
+ return semconv.CodingAgentSessionOutcomeAbandonedNoChange
+ case "clear":
+ return semconv.CodingAgentSessionOutcomeCancelled
+ }
+ if vcsDirty {
+ return semconv.CodingAgentSessionOutcomeAbandonedWithChange
+ }
+ return semconv.CodingAgentSessionOutcomeAbandonedNoChange
+}
+
+// emitToolCall fires only on PostToolUse. PreToolUse is handled at the
+// switch-level as a span event so we don't double-emit a tool span per
+// invocation. VCS / classification context lands on the session-root
+// span as resource attributes, so we don't need to re-stamp them here.
+func emitToolCall(in normalize.Input, p claudePayload, vcs git.Context, cls classify.Classification) error {
+ _ = vcs
+ _ = cls
+ t := normalize.ToolCall{
+ SessionID: p.SessionID,
+ ToolName: p.ToolName,
+ ToolUseID: p.ToolUseID,
+ Vendor: in.Vendor,
+ WorkingDir: p.CWD,
+ StartedAt: time.Now(),
+ EndedAt: time.Now(),
+ }
+ // Surface a Bash command as the tool's canonical command so the
+ // trace-detail view's "Shell" pill renders the right summary. The
+ // raw string is still gated by capture mode in `attrs.go`.
+ if p.ToolName == "Bash" {
+ if cmd := stringFieldFromInput(p.ToolInput, "command"); cmd != "" {
+ t.Command = cmd
+ // Detect agent-attributed git commits / PR creations. The
+ // Bash tool's stdout is available on `tool_response`; we
+ // pass it to the detect helpers so the SHA / URL stamped
+ // on the resulting GitCommit / GitPullRequest spans are
+ // authoritative.
+ emitGitArtifactsClaude(in, p, cmd)
+ }
+ }
+
+ // Edit-decision: PostToolUse fired, so we resolve any PreToolUse
+ // pending entry as an accept. When permission_mode is one of the
+ // auto-accept modes the decision is `auto_accepted` rather than
+ // `accept` so the dashboards can split user-driven vs policy-
+ // driven accepts. Bumps both the session-state edit counters
+ // and the OTel metrics counters (via the emitter), so the
+ // session-root span carries the totals and Prometheus / Mimir
+ // see the deltas in lock-step with the trace.
+ if isEditTool(p.ToolName) {
+ pending := sessionstate.TakePendingEdit(p.SessionID, in.Vendor, p.ToolUseID)
+ decision := semconv.CodingAgentEditDecisionAccept
+ source := semconv.CodingAgentEditDecisionSourceUserInteractive
+ if p.PermissionMode == "auto_accept" || p.PermissionMode == "bypassPermissions" || p.PermissionMode == "acceptEdits" {
+ decision = semconv.CodingAgentEditDecisionAutoAccepted
+ source = semconv.CodingAgentEditDecisionSourcePolicy
+ }
+ ed := normalize.EditDecision{
+ SessionID: p.SessionID,
+ Decision: decision,
+ Source: source,
+ Tool: p.ToolName,
+ Vendor: in.Vendor,
+ At: time.Now(),
+ FilePath: stringFieldFromInput(p.ToolInput, "file_path"),
+ }
+ if pending != nil {
+ ed.LinesAdded = pending.LinesAdded
+ ed.LinesRemoved = pending.LinesRemoved
+ ed.Language = pending.Language
+ if ed.FilePath == "" {
+ ed.FilePath = pending.FilePath
+ }
+ }
+ _ = in.Emit.EmitEditDecision(ed)
+ sessionstate.BumpCodeCounters(p.SessionID, in.Vendor, ed.LinesAdded, ed.LinesRemoved, ed.LinesAdded, 0, 1, 0)
+ }
+
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ if len(p.ToolInput) > 0 {
+ t.Args = string(p.ToolInput)
+ }
+ if len(p.ToolResponse) > 0 {
+ t.Result = string(p.ToolResponse)
+ }
+ }
+ return in.Emit.EmitToolCall(t)
+}
+
+// stashPendingEdit caches the proposed edit body from a PreToolUse
+// hook so PostToolUse can resolve it as an accept (or
+// UserPromptSubmit / SessionEnd can drain it as a reject). Inspects
+// the tool name to choose the right line-count strategy:
+//
+// - Edit: `old_string` → `new_string` (use detect.CountInlineDiff)
+// - Write: `content` is the new body, treat as insertion-only
+// - MultiEdit: iterate the `edits[]` array of {old,new} pairs
+// - NotebookEdit: same as Edit semantically — `new_source` may be
+// present in lieu of `new_string`.
+func stashPendingEdit(in normalize.Input, p claudePayload) {
+ if p.ToolUseID == "" {
+ return
+ }
+ filePath := stringFieldFromInput(p.ToolInput, "file_path")
+ var added, removed int
+ switch p.ToolName {
+ case "Edit", "NotebookEdit":
+ oldStr := stringFieldFromInput(p.ToolInput, "old_string")
+ newStr := stringFieldFromInput(p.ToolInput, "new_string")
+ if newStr == "" {
+ newStr = stringFieldFromInput(p.ToolInput, "new_source")
+ }
+ added, removed = detect.CountInlineDiff(oldStr, newStr)
+ case "Write":
+ body := stringFieldFromInput(p.ToolInput, "content")
+ added, _ = detect.CountInlineDiff("", body)
+ case "MultiEdit":
+ added, removed = countMultiEditLines(p.ToolInput)
+ }
+ sessionstate.AddPendingEdit(p.SessionID, in.Vendor, p.ToolUseID, &sessionstate.PendingEdit{
+ ToolName: p.ToolName,
+ FilePath: filePath,
+ LinesAdded: added,
+ LinesRemoved: removed,
+ Language: guessLanguage(filePath),
+ })
+}
+
+// drainRejectedPendingEdits emits one EditDecision per leftover
+// pending edit, marked as `reject`. Called from UserPromptSubmit /
+// SessionEnd. The function is a no-op when there are no pending
+// entries (the common case for completed-turn sessions).
+func drainRejectedPendingEdits(in normalize.Input, sessionID string) {
+ leftover := sessionstate.DrainPendingEdits(sessionID, in.Vendor)
+ if len(leftover) == 0 {
+ return
+ }
+ for _, e := range leftover {
+ if e == nil {
+ continue
+ }
+ _ = in.Emit.EmitEditDecision(normalize.EditDecision{
+ SessionID: sessionID,
+ Decision: semconv.CodingAgentEditDecisionReject,
+ Source: semconv.CodingAgentEditDecisionSourceUserInteractive,
+ Tool: e.ToolName,
+ Language: e.Language,
+ LinesAdded: e.LinesAdded,
+ LinesRemoved: e.LinesRemoved,
+ FilePath: e.FilePath,
+ Vendor: in.Vendor,
+ At: time.Now(),
+ })
+ sessionstate.BumpCodeCounters(sessionID, in.Vendor, 0, 0, 0, e.LinesAdded, 0, 1)
+ }
+}
+
+// countMultiEditLines parses Claude Code's MultiEdit `tool_input` —
+// `{ "file_path": "...", "edits": [{"old_string":..., "new_string":...}] }`
+// — and totals lines-added/removed across every entry.
+func countMultiEditLines(raw json.RawMessage) (added, removed int) {
+ if len(raw) == 0 {
+ return 0, 0
+ }
+ var m struct {
+ Edits []struct {
+ OldString string `json:"old_string"`
+ NewString string `json:"new_string"`
+ } `json:"edits"`
+ }
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return 0, 0
+ }
+ for _, e := range m.Edits {
+ a, r := detect.CountInlineDiff(e.OldString, e.NewString)
+ added += a
+ removed += r
+ }
+ return added, removed
+}
+
+// guessLanguage maps the file extension onto a language tag for the
+// edit-decision metric. Returns "" when we don't recognise the
+// extension so the dashboard can group those into "other".
+func guessLanguage(filePath string) string {
+ if filePath == "" {
+ return ""
+ }
+ ext := strings.ToLower(filepath.Ext(filePath))
+ switch ext {
+ case ".go":
+ return "go"
+ case ".ts", ".tsx":
+ return "typescript"
+ case ".js", ".jsx", ".mjs", ".cjs":
+ return "javascript"
+ case ".py":
+ return "python"
+ case ".rs":
+ return "rust"
+ case ".java":
+ return "java"
+ case ".kt", ".kts":
+ return "kotlin"
+ case ".swift":
+ return "swift"
+ case ".rb":
+ return "ruby"
+ case ".php":
+ return "php"
+ case ".c":
+ return "c"
+ case ".cpp", ".cc", ".cxx", ".hpp", ".hh", ".hxx":
+ return "cpp"
+ case ".h":
+ return "c"
+ case ".cs":
+ return "csharp"
+ case ".sh", ".bash", ".zsh":
+ return "shell"
+ case ".md", ".markdown":
+ return "markdown"
+ case ".json":
+ return "json"
+ case ".yml", ".yaml":
+ return "yaml"
+ case ".sql":
+ return "sql"
+ case ".css", ".scss", ".sass":
+ return "css"
+ case ".html", ".htm":
+ return "html"
+ }
+ return ""
+}
+
+// emitGitArtifactsClaude inspects a Bash tool's command + stdout for
+// git commit / PR create patterns and emits the matching spans + bumps
+// the session-state counters. The tool response is pulled from
+// `tool_response.stdout` when the field is a string; Anthropic also
+// surfaces compound objects here so we fall back to the raw blob when
+// stdout isn't extractable.
+func emitGitArtifactsClaude(in normalize.Input, p claudePayload, cmd string) {
+ if cmd == "" {
+ return
+ }
+ stdout := bashStdout(p.ToolResponse)
+ now := time.Now()
+ if detect.IsGitCommit(cmd) {
+ sha := detect.ExtractCommitSHA(stdout)
+ message := ""
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ message = detect.ExtractCommitMessage(cmd)
+ }
+ _ = in.Emit.EmitGitCommit(normalize.GitCommit{
+ SessionID: p.SessionID,
+ Vendor: in.Vendor,
+ Tool: "Bash",
+ SHA: sha,
+ Message: message,
+ WorkingDir: p.CWD,
+ At: now,
+ })
+ sessionstate.BumpCommitCount(p.SessionID, in.Vendor)
+ }
+ if detect.IsPullRequest(cmd) {
+ url, num := detect.ExtractPRURLAndNumber(stdout)
+ title := ""
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ title = detect.ExtractPRTitle(cmd)
+ }
+ _ = in.Emit.EmitGitPullRequest(normalize.GitPullRequest{
+ SessionID: p.SessionID,
+ Vendor: in.Vendor,
+ Tool: "Bash",
+ URL: url,
+ Number: num,
+ Title: title,
+ WorkingDir: p.CWD,
+ At: now,
+ })
+ sessionstate.BumpPRCount(p.SessionID, in.Vendor)
+ }
+}
+
+// bashStdout extracts the Bash tool's stdout from Claude Code's
+// `tool_response` blob. The blob is sometimes a plain string and
+// sometimes `{"stdout":"...","stderr":"...","exit_code":0}` — we
+// handle both. Returns "" when neither shape applies so the detect
+// helpers fall through to the cheaper command-only path.
+func bashStdout(raw json.RawMessage) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var s string
+ if err := json.Unmarshal(raw, &s); err == nil {
+ return s
+ }
+ var m struct {
+ Stdout string `json:"stdout"`
+ Output string `json:"output"`
+ }
+ if err := json.Unmarshal(raw, &m); err == nil {
+ if m.Stdout != "" {
+ return m.Stdout
+ }
+ return m.Output
+ }
+ return ""
+}
+
+// hostFromEntrypoint maps Anthropic's per-line `entrypoint` value to
+// our `terminal.type` enum. `claude-vscode` → vscode, `claude-cursor`
+// → cursor, anything else stays empty (the env / process-tree fallback
+// in cli/internal/otlp/exporter.go can still rescue the stamp).
+func hostFromEntrypoint(ep string) string {
+ e := strings.ToLower(strings.TrimSpace(ep))
+ switch {
+ case strings.Contains(e, "vscode"), strings.Contains(e, "vs-code"), strings.Contains(e, "vs_code"):
+ return "vscode"
+ case strings.Contains(e, "cursor"):
+ return "cursor"
+ case strings.Contains(e, "windsurf"):
+ return "windsurf"
+ case strings.Contains(e, "jetbrains"), strings.Contains(e, "intellij"), strings.Contains(e, "pycharm"):
+ return "jetbrains"
+ }
+ return ""
+}
+
+func isEditTool(name string) bool {
+ switch name {
+ case "Edit", "Write", "MultiEdit", "NotebookEdit":
+ return true
+ default:
+ return false
+ }
+}
+
+// stringFieldFromInput pulls a single string field out of the
+// `tool_input` blob if present. We use it for `file_path` (Edit /
+// Write / MultiEdit / NotebookEdit) and `command` (Bash). Returns "" on
+// any error so the caller can decide what to do.
+func stringFieldFromInput(raw json.RawMessage, field string) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return ""
+ }
+ v, ok := m[field]
+ if !ok || len(v) == 0 {
+ return ""
+ }
+ var s string
+ if err := json.Unmarshal(v, &s); err != nil {
+ return ""
+ }
+ return s
+}
+
+// tailTranscript scans the end of a Claude Code transcript JSONL file
+// for the final usage line. The transcript format is one JSON object
+// per line, with assistant turns carrying a `usage` object that totals
+// input/output/cache tokens for that turn. We sum the assistant turns
+// and use the per-model pricing table (cli/internal/coding/pricing) to
+// realize a USD cost.
+//
+// Returns zero values when the path is missing or unreadable; the hook
+// path always tolerates missing transcript data.
+func tailTranscript(path string) (model string, cost float64, inTokens, outTokens, total int64) {
+ if path == "" {
+ return "", 0, 0, 0, 0
+ }
+ if strings.HasPrefix(path, "~/") {
+ if home, err := os.UserHomeDir(); err == nil {
+ path = filepath.Join(home, strings.TrimPrefix(path, "~/"))
+ }
+ }
+ // F3: bound the read to the last `DefaultCap` bytes so the hook
+ // never blocks on a multi-GB transcript. Marathon sessions whose
+ // usage rolls up across the boundary will undercount tokens —
+ // we accept that in exchange for predictable hook latency. The
+ // last-N-bytes window comfortably holds a multi-hour session at
+ // realistic Claude turn sizes.
+ lines := tailfile.Tail(path, tailfile.DefaultCap)
+ if len(lines) == 0 {
+ return "", 0, 0, 0, 0
+ }
+ type usage struct {
+ InputTokens int64 `json:"input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
+ CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
+ }
+ type turn struct {
+ Type string `json:"type"`
+ Message struct {
+ Model string `json:"model"`
+ Usage usage `json:"usage"`
+ } `json:"message"`
+ }
+
+ var ti, to, cacheRead, cacheCreation int64
+ var lastModel string
+ for _, line := range lines {
+ var t turn
+ if err := json.Unmarshal(line, &t); err != nil {
+ continue
+ }
+ // Anthropic transcript reports cache creation + cache read as
+ // separate counters; "fresh" input is the standard input_tokens.
+ // The OTel field gen_ai.usage.input_tokens should equal total
+ // distinct input the model saw, so we sum them.
+ fresh := t.Message.Usage.InputTokens
+ creation := t.Message.Usage.CacheCreationInputTokens
+ read := t.Message.Usage.CacheReadInputTokens
+ ti += fresh + creation + read
+ cacheRead += read
+ cacheCreation += creation
+ to += t.Message.Usage.OutputTokens
+ if t.Message.Model != "" {
+ lastModel = t.Message.Model
+ }
+ }
+ rate := pricing.Lookup(lastModel)
+ cost = rate.Cost(ti, to, cacheRead, cacheCreation)
+ return lastModel, cost, ti, to, ti + to
+}
diff --git a/cli/internal/coding/hook/claudecode/handle_test.go b/cli/internal/coding/hook/claudecode/handle_test.go
new file mode 100644
index 00000000..0fa3e406
--- /dev/null
+++ b/cli/internal/coding/hook/claudecode/handle_test.go
@@ -0,0 +1,243 @@
+package claudecode
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+)
+
+// recordingEmitter mirrors the codex package's test emitter. We keep
+// a local copy rather than share one across packages because each
+// vendor adapter ends up needing slightly different assertion
+// helpers — sharing risked accidental coupling across vendors that
+// blurs the canonical-schema boundary the convention rule enforces.
+type recordingEmitter struct {
+ sessions []normalize.Session
+ toolCalls []normalize.ToolCall
+ editDecisions []normalize.EditDecision
+ llmTurns []normalize.LLMTurn
+ subagents []normalize.Subagent
+ events []normalize.EventEmission
+ gitCommits []normalize.GitCommit
+ gitPRs []normalize.GitPullRequest
+}
+
+func (e *recordingEmitter) EmitSession(s normalize.Session) error {
+ e.sessions = append(e.sessions, s)
+ return nil
+}
+func (e *recordingEmitter) EmitToolCall(t normalize.ToolCall) error {
+ e.toolCalls = append(e.toolCalls, t)
+ return nil
+}
+func (e *recordingEmitter) EmitEditDecision(d normalize.EditDecision) error {
+ e.editDecisions = append(e.editDecisions, d)
+ return nil
+}
+func (e *recordingEmitter) EmitLLMTurn(t normalize.LLMTurn) error {
+ e.llmTurns = append(e.llmTurns, t)
+ return nil
+}
+func (e *recordingEmitter) EmitSubagent(s normalize.Subagent) error {
+ e.subagents = append(e.subagents, s)
+ return nil
+}
+func (e *recordingEmitter) EmitEvent(ev normalize.EventEmission) error {
+ e.events = append(e.events, ev)
+ return nil
+}
+func (e *recordingEmitter) EmitGitCommit(c normalize.GitCommit) error {
+ e.gitCommits = append(e.gitCommits, c)
+ return nil
+}
+func (e *recordingEmitter) EmitGitPullRequest(p normalize.GitPullRequest) error {
+ e.gitPRs = append(e.gitPRs, p)
+ return nil
+}
+
+// withIsolatedCache redirects sessionstate's on-disk cache to a tmp
+// dir so concurrent test runs don't pollute each other's state. We
+// re-point both XDG_CACHE_HOME and HOME because os.UserCacheDir
+// honours either depending on the platform.
+func withIsolatedCache(t *testing.T) {
+ t.Helper()
+ dir := t.TempDir()
+ t.Setenv("XDG_CACHE_HOME", dir)
+ if home := os.Getenv("HOME"); home != "" {
+ t.Setenv("HOME", dir)
+ }
+}
+
+// input builds a normalize.Input the way the hook runner does.
+// Returning a closure keeps the per-call boilerplate readable.
+func inputBuilder(t *testing.T, em *recordingEmitter) func(event string, payload any) normalize.Input {
+ t.Helper()
+ return func(event string, payload any) normalize.Input {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("payload marshal: %v", err)
+ }
+ return normalize.Input{
+ Vendor: "claude-code",
+ Event: event,
+ Payload: body,
+ ContentCapture: "full",
+ Emit: em,
+ }
+ }
+}
+
+// TestClaudePreToolUseTaskLinksSubagent verifies the PreToolUse(Task)
+// → SubagentStop linkage: the Task tool's `tool_use_id` is cached in
+// sessionstate, then echoed on the EmitSubagent call as
+// `ToolCallID`. The chat view groups by this id, so a regression
+// here breaks the "expand subagent" UX.
+func TestClaudePreToolUseTaskLinksSubagent(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ in := inputBuilder(t, em)
+ sid := "cc-session-link-1"
+ taskCallID := "toolu_01TASK"
+
+ if err := handle(context.Background(), in("PreToolUse", map[string]any{
+ "hook_event_name": "PreToolUse",
+ "session_id": sid,
+ "tool_name": "Task",
+ "tool_use_id": taskCallID,
+ "tool_input": json.RawMessage(`{"subagent_type":"research"}`),
+ })); err != nil {
+ t.Fatalf("PreToolUse(Task): %v", err)
+ }
+
+ st := sessionstate.Load(sid, "claude-code")
+ if st == nil || st.ActiveTaskToolUseID != taskCallID {
+ t.Fatalf("expected ActiveTaskToolUseID=%q after PreToolUse(Task); got %+v", taskCallID, st)
+ }
+
+ if err := handle(context.Background(), in("SubagentStop", map[string]any{
+ "hook_event_name": "SubagentStop",
+ "session_id": sid,
+ "subagent_type": "research",
+ "task_id": "task-42",
+ })); err != nil {
+ t.Fatalf("SubagentStop: %v", err)
+ }
+
+ if len(em.subagents) != 1 {
+ t.Fatalf("expected one subagent emission; got %d", len(em.subagents))
+ }
+ got := em.subagents[0]
+ if got.ToolCallID != taskCallID {
+ t.Errorf("subagent.ToolCallID = %q, want %q (the Task tool_use_id cached at PreToolUse)", got.ToolCallID, taskCallID)
+ }
+ if got.SubagentID != "task-42" {
+ t.Errorf("subagent.SubagentID = %q, want %q", got.SubagentID, "task-42")
+ }
+
+ // Cache must be cleared after SubagentStop — otherwise a second
+ // unrelated subagent in the same session would inherit the
+ // stale id.
+ st = sessionstate.Load(sid, "claude-code")
+ if st != nil && st.ActiveTaskToolUseID != "" {
+ t.Errorf("expected ActiveTaskToolUseID to be cleared post-SubagentStop; got %q", st.ActiveTaskToolUseID)
+ }
+}
+
+// TestClaudeSubagentStopWithoutPreToolUse covers the resilient path:
+// when sessionstate is missing (process restarted mid-session, or
+// PreToolUse(Task) wasn't observed by this hook), SubagentStop still
+// emits a span with the linkage fields it does have. The
+// ToolCallID is empty — better than silently dropping the span.
+func TestClaudeSubagentStopWithoutPreToolUse(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ in := inputBuilder(t, em)
+
+ if err := handle(context.Background(), in("SubagentStop", map[string]any{
+ "hook_event_name": "SubagentStop",
+ "session_id": "cc-orphan-1",
+ "subagent_type": "code-review",
+ "task_id": "task-x",
+ })); err != nil {
+ t.Fatalf("SubagentStop: %v", err)
+ }
+ if len(em.subagents) != 1 {
+ t.Fatalf("expected one subagent emission; got %d", len(em.subagents))
+ }
+ if em.subagents[0].ToolCallID != "" {
+ t.Errorf("expected empty ToolCallID when PreToolUse(Task) didn't cache one; got %q", em.subagents[0].ToolCallID)
+ }
+ if em.subagents[0].SubagentID != "task-x" {
+ t.Errorf("subagent.SubagentID = %q, want %q", em.subagents[0].SubagentID, "task-x")
+ }
+}
+
+// TestClaudeSessionDurationCachedAcrossInvocations verifies the
+// W3.3 fix: SessionStart caches `SessionStartedAt` in sessionstate
+// so that SessionEnd — which runs in a separate hook subprocess —
+// can compute the real session duration instead of reporting 0ms.
+//
+// Without the cache, SessionEnd's `time.Now() - time.Now()` is
+// always ~zero.
+func TestClaudeSessionDurationCachedAcrossInvocations(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ in := inputBuilder(t, em)
+ sid := "cc-duration-1"
+
+ if err := handle(context.Background(), in("SessionStart", map[string]any{
+ "hook_event_name": "SessionStart",
+ "session_id": sid,
+ "cwd": "/tmp/work",
+ "source": "startup",
+ })); err != nil {
+ t.Fatalf("SessionStart: %v", err)
+ }
+
+ // Rewind the cached start so SessionEnd sees a non-zero
+ // duration even on the fastest CI runners. Using a real sleep
+ // would slow this test down; mutating the cache directly is
+ // the supported way to inject a known start time.
+ st := sessionstate.Load(sid, "claude-code")
+ if st == nil {
+ t.Fatalf("expected sessionstate to be populated after SessionStart")
+ }
+ st.SessionStartedAt = time.Now().Add(-90 * time.Second)
+ sessionstate.Save(sid, "claude-code", st)
+
+ if err := handle(context.Background(), in("SessionEnd", map[string]any{
+ "hook_event_name": "SessionEnd",
+ "session_id": sid,
+ "cwd": "/tmp/work",
+ "reason": "exit",
+ })); err != nil {
+ t.Fatalf("SessionEnd: %v", err)
+ }
+
+ // emitSession is called for both SessionStart and SessionEnd.
+ // The ended one is whatever lands last with a non-zero EndedAt.
+ var ended *normalize.Session
+ for i := range em.sessions {
+ s := em.sessions[i]
+ if !s.EndedAt.IsZero() {
+ ended = &em.sessions[i]
+ }
+ }
+ if ended == nil {
+ t.Fatalf("expected at least one ended session emission; got %d total", len(em.sessions))
+ }
+ if ended.StartedAt.IsZero() {
+ t.Errorf("ended session.StartedAt is zero — duration cache regression")
+ }
+ if dur := ended.EndedAt.Sub(ended.StartedAt); dur < 30*time.Second {
+ t.Errorf("ended session duration = %s, want >= 30s (cache should have rewound start)", dur)
+ }
+}
diff --git a/cli/internal/coding/hook/claudecode/transcript.go b/cli/internal/coding/hook/claudecode/transcript.go
new file mode 100644
index 00000000..aca0a431
--- /dev/null
+++ b/cli/internal/coding/hook/claudecode/transcript.go
@@ -0,0 +1,257 @@
+package claudecode
+
+// Transcript reader for Claude Code's per-session JSONL file.
+//
+// Each hook invocation reads only the new
+// bytes since the last invocation, coalesces streaming assistant fragments
+// by RequestID, and produces one "complete LLM turn" record per assistant
+// message that finished cleanly (non-empty `stop_reason`).
+//
+// The transcript file is what gives us, on a per-turn basis:
+// - the assistant's text, thinking, and tool_use blocks (chat content)
+// - the user's prompt (text) and tool_result blocks (tool outputs)
+// - the model, request id, and authoritative usage (tokens + cache)
+//
+// SessionEnd alone would let us realize cost/tokens at the end, but the
+// chat tab on the trace detail page expects per-turn spans with input +
+// output messages — that's what Stop / PostToolUse drives once we read
+// the new tail.
+
+import (
+ "bufio"
+ "encoding/json"
+ "io"
+ "os"
+ "strings"
+)
+
+// transcriptLine is a partial decoding of a single JSONL line.
+type transcriptLine struct {
+ Type string `json:"type"`
+ UUID string `json:"uuid"`
+ ParentUUID string `json:"parentUuid"`
+ Timestamp string `json:"timestamp"`
+ SessionID string `json:"sessionId"`
+ Version string `json:"version"`
+ GitBranch string `json:"gitBranch"`
+ CWD string `json:"cwd"`
+ Entrypoint string `json:"entrypoint"`
+ RequestID string `json:"requestId"`
+ IsSidechain bool `json:"isSidechain"`
+ Message json.RawMessage `json:"message"`
+
+ endOffset int64 // byte position immediately after this line
+}
+
+// assistantMessage is the decoded `message` field of an assistant line.
+type assistantMessage struct {
+ Model string `json:"model"`
+ ID string `json:"id"`
+ Content []assistantContentBlock `json:"content"`
+ StopReason string `json:"stop_reason"`
+ Usage assistantUsage `json:"usage"`
+}
+
+type assistantContentBlock struct {
+ Type string `json:"type"`
+ Text string `json:"text,omitempty"`
+ Thinking string `json:"thinking,omitempty"`
+ ID string `json:"id,omitempty"`
+ Name string `json:"name,omitempty"`
+ Input json.RawMessage `json:"input,omitempty"`
+}
+
+type assistantUsage struct {
+ InputTokens int64 `json:"input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
+ CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
+}
+
+// skipTypes are line types the LLM-turn synthesiser ignores.
+var skipTypes = map[string]bool{
+ "file-history-snapshot": true,
+ "queue-operation": true,
+ "attachment": true,
+ "permission-mode": true,
+ "last-prompt": true,
+ "ai-title": true,
+ "system": true,
+}
+
+const maxScannerBuf = 10 * 1024 * 1024 // 10 MB — Claude Code emits multi-MB tool_result lines
+
+// maxBytesPerInvocation caps how many transcript bytes a single hook
+// process will scan. Claude Code transcripts grow to hundreds of MB
+// over a long-running chat; on the very first hook event (offset == 0
+// because sessionstate hasn't seen the session yet), an unbounded
+// scan would happily read the entire file and starve the 5s hook
+// timeout. The cap is a soft ceiling — we honour it by truncating the
+// returned new-offset to (offset + cap) so the next invocation
+// resumes from where we stopped. Set generous enough that a 1MB/sec
+// transcript would still drain in real time across consecutive hook
+// invocations.
+const maxBytesPerInvocation = 8 * 1024 * 1024 // 8 MiB
+
+// readTranscript reads JSONL lines from path starting at the supplied
+// byte offset and returns the parsed lines plus the new offset.
+// Unparseable lines are skipped silently — telemetry must never fail
+// on a partial write.
+func readTranscript(path string, offset int64) ([]transcriptLine, int64, error) {
+ if path == "" {
+ return nil, offset, nil
+ }
+ if strings.HasPrefix(path, "~/") {
+ if home, err := os.UserHomeDir(); err == nil {
+ path = home + path[1:]
+ }
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, offset, err
+ }
+ defer func() { _ = f.Close() }()
+
+ if offset > 0 {
+ if _, err := f.Seek(offset, io.SeekStart); err != nil {
+ return nil, offset, err
+ }
+ }
+
+ scanner := bufio.NewScanner(io.LimitReader(f, maxBytesPerInvocation))
+ scanner.Buffer(make([]byte, 0, 64*1024), maxScannerBuf)
+
+ var lastAdvance int
+ scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) {
+ advance, token, err := bufio.ScanLines(data, atEOF)
+ lastAdvance = advance
+ return advance, token, err
+ })
+
+ var lines []transcriptLine
+ pos := offset
+ for scanner.Scan() {
+ data := scanner.Bytes()
+ lineLen := int64(lastAdvance)
+
+ var line transcriptLine
+ if err := json.Unmarshal(data, &line); err != nil {
+ pos += lineLen
+ continue
+ }
+ if skipTypes[line.Type] {
+ pos += lineLen
+ continue
+ }
+ line.endOffset = pos + lineLen
+ lines = append(lines, line)
+ pos += lineLen
+ }
+ return lines, pos, scanner.Err()
+}
+
+// coalescedTurn is one logical assistant turn after coalescing streaming
+// fragments by RequestID. `lastSafeOffset` is the byte position we can
+// commit to disk; trailing incomplete turns leave it unchanged so the
+// next hook invocation re-reads them.
+type coalescedTurn struct {
+ line transcriptLine
+ msg assistantMessage
+}
+
+// coalesceAssistants merges consecutive assistant lines sharing the
+// same RequestID into one turn, dropping anything that hasn't reached a
+// `stop_reason`. Returns the safe turns plus the offset that lets the
+// next reader resume immediately after them.
+//
+// User / tool_result lines from the transcript are intentionally NOT
+// returned. We used to walk them to attach a `turnContext` to each
+// assistant turn so the user-prompt that triggered the turn could be
+// stamped onto the LLM-turn span — but Claude Code's transcript
+// stores its *wrapped* prompt (prefixed with `<ide_opened_file>…` and
+// similar IDE context envelopes), not the raw text the user typed.
+// We rely on the UserPromptSubmit hook (`emitUserPrompt`) for the raw
+// user-prompt and on `coding_agent.tool.call` spans for tool bodies,
+// so the transcript reader only needs to surface assistant turns.
+func coalesceAssistants(lines []transcriptLine) ([]coalescedTurn, int64) {
+ var (
+ turns []coalescedTurn
+ pending []transcriptLine
+ lastSafeOffset int64
+ lastSafeLen int
+ )
+
+ markSafe := func(off int64) {
+ lastSafeOffset = off
+ lastSafeLen = len(turns)
+ }
+
+ appendIfComplete := func(line transcriptLine) {
+ var msg assistantMessage
+ if err := json.Unmarshal(line.Message, &msg); err != nil || strings.TrimSpace(msg.StopReason) == "" {
+ return
+ }
+ turns = append(turns, coalescedTurn{line: line, msg: msg})
+ markSafe(line.endOffset)
+ }
+
+ flush := func() {
+ if len(pending) == 0 {
+ return
+ }
+ last := pending[len(pending)-1]
+ var lastMsg assistantMessage
+ if err := json.Unmarshal(last.Message, &lastMsg); err == nil && strings.TrimSpace(lastMsg.StopReason) != "" {
+ merged := mergeAssistantGroup(pending)
+ var msg assistantMessage
+ if err := json.Unmarshal(merged.Message, &msg); err == nil {
+ turns = append(turns, coalescedTurn{line: merged, msg: msg})
+ markSafe(merged.endOffset)
+ }
+ }
+ pending = nil
+ }
+
+ for _, line := range lines {
+ if line.Type == "assistant" {
+ if line.RequestID == "" {
+ flush()
+ appendIfComplete(line)
+ continue
+ }
+ if len(pending) > 0 && pending[0].RequestID != line.RequestID {
+ flush()
+ }
+ pending = append(pending, line)
+ continue
+ }
+ flush()
+ }
+ flush()
+
+ return turns[:lastSafeLen], lastSafeOffset
+}
+
+func mergeAssistantGroup(group []transcriptLine) transcriptLine {
+ if len(group) == 1 {
+ return group[0]
+ }
+ final := group[len(group)-1]
+ var blocks []assistantContentBlock
+ for _, l := range group {
+ var m assistantMessage
+ if err := json.Unmarshal(l.Message, &m); err != nil {
+ continue
+ }
+ blocks = append(blocks, m.Content...)
+ }
+ var finalMsg assistantMessage
+ if err := json.Unmarshal(final.Message, &finalMsg); err != nil {
+ return final
+ }
+ finalMsg.Content = blocks
+ if merged, err := json.Marshal(finalMsg); err == nil {
+ final.Message = merged
+ }
+ return final
+}
diff --git a/cli/internal/coding/hook/codex/codex.go b/cli/internal/coding/hook/codex/codex.go
new file mode 100644
index 00000000..584e07fc
--- /dev/null
+++ b/cli/internal/coding/hook/codex/codex.go
@@ -0,0 +1,25 @@
+// Package codex implements the Codex CLI hook adapter.
+//
+// Codex emits hooks (SessionStart, UserPromptSubmit, PostToolUse, Stop)
+// with a JSON payload, plus a rollout JSONL at
+// ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl that carries token usage
+// the hooks alone don't expose. Adapter logic lives in handle.go.
+package codex
+
+import (
+ "context"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+// New returns a new Codex adapter.
+func New() normalize.Adapter { return &adapter{} }
+
+type adapter struct{}
+
+func (a *adapter) Vendor() string { return semconv.CodingAgentVendorCodex }
+
+func (a *adapter) Handle(ctx context.Context, in normalize.Input) error {
+ return handle(ctx, in)
+}
diff --git a/cli/internal/coding/hook/codex/handle.go b/cli/internal/coding/hook/codex/handle.go
new file mode 100644
index 00000000..45499323
--- /dev/null
+++ b/cli/internal/coding/hook/codex/handle.go
@@ -0,0 +1,1139 @@
+package codex
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/classify"
+ "github.com/openlit/openlit/cli/internal/coding/detect"
+ "github.com/openlit/openlit/cli/internal/coding/git"
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/pricing"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+// codexPayload mirrors the JSON envelope OpenAI Codex sends to a hook
+// command. Field naming follows the protocol as documented at
+// https://developers.openai.com/codex/hooks. Unknown fields are
+// ignored so Codex can add keys without breaking installs.
+type codexPayload struct {
+ HookEventName string `json:"hook_event_name"`
+ SessionID string `json:"session_id"`
+ TurnID string `json:"turn_id"`
+ TranscriptPath string `json:"transcript_path"`
+ Cwd string `json:"cwd"`
+ Model string `json:"model"`
+ Source string `json:"source"`
+ Prompt string `json:"prompt"`
+ ToolName string `json:"tool_name"`
+ ToolUseID string `json:"tool_use_id"`
+ ToolInput json.RawMessage `json:"tool_input"`
+ ToolResponse json.RawMessage `json:"tool_response"`
+ ToolOutput json.RawMessage `json:"tool_output"`
+ ToolDurationMs *float64 `json:"tool_duration_ms"`
+ DurationMs *float64 `json:"duration_ms"`
+ Status string `json:"status"`
+ Error json.RawMessage `json:"error"`
+ Timestamp string `json:"timestamp"`
+ StopHookActive bool `json:"stop_hook_active"`
+ LastAssistantMessage *string `json:"last_assistant_message"`
+
+ // ApprovalMode mirrors Codex's `--approval-mode` (`untrusted`,
+ // `on-failure`, `on-request`, `never`). Codex doesn't always
+ // stamp it, but when it does we treat it as the OTel-canonical
+ // `coding_agent.policy.permission_mode`. Older builds called the
+ // field `approval_mode`; we accept both.
+ ApprovalMode string `json:"approval_mode"`
+ PermissionMode string `json:"permission_mode"`
+}
+
+// handle is the per-invocation entry point invoked by `openlit coding hook`.
+func handle(ctx context.Context, in normalize.Input) error {
+ var p codexPayload
+ if err := json.Unmarshal(in.Payload, &p); err != nil {
+ return nil
+ }
+
+ event := in.Event
+ if event == "" {
+ event = p.HookEventName
+ }
+
+ cwd := strings.TrimSpace(p.Cwd)
+ if cwd == "" {
+ if wd, err := os.Getwd(); err == nil {
+ cwd = wd
+ }
+ }
+ vcs := git.Snapshot(ctx, cwd)
+ cls := classify.Classify(classify.Inputs{
+ // v1: same posture as the Cursor / Claude Code adapters —
+ // no API-key allowlist is wired up at the CLI surface, so
+ // we let the classifier lean on the repo signal alone.
+ APIKeyAllowlistKnown: false,
+ APIKeyOnAllowlist: false,
+ RepoURL: vcs.RepoURL,
+ RepoAllowlist: classify.SplitAllowlist(os.Getenv("OPENLIT_CODING_REPO_ALLOWLIST")),
+ })
+
+ permissionMode := nonEmpty(p.PermissionMode, p.ApprovalMode)
+
+ // Surface subagent linkage as soon as we have it. Codex's
+ // transcript carries this in the `session_meta` record, which is
+ // at or near the top of the rollout JSONL.
+ primeSubagentLink(p)
+
+ switch event {
+ case "SessionStart":
+ return in.Emit.EmitSession(buildSession(in, p, vcs, cls, permissionMode, cwd, "started", time.Time{}))
+
+ case "UserPromptSubmit":
+ stampTurnFragment(p, in.ContentCapture, func(f *sessionstate.CodexTurnFragment) {
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull && p.Prompt != "" {
+ f.Prompt = p.Prompt
+ }
+ if f.StartedAt.IsZero() {
+ f.StartedAt = parseEventTime(p.Timestamp)
+ }
+ })
+ // Cheap event so the chat timeline can show "user submitted
+ // a prompt" even before Stop fires. The full LLM-turn span
+ // is emitted at Stop.
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: p.SessionID,
+ Name: "coding_agent.user_prompt.submit",
+ At: parseEventTime(p.Timestamp),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "coding_agent.turn.id": p.TurnID,
+ "code.cwd": cwd,
+ "gen_ai.request.model": p.Model,
+ },
+ })
+
+ case "PreToolUse":
+ // Pre-event only. The authoritative tool span fires at
+ // PostToolUse to avoid double-counting.
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: p.SessionID,
+ Name: "coding_agent.tool.requested",
+ At: parseEventTime(p.Timestamp),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "coding_agent.turn.id": p.TurnID,
+ "gen_ai.tool.name": p.ToolName,
+ "gen_ai.tool.call.id": p.ToolUseID,
+ "code.cwd": cwd,
+ "gen_ai.request.model": p.Model,
+ },
+ })
+
+ case "PostToolUse":
+ t := buildToolCall(in, p, cwd)
+ _ = in.Emit.EmitToolCall(t)
+ // Detect agent-attributed git commits / PR creations from
+ // shell-style tools. Codex emits `shell` and `local_shell`.
+ // We only attribute when the tool completed successfully —
+ // a failed git invocation does NOT count toward the commit
+ // / PR rollups.
+ if normalizeStatus(p) != "error" {
+ emitGitArtifactsCodex(in, p, cwd)
+ }
+ // apply_patch is Codex's edit tool. Parse the patch body
+ // into per-file LinesAdded / LinesRemoved counts and emit
+ // one EditDecision per file. The decision is `auto_accepted`
+ // because Codex applies patches without an interactive
+ // review step (the diff is shown but the apply is the
+ // default action) — matches today's auto_accept behavior on
+ // Cursor's afterFileEdit.
+ if isApplyPatchTool(p.ToolName) && normalizeStatus(p) != "error" {
+ emitApplyPatchEditDecisions(in, p, cwd)
+ }
+ // Cache the call on the turn fragment so the Stop event can
+ // render it as a `tool_call` / `tool_call_response` part in
+ // `gen_ai.input.messages` + `gen_ai.output.messages`.
+ stampTurnFragment(p, in.ContentCapture, func(f *sessionstate.CodexTurnFragment) {
+ rec := sessionstate.CodexToolRecord{
+ ToolName: p.ToolName,
+ ToolUseID: p.ToolUseID,
+ Status: normalizeStatus(p),
+ Cwd: cwd,
+ CompletedAt: p.Timestamp,
+ DurationMs: durationMsOr(p.ToolDurationMs, p.DurationMs),
+ }
+ if rec.Status == "error" {
+ rec.ErrorMessage = errorMessage(p.Error)
+ }
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ if len(p.ToolInput) > 0 {
+ rec.ToolInput = string(p.ToolInput)
+ }
+ resp := p.ToolResponse
+ if len(resp) == 0 {
+ resp = p.ToolOutput
+ }
+ if len(resp) > 0 {
+ rec.ToolResponse = string(resp)
+ }
+ }
+ f.Tools = append(f.Tools, rec)
+ })
+ return nil
+
+ case "Stop":
+ // Stop closes one turn. Drain the turn fragment, tail the
+ // transcript for authoritative token usage, and emit one
+ // `coding_agent.llm.turn` span — the canonical
+ // "generation" record per OTel GenAI.
+ emitTurnOnStop(in, p, cwd, permissionMode)
+ // Codex has NO `SessionEnd` event — the rollout just ends
+ // when the user closes the Codex CLI. We periodically
+ // re-emit the session-root span so the Sessions row lights
+ // up with up-to-the-turn rollups. Deterministic SpanIDs
+ // collapse all re-emits onto the same `otel_traces` row,
+ // so this is purely a wire / CPU optimisation; throttle to
+ // at most once per ~60s of wall-clock so long Codex
+ // sessions (which can fire dozens of Stop events per
+ // minute) don't ship a redundant session-root span per
+ // turn.
+ if shouldEmitCodexSessionRoot(p.SessionID) {
+ s := buildSession(in, p, vcs, cls, permissionMode, cwd, "ended", parseEventTime(p.Timestamp))
+ s.Outcome = semconv.CodingAgentSessionOutcomeCompleted
+ _ = in.Emit.EmitSession(s)
+ markCodexSessionRootEmitted(p.SessionID)
+ }
+ // Low-cost loop event so the Sessions tab can count turns
+ // without scanning the LLM-turn span every time.
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: p.SessionID,
+ Name: "coding_agent.session.loop.stop",
+ At: parseEventTime(p.Timestamp),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "coding_agent.hook.event": event,
+ "coding_agent.turn.id": p.TurnID,
+ "coding_agent.session.loop.kind": "assistant_turn_end",
+ "coding_agent.session.outcome": semconv.CodingAgentSessionOutcomeCompleted,
+ "codex.stop_hook_active": p.StopHookActive,
+ },
+ })
+
+ default:
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: p.SessionID,
+ Name: "coding_agent.hook.unknown_event",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.hook.event": event,
+ "coding_agent.client": in.Vendor,
+ },
+ })
+ }
+}
+
+// codexSessionRootMinInterval is the minimum wall-clock between
+// session-root re-emits during a Codex chat. Deterministic SpanIDs
+// collapse repeated emissions onto the same `otel_traces` row, but
+// the OTLP send still costs CPU + bytes on every Stop event. 60s is
+// a sane middle ground: dashboards refresh fast enough that the
+// Sessions row lights up within a single observation cycle, while
+// dense back-and-forth sessions don't ship one duplicate root span
+// per turn.
+const codexSessionRootMinInterval = 60 * time.Second
+
+// shouldEmitCodexSessionRoot reports whether enough wall-clock has
+// passed since the last session-root emission for this session to
+// justify another. Always allows the first emission (cache miss).
+func shouldEmitCodexSessionRoot(sessionID string) bool {
+ if sessionID == "" {
+ return true
+ }
+ st := sessionstate.Load(sessionID, "codex")
+ if st == nil || st.LastSessionRootEmitAt.IsZero() {
+ return true
+ }
+ return time.Since(st.LastSessionRootEmitAt) >= codexSessionRootMinInterval
+}
+
+// markCodexSessionRootEmitted records that we just emitted the
+// session-root span so the next Stop within the throttle window
+// skips re-emission.
+func markCodexSessionRootEmitted(sessionID string) {
+ if sessionID == "" {
+ return
+ }
+ st := sessionstate.Load(sessionID, "codex")
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ st.LastSessionRootEmitAt = time.Now()
+ sessionstate.Save(sessionID, "codex", st)
+}
+
+// buildSession produces the canonical `coding_agent.session` span. We
+// emit it on SessionStart. Codex doesn't have a `SessionEnd` event;
+// the per-turn `coding_agent.llm.turn` spans accumulate naturally
+// and the session row in the UI rolls them up.
+func buildSession(
+ in normalize.Input,
+ p codexPayload,
+ vcs git.Context,
+ cls classify.Classification,
+ permissionMode, cwd, kind string,
+ endedAt time.Time,
+) normalize.Session {
+ s := normalize.Session{
+ SessionID: p.SessionID,
+ ConversationID: p.SessionID,
+ Vendor: in.Vendor,
+ Model: p.Model,
+ StartedAt: parseEventTime(p.Timestamp),
+ EndedAt: endedAt,
+ PermissionMode: permissionMode,
+ CWD: cwd,
+ RepoURL: vcs.RepoURL,
+ HeadSHA: vcs.HeadSHA,
+ BranchName: vcs.Branch,
+ VCSDirty: vcs.Dirty,
+ UserClassification: cls.Value,
+ ClassificationReason: cls.Reason,
+ Extras: map[string]string{
+ "coding_agent.hook.event": p.HookEventName,
+ "codex.session.lifecycle": kind,
+ },
+ }
+ if p.TranscriptPath != "" {
+ s.Extras["coding_agent.session.transcript_path"] = p.TranscriptPath
+ }
+ if p.Source != "" {
+ s.Extras["codex.session.source"] = p.Source
+ }
+ // Carry the subagent-link metadata (if any) onto the session
+ // span — the UI uses it to fold this row under the parent chat.
+ if st := sessionstate.Load(p.SessionID, "codex"); st != nil && st.CodexSubagent != nil {
+ s.Extras["coding_agent.agent.parent_id"] = st.CodexSubagent.ParentSessionID
+ s.Extras["coding_agent.subagent.type"] = "task"
+ if st.CodexSubagent.AgentRole != "" {
+ s.Extras["codex.agent.role"] = st.CodexSubagent.AgentRole
+ }
+ if st.CodexSubagent.AgentNickname != "" {
+ s.Extras["codex.agent.nickname"] = st.CodexSubagent.AgentNickname
+ }
+ }
+ return s
+}
+
+// buildToolCall produces a `coding_agent.tool.call` span for one
+// PostToolUse event. We mirror the Cursor adapter: name/id/cwd are
+// always stamped, bodies (args / result) only land in full capture.
+func buildToolCall(in normalize.Input, p codexPayload, cwd string) normalize.ToolCall {
+ durMs := durationMsOr(p.ToolDurationMs, p.DurationMs)
+ now := parseEventTime(p.Timestamp)
+ if now.IsZero() {
+ now = time.Now()
+ }
+ t := normalize.ToolCall{
+ SessionID: p.SessionID,
+ ToolName: p.ToolName,
+ ToolUseID: p.ToolUseID,
+ Vendor: in.Vendor,
+ Model: p.Model,
+ WorkingDir: cwd,
+ StartedAt: now.Add(-time.Duration(durMs) * time.Millisecond),
+ EndedAt: now,
+ }
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ if len(p.ToolInput) > 0 {
+ t.Args = string(p.ToolInput)
+ }
+ resp := p.ToolResponse
+ if len(resp) == 0 {
+ resp = p.ToolOutput
+ }
+ if len(resp) > 0 {
+ t.Result = string(resp)
+ }
+ }
+ // Shell / apply_patch are the most common codex tools — expose
+ // the command head so dashboards can render "ran: ls" without
+ // having to parse JSON.
+ if cmd := commandFromToolInput(p.ToolName, p.ToolInput, in.ContentCapture); cmd != "" {
+ t.Command = cmd
+ }
+ if normalizeStatus(p) == "error" {
+ t.Errored = true
+ t.ErrorMsg = errorMessage(p.Error)
+ }
+ return t
+}
+
+// emitTurnOnStop builds and emits one `coding_agent.llm.turn` span
+// from the cached turn fragment + a transcript-derived token snapshot.
+// This is the OTel-canonical "generation" record: a single LLM call
+// with input messages, output messages, tokens, and cost.
+//
+// The shape of `gen_ai.input.messages` and `gen_ai.output.messages` is
+// produced centrally in `cli/internal/otlp/attrs.go` from the typed
+// fields we set here (Prompt, Response). Adapters never serialise
+// that JSON themselves — keeping the OTel GenAI spec-compliance check
+// in one place. Tool calls + tool results that bracket this turn are
+// emitted as their own `coding_agent.tool.call` spans rather than
+// folded into the LLM-turn messages JSON, so a single turn's
+// messages stay well under the span-attribute size cap regardless of
+// how chatty the tool layer was.
+func emitTurnOnStop(in normalize.Input, p codexPayload, cwd, permissionMode string) {
+ st := sessionstate.Load(p.SessionID, "codex")
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ frag := loadTurnFragment(st, p.TurnID)
+ if frag == nil {
+ frag = &sessionstate.CodexTurnFragment{TurnID: p.TurnID}
+ }
+ if p.Model != "" {
+ frag.Model = p.Model
+ }
+ if p.Source != "" {
+ frag.Source = p.Source
+ }
+ frag.StopHookActive = p.StopHookActive
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull &&
+ p.LastAssistantMessage != nil && *p.LastAssistantMessage != "" {
+ frag.LastAssistantMessage = *p.LastAssistantMessage
+ }
+
+ completedAt := parseEventTime(p.Timestamp)
+ if completedAt.IsZero() {
+ completedAt = time.Now()
+ }
+ startedAt := frag.StartedAt
+ if startedAt.IsZero() {
+ startedAt = completedAt
+ }
+
+ turn := normalize.LLMTurn{
+ SessionID: p.SessionID,
+ ConversationID: p.SessionID,
+ GenerationID: p.TurnID,
+ Vendor: in.Vendor,
+ Model: frag.Model,
+ StartedAt: startedAt,
+ EndedAt: completedAt,
+ }
+
+ // Token usage: prefer the transcript-derived per-turn delta —
+ // subtract the pre-model baseline from the final cumulative.
+ transcriptPath := strings.TrimSpace(p.TranscriptPath)
+ if transcriptPath == "" {
+ // Fallback: scan ~/.codex/sessions for a rollout whose
+ // first line contains our session id. We look at today +
+ // yesterday so wrapped-midnight sessions still attribute
+ // usage.
+ transcriptPath = findRolloutForSession(p.SessionID)
+ }
+ if snap, ok := readTokenUsageForTurn(transcriptPath, p.TurnID); ok {
+ turn.InputTokens = snap.TurnUsage.InputTokens
+ turn.OutputTokens = snap.TurnUsage.OutputTokens
+ turn.TotalTokens = snap.TurnUsage.TotalTokens
+ if turn.TotalTokens == 0 {
+ turn.TotalTokens = turn.InputTokens + turn.OutputTokens
+ }
+ turn.CacheReadTokens = snap.TurnUsage.CachedInputTokens
+ if rate := pricing.Lookup(turn.Model); turn.Model != "" {
+ // OpenAI's prompt caching is implicit — the rollout
+ // only surfaces `cached_input_tokens` (reads). There
+ // is no separate cache-write counter, so we pass 0
+ // for cacheCreation.
+ turn.CostUSD = rate.Cost(turn.InputTokens, turn.OutputTokens, turn.CacheReadTokens, 0)
+ }
+ if snap.TurnUsage.ReasoningOutputTokens > 0 {
+ if turn.Extras == nil {
+ turn.Extras = map[string]string{}
+ }
+ turn.Extras["coding_agent.llm.reasoning.tokens"] = formatInt(snap.TurnUsage.ReasoningOutputTokens)
+ }
+ }
+
+ turn.FinishReasons = []string{"stop"}
+ // Codex doesn't expose the cumulative input separately from
+ // cached input; surface the model context window when we have it
+ // so dashboards can show "headroom" pills.
+ if turn.Extras == nil {
+ turn.Extras = map[string]string{}
+ }
+ if frag.Source != "" {
+ turn.Extras["codex.source"] = frag.Source
+ }
+ if cwd != "" {
+ turn.Extras["code.cwd"] = cwd
+ }
+ if permissionMode != "" {
+ turn.Extras["coding_agent.policy.permission_mode"] = permissionMode
+ }
+ if frag.StopHookActive {
+ turn.Extras["codex.stop_hook_active"] = "true"
+ }
+ if st.CodexSubagent != nil && st.CodexSubagent.ParentSessionID != "" {
+ turn.Extras["coding_agent.agent.parent_id"] = st.CodexSubagent.ParentSessionID
+ turn.Extras["coding_agent.subagent.type"] = "task"
+ }
+ if len(turn.Extras) == 0 {
+ turn.Extras = nil
+ }
+
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ if s := strings.TrimSpace(frag.Prompt); s != "" {
+ turn.Prompt = s
+ }
+ if s := strings.TrimSpace(frag.LastAssistantMessage); s != "" {
+ turn.Response = s
+ }
+ // Tool calls + tool results are captured as their own
+ // `coding_agent.tool.call` spans (with
+ // `gen_ai.tool.call.arguments` / `gen_ai.tool.call.result`)
+ // at PreToolUse / PostToolUse time. We deliberately do NOT
+ // duplicate them onto the LLM-turn messages JSON; the chat
+ // view interleaves the two span kinds by timestamp.
+ }
+
+ _ = in.Emit.EmitLLMTurn(turn)
+
+ // Drain the turn fragment — it's served its purpose. We keep the
+ // session state itself so the next turn (still in this session)
+ // finds the cached subagent link and identity.
+ clearTurnFragment(st, p.TurnID)
+ sessionstate.Save(p.SessionID, "codex", st)
+}
+
+// stampTurnFragment loads or creates the turn fragment for `p.TurnID`,
+// applies the caller's mutation, then persists. We bound CodexTurns to
+// 16 entries so a marathon session doesn't grow the on-disk cache
+// unboundedly. The Stop event drains its own fragment.
+func stampTurnFragment(p codexPayload, capture string, mutate func(*sessionstate.CodexTurnFragment)) {
+ if p.SessionID == "" || p.TurnID == "" {
+ return
+ }
+ _ = capture // reserved — gated content has already been filtered at the call site
+ st := sessionstate.Load(p.SessionID, "codex")
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ if st.CodexTurns == nil {
+ st.CodexTurns = map[string]*sessionstate.CodexTurnFragment{}
+ }
+ f, ok := st.CodexTurns[p.TurnID]
+ if !ok {
+ f = &sessionstate.CodexTurnFragment{TurnID: p.TurnID, StartedAt: parseEventTime(p.Timestamp)}
+ st.CodexTurns[p.TurnID] = f
+ }
+ if f.Model == "" && p.Model != "" {
+ f.Model = p.Model
+ }
+ if f.Source == "" && p.Source != "" {
+ f.Source = p.Source
+ }
+ mutate(f)
+ pruneTurnFragments(st)
+ sessionstate.Save(p.SessionID, "codex", st)
+}
+
+// pruneTurnFragments keeps the per-session map at 16 entries. We pick
+// the oldest by StartedAt; ties on the zero value drop arbitrarily,
+// which is safe because every fragment is independently drainable on
+// its own Stop event.
+func pruneTurnFragments(st *sessionstate.State) {
+ const cap = 16
+ if len(st.CodexTurns) <= cap {
+ return
+ }
+ type ageKey struct {
+ key string
+ t time.Time
+ }
+ ages := make([]ageKey, 0, len(st.CodexTurns))
+ for k, v := range st.CodexTurns {
+ ages = append(ages, ageKey{key: k, t: v.StartedAt})
+ }
+ // stable enough — sort ascending so the oldest sort to the front
+ for i := 1; i < len(ages); i++ {
+ for j := i; j > 0 && ages[j-1].t.After(ages[j].t); j-- {
+ ages[j-1], ages[j] = ages[j], ages[j-1]
+ }
+ }
+ for i := 0; i < len(ages)-cap; i++ {
+ delete(st.CodexTurns, ages[i].key)
+ }
+}
+
+func loadTurnFragment(st *sessionstate.State, turnID string) *sessionstate.CodexTurnFragment {
+ if st == nil || st.CodexTurns == nil {
+ return nil
+ }
+ return st.CodexTurns[turnID]
+}
+
+func clearTurnFragment(st *sessionstate.State, turnID string) {
+ if st == nil || st.CodexTurns == nil {
+ return
+ }
+ delete(st.CodexTurns, turnID)
+ if len(st.CodexTurns) == 0 {
+ st.CodexTurns = nil
+ }
+}
+
+// primeSubagentLink reads the transcript's `session_meta` block once
+// per session and caches the parent linkage. Cheap because we only
+// scan to the first matching line; idempotent because subsequent calls
+// return early when the cache is already populated.
+func primeSubagentLink(p codexPayload) {
+ if p.SessionID == "" {
+ return
+ }
+ st := sessionstate.Load(p.SessionID, "codex")
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ if st.CodexSubagent != nil {
+ return
+ }
+ path := strings.TrimSpace(p.TranscriptPath)
+ if path == "" {
+ path = findRolloutForSession(p.SessionID)
+ }
+ if path == "" {
+ return
+ }
+ meta, ok := readSessionMeta(path)
+ if !ok || meta.ThreadSource != "subagent" || meta.ParentSessionID == "" {
+ return
+ }
+ st.CodexSubagent = &sessionstate.CodexSubagentLink{
+ ParentSessionID: meta.ParentSessionID,
+ AgentRole: meta.AgentRole,
+ AgentNickname: meta.AgentNickname,
+ AgentDepth: meta.AgentDepth,
+ }
+ sessionstate.Save(p.SessionID, "codex", st)
+}
+
+// normalizeStatus maps Codex's PostToolUse `status` / `error` /
+// response-shape signals onto our `completed` / `error` enum.
+func normalizeStatus(p codexPayload) string {
+ if s := canonicalStatus(p.Status); s != "" {
+ return s
+ }
+ if hasErrorEvidence(p.Error) {
+ return "error"
+ }
+ resp := p.ToolResponse
+ if len(resp) == 0 {
+ resp = p.ToolOutput
+ }
+ if s := statusFromToolResponse(resp); s != "" {
+ return s
+ }
+ return ""
+}
+
+func canonicalStatus(raw string) string {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case "error", "failed", "failure":
+ return "error"
+ case "completed", "complete", "success", "succeeded", "ok":
+ return "completed"
+ }
+ return ""
+}
+
+func hasErrorEvidence(raw json.RawMessage) bool {
+ if len(raw) == 0 || string(raw) == "null" {
+ return false
+ }
+ var v any
+ if err := json.Unmarshal(raw, &v); err != nil {
+ return true
+ }
+ return !emptyJSONValue(v)
+}
+
+func statusFromToolResponse(raw json.RawMessage) string {
+ if len(raw) == 0 || string(raw) == "null" {
+ return ""
+ }
+ var v any
+ if err := json.Unmarshal(raw, &v); err != nil {
+ return ""
+ }
+ return statusFromValue(v)
+}
+
+func statusFromValue(v any) string {
+ switch x := v.(type) {
+ case map[string]any:
+ for _, key := range []string{"status", "state"} {
+ if s := canonicalStatus(stringField(x, key)); s != "" {
+ return s
+ }
+ }
+ for _, key := range []string{"is_error", "isError"} {
+ if b, ok := boolField(x, key); ok {
+ if b {
+ return "error"
+ }
+ return "completed"
+ }
+ }
+ if b, ok := boolField(x, "success"); ok {
+ if b {
+ return "completed"
+ }
+ return "error"
+ }
+ for _, key := range []string{"exit_code", "exitCode"} {
+ if code, ok := numberField(x, key); ok {
+ if code == 0 {
+ return "completed"
+ }
+ return "error"
+ }
+ }
+ // Positive signal: a non-empty tool response with no
+ // explicit error / success / exit_code field is most often
+ // a successful tool call that simply returned a plain
+ // payload (Codex's `read_file` is a common shape — just a
+ // `{ "content": "..." }` body). Treating these as
+ // completed lets dashboards show "✓ tool" instead of a
+ // faded "unknown" pill. We deliberately only do this when
+ // there's at least one field — an empty map is still
+ // unknown.
+ if len(x) > 0 {
+ return "completed"
+ }
+ case string:
+ return canonicalStatus(x)
+ }
+ return ""
+}
+
+func emptyJSONValue(v any) bool {
+ switch x := v.(type) {
+ case nil:
+ return true
+ case bool:
+ return !x
+ case string:
+ return strings.TrimSpace(x) == ""
+ case float64:
+ return x == 0
+ case []any:
+ return len(x) == 0
+ case map[string]any:
+ return len(x) == 0
+ }
+ return false
+}
+
+func stringField(m map[string]any, key string) string {
+ if v, ok := m[key]; ok {
+ if s, ok := v.(string); ok {
+ return s
+ }
+ }
+ return ""
+}
+
+func boolField(m map[string]any, key string) (bool, bool) {
+ v, ok := m[key]
+ if !ok {
+ return false, false
+ }
+ b, ok := v.(bool)
+ return b, ok
+}
+
+func numberField(m map[string]any, key string) (float64, bool) {
+ v, ok := m[key]
+ if !ok {
+ return 0, false
+ }
+ switch n := v.(type) {
+ case float64:
+ return n, true
+ case int:
+ return float64(n), true
+ }
+ return 0, false
+}
+
+func errorMessage(raw json.RawMessage) string {
+ if len(raw) == 0 || string(raw) == "null" {
+ return ""
+ }
+ var s string
+ if err := json.Unmarshal(raw, &s); err == nil {
+ return s
+ }
+ var obj struct {
+ Message string `json:"message"`
+ }
+ if err := json.Unmarshal(raw, &obj); err == nil && obj.Message != "" {
+ return obj.Message
+ }
+ return string(raw)
+}
+
+// commandFromToolInput peeks at Codex's `tool_input` to pull the
+// canonical command string for shell / apply_patch tools. In metadata
+// or minimal mode we keep only the binary head so the trace-detail
+// "Shell" pill still works without leaking flags. Full mode returns
+// the entire command.
+func commandFromToolInput(toolName string, raw json.RawMessage, capture string) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return ""
+ }
+ pickStr := func(keys ...string) string {
+ for _, k := range keys {
+ v, ok := m[k]
+ if !ok {
+ continue
+ }
+ var s string
+ if err := json.Unmarshal(v, &s); err == nil && s != "" {
+ return s
+ }
+ }
+ return ""
+ }
+ cmd := ""
+ switch strings.ToLower(toolName) {
+ case "shell", "local_shell", "local-shell":
+ cmd = pickStr("command", "cmd", "shell")
+ if cmd == "" {
+ // some shells ship an array — fall back to joining
+ if arr, ok := m["command"]; ok {
+ var parts []string
+ if err := json.Unmarshal(arr, &parts); err == nil {
+ cmd = strings.Join(parts, " ")
+ }
+ }
+ }
+ case "apply_patch", "apply-patch":
+ // apply_patch carries a diff — surface the first hunk header
+ // so dashboards can show "edited <file>" without leaking the
+ // patch body.
+ if patch := pickStr("input", "patch"); patch != "" {
+ for _, line := range strings.Split(patch, "\n") {
+ if strings.HasPrefix(line, "*** ") {
+ return strings.TrimSpace(line)
+ }
+ }
+ }
+ }
+ if cmd == "" {
+ return ""
+ }
+ cmd = strings.TrimSpace(cmd)
+ if capture == semconv.CodingAgentContentCaptureFull {
+ return cmd
+ }
+ if i := strings.IndexAny(cmd, " \t"); i > 0 {
+ return cmd[:i]
+ }
+ return cmd
+}
+
+// isApplyPatchTool reports whether the tool name is Codex's edit tool.
+func isApplyPatchTool(name string) bool {
+ return strings.ToLower(name) == "apply_patch"
+}
+
+// emitApplyPatchEditDecisions parses Codex's apply_patch input into
+// per-file unified-diff line counts and emits one EditDecision span
+// per file. The session-state LOC / accept counters are bumped at the
+// same time so the session-root span (re-emitted on Stop) carries the
+// running rollups.
+func emitApplyPatchEditDecisions(in normalize.Input, p codexPayload, cwd string) {
+ patch := applyPatchBody(p.ToolInput)
+ if patch == "" {
+ return
+ }
+ counts := detect.CountPatchLines(patch)
+ if len(counts) == 0 {
+ return
+ }
+ now := parseEventTime(p.Timestamp)
+ if now.IsZero() {
+ now = time.Now()
+ }
+ var totalAdded, totalRemoved int
+ for _, c := range counts {
+ _ = in.Emit.EmitEditDecision(normalize.EditDecision{
+ SessionID: p.SessionID,
+ Decision: semconv.CodingAgentEditDecisionAutoAccepted,
+ Source: semconv.CodingAgentEditDecisionSourcePolicy,
+ Tool: "apply_patch",
+ Language: guessLanguageCodex(c.FilePath),
+ LinesAdded: c.LinesAdded,
+ LinesRemoved: c.LinesRemoved,
+ FilePath: c.FilePath,
+ Vendor: in.Vendor,
+ At: now,
+ })
+ totalAdded += c.LinesAdded
+ totalRemoved += c.LinesRemoved
+ }
+ if totalAdded > 0 || totalRemoved > 0 {
+ sessionstate.BumpCodeCounters(p.SessionID, in.Vendor, totalAdded, totalRemoved, totalAdded, 0, len(counts), 0)
+ }
+ _ = cwd
+}
+
+// applyPatchBody extracts the patch text from Codex's apply_patch
+// tool_input. Tries `input`, `patch`, and `diff` field names — Codex
+// has shipped each in different rollout versions.
+func applyPatchBody(raw json.RawMessage) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return ""
+ }
+ for _, k := range []string{"input", "patch", "diff"} {
+ v, ok := m[k]
+ if !ok || len(v) == 0 {
+ continue
+ }
+ var s string
+ if err := json.Unmarshal(v, &s); err == nil && s != "" {
+ return s
+ }
+ }
+ return ""
+}
+
+// emitGitArtifactsCodex inspects Codex's shell-style tool input/output
+// and emits GitCommit / GitPullRequest spans + bumps the counters when
+// the command matched. Codex packs the shell tool's command in
+// `tool_input.command` (string OR array of strings) and the stdout in
+// `tool_response` / `tool_output`.
+func emitGitArtifactsCodex(in normalize.Input, p codexPayload, cwd string) {
+ if !isShellTool(p.ToolName) {
+ return
+ }
+ cmd := shellCommand(p.ToolInput)
+ if cmd == "" {
+ return
+ }
+ stdout := shellStdout(p.ToolResponse, p.ToolOutput)
+ now := parseEventTime(p.Timestamp)
+ if now.IsZero() {
+ now = time.Now()
+ }
+ if detect.IsGitCommit(cmd) {
+ message := ""
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ message = detect.ExtractCommitMessage(cmd)
+ }
+ _ = in.Emit.EmitGitCommit(normalize.GitCommit{
+ SessionID: p.SessionID,
+ Vendor: in.Vendor,
+ Tool: p.ToolName,
+ SHA: detect.ExtractCommitSHA(stdout),
+ Message: message,
+ WorkingDir: cwd,
+ At: now,
+ })
+ sessionstate.BumpCommitCount(p.SessionID, in.Vendor)
+ }
+ if detect.IsPullRequest(cmd) {
+ url, num := detect.ExtractPRURLAndNumber(stdout)
+ title := ""
+ if in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ title = detect.ExtractPRTitle(cmd)
+ }
+ _ = in.Emit.EmitGitPullRequest(normalize.GitPullRequest{
+ SessionID: p.SessionID,
+ Vendor: in.Vendor,
+ Tool: p.ToolName,
+ URL: url,
+ Number: num,
+ Title: title,
+ WorkingDir: cwd,
+ At: now,
+ })
+ sessionstate.BumpPRCount(p.SessionID, in.Vendor)
+ }
+}
+
+func isShellTool(name string) bool {
+ switch strings.ToLower(name) {
+ case "shell", "local_shell", "local-shell":
+ return true
+ }
+ return false
+}
+
+// shellCommand pulls the command string from Codex's shell tool
+// input. The field is sometimes a plain string, sometimes an array.
+func shellCommand(raw json.RawMessage) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return ""
+ }
+ for _, k := range []string{"command", "cmd", "shell"} {
+ v, ok := m[k]
+ if !ok || len(v) == 0 {
+ continue
+ }
+ var s string
+ if err := json.Unmarshal(v, &s); err == nil && s != "" {
+ return s
+ }
+ var arr []string
+ if err := json.Unmarshal(v, &arr); err == nil && len(arr) > 0 {
+ return strings.Join(arr, " ")
+ }
+ }
+ return ""
+}
+
+// shellStdout extracts a string stdout body from Codex's tool
+// response. Tries `tool_response` first (newer rollouts) then
+// `tool_output`. Both have shipped as either a plain string or
+// `{"output":"..."}` / `{"stdout":"..."}`.
+func shellStdout(resp, out json.RawMessage) string {
+ for _, raw := range []json.RawMessage{resp, out} {
+ if len(raw) == 0 {
+ continue
+ }
+ var s string
+ if err := json.Unmarshal(raw, &s); err == nil && s != "" {
+ return s
+ }
+ var m struct {
+ Output string `json:"output"`
+ Stdout string `json:"stdout"`
+ }
+ if err := json.Unmarshal(raw, &m); err == nil {
+ if m.Output != "" {
+ return m.Output
+ }
+ if m.Stdout != "" {
+ return m.Stdout
+ }
+ }
+ }
+ return ""
+}
+
+// guessLanguageCodex maps a file extension onto a language tag for
+// the edit-decision metric. Returns "" when the extension isn't
+// recognised so dashboards can group those into "other".
+func guessLanguageCodex(filePath string) string {
+ if filePath == "" {
+ return ""
+ }
+ idx := strings.LastIndex(filePath, ".")
+ if idx < 0 || idx == len(filePath)-1 {
+ return ""
+ }
+ switch strings.ToLower(filePath[idx:]) {
+ case ".go":
+ return "go"
+ case ".ts", ".tsx":
+ return "typescript"
+ case ".js", ".jsx", ".mjs", ".cjs":
+ return "javascript"
+ case ".py":
+ return "python"
+ case ".rs":
+ return "rust"
+ case ".java":
+ return "java"
+ case ".rb":
+ return "ruby"
+ case ".php":
+ return "php"
+ case ".c", ".h":
+ return "c"
+ case ".cpp", ".cc", ".cxx", ".hpp", ".hh", ".hxx":
+ return "cpp"
+ case ".cs":
+ return "csharp"
+ case ".sh", ".bash", ".zsh":
+ return "shell"
+ case ".md", ".markdown":
+ return "markdown"
+ case ".json":
+ return "json"
+ case ".yml", ".yaml":
+ return "yaml"
+ case ".sql":
+ return "sql"
+ case ".html", ".htm":
+ return "html"
+ case ".css", ".scss", ".sass":
+ return "css"
+ }
+ return ""
+}
+
+func parseEventTime(raw string) time.Time {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return time.Now()
+ }
+ if t, err := time.Parse(time.RFC3339Nano, raw); err == nil {
+ return t
+ }
+ if t, err := time.Parse(time.RFC3339, raw); err == nil {
+ return t
+ }
+ return time.Now()
+}
+
+func durationMsOr(primary, secondary *float64) int64 {
+ if primary != nil && *primary > 0 {
+ return int64(*primary)
+ }
+ if secondary != nil && *secondary > 0 {
+ return int64(*secondary)
+ }
+ return 0
+}
+
+func nonEmpty(a, b string) string {
+ if a != "" {
+ return a
+ }
+ return b
+}
+
+func formatInt(n int64) string {
+ if n == 0 {
+ return "0"
+ }
+ // avoid pulling in strconv for one call site
+ return jsonNumberString(n)
+}
+
+// jsonNumberString stringifies an int64 by marshalling through
+// encoding/json — cheap and avoids a strconv import for the one
+// numeric tag we render today.
+func jsonNumberString(n int64) string {
+ b, _ := json.Marshal(n)
+ return string(b)
+}
diff --git a/cli/internal/coding/hook/codex/handle_test.go b/cli/internal/coding/hook/codex/handle_test.go
new file mode 100644
index 00000000..d91f675d
--- /dev/null
+++ b/cli/internal/coding/hook/codex/handle_test.go
@@ -0,0 +1,389 @@
+package codex
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+)
+
+// recordingEmitter is a normalize.Emitter implementation that captures
+// every call so tests can assert on the order + content of emissions.
+type recordingEmitter struct {
+ sessions []normalize.Session
+ toolCalls []normalize.ToolCall
+ editDecisions []normalize.EditDecision
+ llmTurns []normalize.LLMTurn
+ subagents []normalize.Subagent
+ events []normalize.EventEmission
+ gitCommits []normalize.GitCommit
+ gitPRs []normalize.GitPullRequest
+}
+
+func (e *recordingEmitter) EmitSession(s normalize.Session) error {
+ e.sessions = append(e.sessions, s)
+ return nil
+}
+func (e *recordingEmitter) EmitToolCall(t normalize.ToolCall) error {
+ e.toolCalls = append(e.toolCalls, t)
+ return nil
+}
+func (e *recordingEmitter) EmitEditDecision(d normalize.EditDecision) error {
+ e.editDecisions = append(e.editDecisions, d)
+ return nil
+}
+func (e *recordingEmitter) EmitLLMTurn(t normalize.LLMTurn) error {
+ e.llmTurns = append(e.llmTurns, t)
+ return nil
+}
+func (e *recordingEmitter) EmitSubagent(s normalize.Subagent) error {
+ e.subagents = append(e.subagents, s)
+ return nil
+}
+func (e *recordingEmitter) EmitEvent(ev normalize.EventEmission) error {
+ e.events = append(e.events, ev)
+ return nil
+}
+func (e *recordingEmitter) EmitGitCommit(c normalize.GitCommit) error {
+ e.gitCommits = append(e.gitCommits, c)
+ return nil
+}
+func (e *recordingEmitter) EmitGitPullRequest(p normalize.GitPullRequest) error {
+ e.gitPRs = append(e.gitPRs, p)
+ return nil
+}
+
+// withIsolatedCache redirects sessionstate's on-disk cache to a tmp
+// dir so tests don't leak state between runs.
+func withIsolatedCache(t *testing.T) {
+ t.Helper()
+ dir := t.TempDir()
+ t.Setenv("XDG_CACHE_HOME", dir)
+ if home := os.Getenv("HOME"); home != "" {
+ t.Setenv("HOME", dir)
+ }
+}
+
+func TestCodexEndToEndOneTurn(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ in := func(event string, payload any) normalize.Input {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("payload marshal: %v", err)
+ }
+ return normalize.Input{
+ Vendor: "codex",
+ Event: event,
+ Payload: body,
+ ContentCapture: "full",
+ Emit: em,
+ }
+ }
+
+ sid := "cdx-session-1"
+ turn := "turn-1"
+ now := time.Now().UTC().Format(time.RFC3339Nano)
+
+ if err := handle(context.Background(), in("SessionStart", map[string]any{
+ "hook_event_name": "SessionStart",
+ "session_id": sid,
+ "cwd": "/tmp/work",
+ "model": "gpt-5",
+ "source": "startup",
+ "timestamp": now,
+ })); err != nil {
+ t.Fatalf("SessionStart: %v", err)
+ }
+ if err := handle(context.Background(), in("UserPromptSubmit", map[string]any{
+ "hook_event_name": "UserPromptSubmit",
+ "session_id": sid,
+ "turn_id": turn,
+ "prompt": "refactor sessionstate",
+ "timestamp": now,
+ })); err != nil {
+ t.Fatalf("UserPromptSubmit: %v", err)
+ }
+ if err := handle(context.Background(), in("PostToolUse", map[string]any{
+ "hook_event_name": "PostToolUse",
+ "session_id": sid,
+ "turn_id": turn,
+ "tool_name": "shell",
+ "tool_use_id": "call_1",
+ "tool_input": json.RawMessage(`{"command":"ls -la"}`),
+ "tool_response": json.RawMessage(`{"stdout":"foo bar","exit_code":0}`),
+ "tool_duration_ms": 25.0,
+ "status": "completed",
+ "timestamp": now,
+ })); err != nil {
+ t.Fatalf("PostToolUse: %v", err)
+ }
+ lastMsg := "Refactored, see diff."
+ if err := handle(context.Background(), in("Stop", map[string]any{
+ "hook_event_name": "Stop",
+ "session_id": sid,
+ "turn_id": turn,
+ "last_assistant_message": lastMsg,
+ "timestamp": now,
+ })); err != nil {
+ t.Fatalf("Stop: %v", err)
+ }
+
+ // Sessions: SessionStart → 1, Stop → 1 (Codex has no SessionEnd
+ // event, so we re-emit the session-root span on every Stop with
+ // outcome=completed). The deterministic span IDs in the otlp
+ // emitter dedupe these into a single `otel_traces` row.
+ if len(em.sessions) != 2 {
+ t.Fatalf("expected 2 sessions (start + stop), got %d", len(em.sessions))
+ }
+ if em.sessions[0].Vendor != "codex" {
+ t.Errorf("session vendor: got %q, want codex", em.sessions[0].Vendor)
+ }
+ if em.sessions[1].Outcome == "" {
+ t.Errorf("stop session outcome empty; expected `completed`")
+ }
+ // Tool calls: PostToolUse → 1
+ if len(em.toolCalls) != 1 {
+ t.Fatalf("expected 1 tool call, got %d", len(em.toolCalls))
+ }
+ tc := em.toolCalls[0]
+ if tc.ToolName != "shell" {
+ t.Errorf("tool name: got %q, want shell", tc.ToolName)
+ }
+ if tc.Command != "ls -la" {
+ t.Errorf("tool command (full mode): got %q, want %q", tc.Command, "ls -la")
+ }
+ // LLM turns: Stop → 1
+ if len(em.llmTurns) != 1 {
+ t.Fatalf("expected 1 llm turn, got %d", len(em.llmTurns))
+ }
+ llt := em.llmTurns[0]
+ if llt.Prompt != "refactor sessionstate" {
+ t.Errorf("llm.prompt: got %q", llt.Prompt)
+ }
+ if llt.Response != lastMsg {
+ t.Errorf("llm.response: got %q want %q", llt.Response, lastMsg)
+ }
+ // Tool calls + tool results are NOT folded onto the LLM-turn
+ // span — they live on the dedicated `coding_agent.tool.call`
+ // span (asserted above via em.toolCalls). Re-encoding them in
+ // the turn's messages JSON used to balloon `gen_ai.input.messages`
+ // past the 16 KB cap, which broke the chat view's JSON parser.
+}
+
+// TestCodexMetadataModeDropsBodies verifies the content-capture matrix:
+// in metadata mode we still emit the LLM turn span but bodies are gone.
+func TestCodexMetadataModeDropsBodies(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ in := func(event string, payload any) normalize.Input {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("payload marshal: %v", err)
+ }
+ return normalize.Input{
+ Vendor: "codex",
+ Event: event,
+ Payload: body,
+ ContentCapture: "metadata_only",
+ Emit: em,
+ }
+ }
+
+ sid := "cdx-session-2"
+ turn := "turn-A"
+
+ if err := handle(context.Background(), in("UserPromptSubmit", map[string]any{
+ "session_id": sid,
+ "turn_id": turn,
+ "prompt": "this should not appear",
+ })); err != nil {
+ t.Fatalf("UserPromptSubmit: %v", err)
+ }
+ lastMsg := "and neither should this"
+ if err := handle(context.Background(), in("Stop", map[string]any{
+ "session_id": sid,
+ "turn_id": turn,
+ "last_assistant_message": lastMsg,
+ })); err != nil {
+ t.Fatalf("Stop: %v", err)
+ }
+ if len(em.llmTurns) != 1 {
+ t.Fatalf("expected 1 llm turn, got %d", len(em.llmTurns))
+ }
+ if em.llmTurns[0].Prompt != "" {
+ t.Errorf("metadata mode leaked prompt body: %q", em.llmTurns[0].Prompt)
+ }
+ if em.llmTurns[0].Response != "" {
+ t.Errorf("metadata mode leaked response body: %q", em.llmTurns[0].Response)
+ }
+}
+
+// TestCodexTokenSnapshotFromRollout verifies that the per-turn token
+// delta is computed correctly from a synthetic rollout.jsonl. This is
+// the contract that downstream USD cost rollups depend on.
+func TestCodexTokenSnapshotFromRollout(t *testing.T) {
+ dir := t.TempDir()
+ rollout := filepath.Join(dir, "rollout-2026-05-test.jsonl")
+
+ lines := []map[string]any{
+ {"type": "session_meta", "payload": map[string]any{"id": "cdx-tok-1"}},
+ // turn A starts — baseline = 0 input/0 output (first turn)
+ {"type": "turn_context", "payload": map[string]any{"turn_id": "turn-A"}},
+ // pre-model snapshot
+ {"type": "event_msg", "payload": map[string]any{
+ "type": "token_count",
+ "info": map[string]any{
+ "total_token_usage": map[string]any{"input_tokens": 100, "output_tokens": 0, "total_tokens": 100},
+ "model_context_window": 200000,
+ },
+ }},
+ // model activity → next token_count is final for this turn
+ {"type": "response_item", "payload": map[string]any{"type": "message", "role": "assistant"}},
+ {"type": "event_msg", "payload": map[string]any{
+ "type": "token_count",
+ "info": map[string]any{
+ "total_token_usage": map[string]any{"input_tokens": 1500, "output_tokens": 400, "cached_input_tokens": 800, "reasoning_output_tokens": 150, "total_tokens": 1900},
+ },
+ }},
+ }
+ var buf []byte
+ for _, l := range lines {
+ b, err := json.Marshal(l)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ buf = append(buf, b...)
+ buf = append(buf, '\n')
+ }
+ if err := os.WriteFile(rollout, buf, 0o600); err != nil {
+ t.Fatalf("write rollout: %v", err)
+ }
+ snap, ok := readTokenUsageForTurn(rollout, "turn-A")
+ if !ok {
+ t.Fatalf("expected token snapshot, got none")
+ }
+ // Per-turn delta = final cumulative - pre-model baseline. The
+ // pre-model snapshot was 100 input / 0 output, so the delta we
+ // attribute to this turn's model activity is 1400 / 400 /
+ // 800-cached / 150-reasoning. Crucially the BASELINE (100
+ // cumulative input before the turn started thinking) belongs to
+ // system/dialog overhead, not this turn.
+ if snap.TurnUsage.InputTokens != 1400 {
+ t.Errorf("input_tokens: got %d want 1400", snap.TurnUsage.InputTokens)
+ }
+ if snap.TurnUsage.OutputTokens != 400 {
+ t.Errorf("output_tokens: got %d want 400", snap.TurnUsage.OutputTokens)
+ }
+ if snap.TurnUsage.CachedInputTokens != 800 {
+ t.Errorf("cached_input_tokens: got %d want 800", snap.TurnUsage.CachedInputTokens)
+ }
+ if snap.TurnUsage.ReasoningOutputTokens != 150 {
+ t.Errorf("reasoning_output_tokens: got %d want 150", snap.TurnUsage.ReasoningOutputTokens)
+ }
+ if snap.TotalUsage.InputTokens != 1500 {
+ t.Errorf("total cumulative input: got %d want 1500", snap.TotalUsage.InputTokens)
+ }
+}
+
+// TestCodexSubagentLinkFromSessionMeta verifies that a `session_meta`
+// block with subagent fields is cached into sessionstate so subsequent
+// spans inherit `coding_agent.agent.parent_id`.
+func TestCodexSubagentLinkFromSessionMeta(t *testing.T) {
+ withIsolatedCache(t)
+
+ dir := t.TempDir()
+ rollout := filepath.Join(dir, "rollout-2026-05-sub.jsonl")
+ body := map[string]any{
+ "type": "session_meta",
+ "payload": map[string]any{
+ "id": "cdx-child",
+ "thread_source": "subagent",
+ "parent_session_id": "cdx-parent",
+ "agent_role": "code-reviewer",
+ "agent_nickname": "reviewer-1",
+ "agent_depth": 2,
+ },
+ }
+ raw, _ := json.Marshal(body)
+ if err := os.WriteFile(rollout, append(raw, '\n'), 0o600); err != nil {
+ t.Fatalf("write rollout: %v", err)
+ }
+ em := &recordingEmitter{}
+ body2, _ := json.Marshal(map[string]any{
+ "hook_event_name": "SessionStart",
+ "session_id": "cdx-child",
+ "transcript_path": rollout,
+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
+ "cwd": "/tmp",
+ })
+ if err := handle(context.Background(), normalize.Input{
+ Vendor: "codex",
+ Event: "SessionStart",
+ Payload: body2,
+ ContentCapture: "metadata_only",
+ Emit: em,
+ }); err != nil {
+ t.Fatalf("SessionStart: %v", err)
+ }
+ st := sessionstate.Load("cdx-child", "codex")
+ if st == nil || st.CodexSubagent == nil {
+ t.Fatalf("expected subagent link, got %+v", st)
+ }
+ if st.CodexSubagent.ParentSessionID != "cdx-parent" {
+ t.Errorf("parent_session_id: got %q want cdx-parent", st.CodexSubagent.ParentSessionID)
+ }
+ if st.CodexSubagent.AgentRole != "code-reviewer" {
+ t.Errorf("agent_role: got %q", st.CodexSubagent.AgentRole)
+ }
+
+ // The session-root span emitted on SessionStart must carry the
+ // parent linkage. Without this, the Sessions list shows the
+ // subagent as a standalone row instead of folding it under the
+ // parent's chat.
+ if len(em.sessions) == 0 {
+ t.Fatalf("expected SessionStart to emit a session span")
+ }
+ gotParent := em.sessions[0].Extras["coding_agent.agent.parent_id"]
+ if gotParent != "cdx-parent" {
+ t.Errorf("SessionStart extras parent_id: got %q want cdx-parent", gotParent)
+ }
+
+ // A later Stop event in the same subagent session must re-stamp
+ // the parent_id on the llm.turn span — long subagents accumulate
+ // many turns and the UI's chat_id fold relies on the resource
+ // attr being present on *every* span this session emits, not just
+ // the root.
+ turn := "turn-sub-1"
+ stopBody, _ := json.Marshal(map[string]any{
+ "hook_event_name": "Stop",
+ "session_id": "cdx-child",
+ "turn_id": turn,
+ "transcript_path": rollout,
+ "last_assistant_message": "ok",
+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
+ })
+ if err := handle(context.Background(), normalize.Input{
+ Vendor: "codex",
+ Event: "Stop",
+ Payload: stopBody,
+ ContentCapture: "full",
+ Emit: em,
+ }); err != nil {
+ t.Fatalf("Stop: %v", err)
+ }
+ if len(em.llmTurns) == 0 {
+ t.Fatalf("expected Stop to emit an llm.turn")
+ }
+ turnParent := em.llmTurns[0].Extras["coding_agent.agent.parent_id"]
+ if turnParent != "cdx-parent" {
+ t.Errorf("llm.turn extras parent_id: got %q want cdx-parent", turnParent)
+ }
+}
diff --git a/cli/internal/coding/hook/codex/transcript.go b/cli/internal/coding/hook/codex/transcript.go
new file mode 100644
index 00000000..ef27b257
--- /dev/null
+++ b/cli/internal/coding/hook/codex/transcript.go
@@ -0,0 +1,459 @@
+// Codex rollout/transcript JSONL reader.
+//
+// Codex writes one JSONL record per event under
+// ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl. Every record has a
+// `type` discriminator. The shapes we care about for telemetry are:
+//
+// {"type":"session_meta", "payload":{...}}
+// {"type":"turn_context", "payload":{"turn_id":"..."}}
+// {"type":"response_item", "payload":{"type":"function_call"|"message"|"reasoning",...}}
+// {"type":"event_msg", "payload":{"type":"token_count","info":{...}}}
+//
+// The token-count delta algorithm here: Codex's `token_count` events
+// fire several times per turn and the `info.total_token_usage` field
+// is a running cumulative counter for the entire session. To get
+// *this* turn's usage we subtract the baseline (the value observed
+// just before the assistant started producing model output for this
+// turn) from the final (the value observed at end of turn).
+
+package codex
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+)
+
+// maxTranscriptScan caps how many bytes of one rollout we'll read.
+// Long sessions (hours of dense usage) can exceed our 4 MiB tail-file
+// budget; we accept slight undercount on those rather than blow the
+// 5s hook timeout.
+const maxTranscriptScan = 32 * 1024 * 1024
+
+// maxLineLen is the per-line scanner buffer ceiling. Codex's
+// `response_item` records that wrap large tool outputs can be hundreds
+// of KiB; 1 MiB is a comfortable safety margin.
+const maxLineLen = 1 * 1024 * 1024
+
+// codexLine is the outer JSON envelope every line in a rollout
+// transcript shares.
+type codexLine struct {
+ Type string `json:"type"`
+ Payload json.RawMessage `json:"payload"`
+}
+
+// sessionMeta captures the subset of fields Codex's `session_meta`
+// record exposes about subagent linkage. We collapse the legacy
+// `parent_thread_id` / `Source.Subagent.ThreadSpawn.*` fallbacks
+// into the same struct so both old and new transcript versions are
+// handled.
+type sessionMeta struct {
+ SessionID string
+ ThreadSource string
+ ParentSessionID string
+ AgentRole string
+ AgentNickname string
+ AgentDepth int
+}
+
+// codexTokenUsage mirrors the per-turn token counters Codex emits in
+// every `token_count` event. We use the same field names as the wire
+// format so a JSON unmarshal in `parseTokenUsageInfo` is trivial.
+type codexTokenUsage struct {
+ InputTokens int64 `json:"input_tokens"`
+ CachedInputTokens int64 `json:"cached_input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`
+ TotalTokens int64 `json:"total_tokens"`
+}
+
+// codexTokenUsageInfo is the payload of a `token_count` event_msg. The
+// `last_token_usage` is the most recent single-shot, and
+// `total_token_usage` is the cumulative for the entire session — we
+// subtract the baseline from the final cumulative to attribute usage
+// to a specific turn.
+type codexTokenUsageInfo struct {
+ TotalTokenUsage codexTokenUsage `json:"total_token_usage"`
+ LastTokenUsage codexTokenUsage `json:"last_token_usage"`
+ ModelContextWindow int64 `json:"model_context_window"`
+}
+
+// codexTokenSnapshot is the result of scanning a transcript for a
+// specific turn's token usage. `TurnUsage` is the attributed-to-turn
+// delta we surface as `gen_ai.usage.*`. `TotalUsage` keeps the
+// cumulative numbers so the session-root rollup is also possible.
+type codexTokenSnapshot struct {
+ TurnID string
+ TurnUsage codexTokenUsage
+ BaselineUsage codexTokenUsage
+ LastUsage codexTokenUsage
+ TotalUsage codexTokenUsage
+ ModelContextWindow int64
+}
+
+// readSessionMeta scans the head of a transcript for the first
+// `session_meta` block. Returns ok=false when the file is missing or
+// the block can't be parsed.
+func readSessionMeta(path string) (sessionMeta, bool) {
+ var found sessionMeta
+ ok := false
+ _ = scanCodexLines(path, func(raw []byte) (bool, error) {
+ var l codexLine
+ if err := json.Unmarshal(raw, &l); err != nil || l.Type != "session_meta" {
+ return false, nil
+ }
+ meta, mok := parseSessionMeta(l.Payload)
+ if !mok {
+ return true, nil
+ }
+ found = meta
+ ok = true
+ return true, nil
+ })
+ return found, ok
+}
+
+// readTokenUsageForTurn scans `path` for the cumulative token-usage
+// snapshots that bracket Codex's `turn_id`. Returns ok=false when:
+// - `path` or `turnID` are empty
+// - the transcript can't be opened or never contained the turn
+// - the delta would be non-positive (defensive guard against
+// out-of-order rollout writes)
+//
+// On success the returned snapshot's `TurnUsage` is the per-turn delta
+// suitable for emitting as `gen_ai.usage.input_tokens`,
+// `gen_ai.usage.output_tokens`, `gen_ai.usage.cache.read_input_tokens`,
+// and `coding_agent.llm.reasoning_tokens`.
+func readTokenUsageForTurn(path, turnID string) (codexTokenSnapshot, bool) {
+ if path == "" || turnID == "" {
+ return codexTokenSnapshot{}, false
+ }
+
+ var (
+ activeTurnID string
+ seenAnyTurn bool
+ targetStarted bool
+ targetIsFirstTurn bool
+ targetModelActive bool
+ haveBaseline bool
+ baseline codexTokenUsage
+ haveLastTotal bool
+ lastTotal codexTokenUsage
+ haveFinal bool
+ finalInfo codexTokenUsageInfo
+ )
+
+ err := scanCodexLines(path, func(raw []byte) (bool, error) {
+ var l codexLine
+ if err := json.Unmarshal(raw, &l); err != nil {
+ return false, nil
+ }
+ switch l.Type {
+ case "turn_context":
+ nextTurnID := parseCodexTurnID(l.Payload)
+ if nextTurnID == "" {
+ return false, nil
+ }
+ if !seenAnyTurn {
+ targetIsFirstTurn = nextTurnID == turnID
+ }
+ seenAnyTurn = true
+ activeTurnID = nextTurnID
+ if nextTurnID == turnID && !targetStarted {
+ targetStarted = true
+ targetModelActive = false
+ if haveLastTotal {
+ baseline = lastTotal
+ haveBaseline = true
+ }
+ }
+ case "response_item":
+ if activeTurnID != turnID || !targetStarted {
+ return false, nil
+ }
+ if isModelActivity(l.Payload) {
+ targetModelActive = true
+ }
+ case "event_msg":
+ info, ok := parseTokenUsageInfo(l.Payload)
+ if !ok {
+ return false, nil
+ }
+ if activeTurnID == turnID && targetStarted {
+ if !targetModelActive {
+ // pre-model snapshots roll forward the baseline
+ baseline = info.TotalTokenUsage
+ haveBaseline = true
+ lastTotal = info.TotalTokenUsage
+ haveLastTotal = true
+ return false, nil
+ }
+ finalInfo = info
+ haveFinal = true
+ }
+ lastTotal = info.TotalTokenUsage
+ haveLastTotal = true
+ }
+ return false, nil
+ })
+ if err != nil || !targetStarted || !haveFinal {
+ return codexTokenSnapshot{}, false
+ }
+ if !haveBaseline {
+ if !targetIsFirstTurn {
+ return codexTokenSnapshot{}, false
+ }
+ baseline = codexTokenUsage{}
+ }
+ turnUsage, ok := subtractCodexUsage(finalInfo.TotalTokenUsage, baseline)
+ if !ok || !hasPositiveCodexUsage(turnUsage) {
+ return codexTokenSnapshot{}, false
+ }
+ return codexTokenSnapshot{
+ TurnID: turnID,
+ TurnUsage: turnUsage,
+ BaselineUsage: baseline,
+ LastUsage: finalInfo.LastTokenUsage,
+ TotalUsage: finalInfo.TotalTokenUsage,
+ ModelContextWindow: finalInfo.ModelContextWindow,
+ }, true
+}
+
+// scanCodexLines reads the file line-by-line, invoking visit on each.
+// Stops when visit returns done=true or the byte budget is exceeded.
+// Best-effort: a corrupt line is skipped silently, never fatal.
+func scanCodexLines(path string, visit func(raw []byte) (bool, error)) error {
+ if strings.HasPrefix(path, "~/") {
+ if home, err := os.UserHomeDir(); err == nil {
+ path = filepath.Join(home, strings.TrimPrefix(path, "~/"))
+ }
+ }
+ f, err := os.Open(path) //nolint:gosec // path comes from the codex hook payload
+ if err != nil {
+ return err
+ }
+ defer func() { _ = f.Close() }()
+
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 64*1024), maxLineLen)
+ var read int64
+ for scanner.Scan() {
+ read += int64(len(scanner.Bytes())) + 1
+ if read > maxTranscriptScan {
+ return fmt.Errorf("codex transcript byte budget exceeded")
+ }
+ done, err := visit(scanner.Bytes())
+ if err != nil {
+ return err
+ }
+ if done {
+ return nil
+ }
+ }
+ return scanner.Err()
+}
+
+// parseSessionMeta reads the session_meta envelope on a Codex
+// transcript header. Only the current top-level layout is supported —
+// older Codex builds shipped the fields under
+// source.subagent.thread_spawn.*, which we no longer maintain.
+// Returns ok=true only when at least one identifying field is
+// non-empty.
+func parseSessionMeta(raw json.RawMessage) (sessionMeta, bool) {
+ var p struct {
+ ID string `json:"id"`
+ ThreadSource string `json:"thread_source"`
+ ParentSessionID string `json:"parent_session_id"`
+ AgentRole string `json:"agent_role"`
+ AgentNickname string `json:"agent_nickname"`
+ AgentDepth int `json:"agent_depth"`
+ }
+ if err := json.Unmarshal(raw, &p); err != nil {
+ return sessionMeta{}, false
+ }
+ meta := sessionMeta{
+ SessionID: p.ID,
+ ThreadSource: p.ThreadSource,
+ ParentSessionID: p.ParentSessionID,
+ AgentRole: p.AgentRole,
+ AgentNickname: p.AgentNickname,
+ AgentDepth: p.AgentDepth,
+ }
+ if meta.ThreadSource == "" && meta.ParentSessionID != "" {
+ meta.ThreadSource = "subagent"
+ }
+ if meta.SessionID == "" && meta.ParentSessionID == "" && meta.ThreadSource == "" {
+ return sessionMeta{}, false
+ }
+ return meta, true
+}
+
+func parseCodexTurnID(raw json.RawMessage) string {
+ var p struct {
+ TurnID string `json:"turn_id"`
+ }
+ if err := json.Unmarshal(raw, &p); err != nil {
+ return ""
+ }
+ return p.TurnID
+}
+
+func parseTokenUsageInfo(raw json.RawMessage) (codexTokenUsageInfo, bool) {
+ var p struct {
+ Type string `json:"type"`
+ Info *codexTokenUsageInfo `json:"info"`
+ }
+ if err := json.Unmarshal(raw, &p); err != nil {
+ return codexTokenUsageInfo{}, false
+ }
+ if p.Type != "token_count" || p.Info == nil {
+ return codexTokenUsageInfo{}, false
+ }
+ return *p.Info, true
+}
+
+// isModelActivity reports whether a `response_item` payload represents
+// model-side activity (a reasoning chunk, a function call, an
+// assistant message, a custom-tool call, or a local-shell call). Used
+// to detect the boundary between baseline and final token snapshots —
+// any model activity inside the active turn promotes the next
+// `token_count` event to "final".
+func isModelActivity(raw json.RawMessage) bool {
+ var item struct {
+ Type string `json:"type"`
+ Role string `json:"role"`
+ }
+ if err := json.Unmarshal(raw, &item); err == nil && item.Type != "" {
+ switch item.Type {
+ case "reasoning", "function_call", "custom_tool_call", "local_shell_call":
+ return true
+ case "message":
+ return item.Role == "assistant"
+ }
+ }
+ // Some Codex builds wrap the response item in `{"item": {...}}`.
+ var wrapped struct {
+ Item struct {
+ Type string `json:"type"`
+ Role string `json:"role"`
+ } `json:"item"`
+ }
+ if err := json.Unmarshal(raw, &wrapped); err == nil && wrapped.Item.Type != "" {
+ switch wrapped.Item.Type {
+ case "reasoning", "function_call", "custom_tool_call", "local_shell_call":
+ return true
+ case "message":
+ return wrapped.Item.Role == "assistant"
+ }
+ }
+ return false
+}
+
+func subtractCodexUsage(final, baseline codexTokenUsage) (codexTokenUsage, bool) {
+ out := codexTokenUsage{
+ InputTokens: final.InputTokens - baseline.InputTokens,
+ CachedInputTokens: final.CachedInputTokens - baseline.CachedInputTokens,
+ OutputTokens: final.OutputTokens - baseline.OutputTokens,
+ ReasoningOutputTokens: final.ReasoningOutputTokens - baseline.ReasoningOutputTokens,
+ TotalTokens: final.TotalTokens - baseline.TotalTokens,
+ }
+ if out.InputTokens < 0 || out.CachedInputTokens < 0 ||
+ out.OutputTokens < 0 || out.ReasoningOutputTokens < 0 ||
+ out.TotalTokens < 0 {
+ return codexTokenUsage{}, false
+ }
+ return out, true
+}
+
+func hasPositiveCodexUsage(u codexTokenUsage) bool {
+ return u.InputTokens > 0 ||
+ u.CachedInputTokens > 0 ||
+ u.OutputTokens > 0 ||
+ u.ReasoningOutputTokens > 0 ||
+ u.TotalTokens > 0
+}
+
+// findRolloutForSession walks today's Codex `sessions/<date>` tree
+// looking for a `rollout-*.jsonl` whose first line contains the given
+// `sessionID`. This is the fallback when the hook payload doesn't
+// include `transcript_path`. We only scan today's directory because
+// Stop fires within the same calendar day as the session start
+// (sessions span days only on truly long-running setups — an
+// acceptable corner-case to undercount). Returns "" when no match
+// is found.
+func findRolloutForSession(sessionID string) string {
+ if sessionID == "" {
+ return ""
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return ""
+ }
+ // Try today and yesterday (UTC) — sessions that wrap midnight UTC
+ // rarely cross more than a single day boundary, and scanning two
+ // days is still cheap.
+ now := time.Now().UTC()
+ candidates := []string{
+ filepath.Join(home, ".codex", "sessions", now.Format("2006/01/02")),
+ filepath.Join(home, ".codex", "sessions", now.AddDate(0, 0, -1).Format("2006/01/02")),
+ }
+ for _, dir := range candidates {
+ if path := scanRolloutDirForSession(dir, sessionID); path != "" {
+ return path
+ }
+ }
+ return ""
+}
+
+func scanRolloutDirForSession(dir, sessionID string) string {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return ""
+ }
+ // Most-recent first so a fresh session's transcript wins over an
+ // older one with the same prefix in the filename.
+ sort.Slice(entries, func(i, j int) bool {
+ ii, _ := entries[i].Info()
+ jj, _ := entries[j].Info()
+ if ii == nil || jj == nil {
+ return false
+ }
+ return ii.ModTime().After(jj.ModTime())
+ })
+ for _, e := range entries {
+ if e.IsDir() || !strings.HasPrefix(e.Name(), "rollout-") || !strings.HasSuffix(e.Name(), ".jsonl") {
+ continue
+ }
+ path := filepath.Join(dir, e.Name())
+ if rolloutFirstLineHasSession(path, sessionID) {
+ return path
+ }
+ }
+ return ""
+}
+
+func rolloutFirstLineHasSession(path, sessionID string) bool {
+ f, err := os.Open(path) //nolint:gosec // path under ~/.codex
+ if err != nil {
+ return false
+ }
+ defer func() { _ = f.Close() }()
+ r := bufio.NewReaderSize(f, 64*1024)
+ for i := 0; i < 4; i++ {
+ // `session_meta` is always at or near the top of a rollout;
+ // reading up to 4 lines is enough to find it.
+ line, err := r.ReadString('\n')
+ if err != nil && line == "" {
+ return false
+ }
+ if strings.Contains(line, sessionID) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/cli/internal/coding/hook/cursor/cursor.go b/cli/internal/coding/hook/cursor/cursor.go
new file mode 100644
index 00000000..52fee32e
--- /dev/null
+++ b/cli/internal/coding/hook/cursor/cursor.go
@@ -0,0 +1,25 @@
+// Package cursor implements the Cursor hook adapter.
+//
+// Cursor exposes 8 hook events; payloads are JSON on stdin. Cursor has
+// no transcript file we can tail, so we rely entirely on the hooks +
+// any LLM activity also flowing through OTel from the agent's own
+// instrumentation (where available). Adapter logic lives in handle.go.
+package cursor
+
+import (
+ "context"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+// New returns a new Cursor adapter.
+func New() normalize.Adapter { return &adapter{} }
+
+type adapter struct{}
+
+func (a *adapter) Vendor() string { return semconv.CodingAgentVendorCursor }
+
+func (a *adapter) Handle(ctx context.Context, in normalize.Input) error {
+ return handle(ctx, in)
+}
diff --git a/cli/internal/coding/hook/cursor/handle.go b/cli/internal/coding/hook/cursor/handle.go
new file mode 100644
index 00000000..0686ef05
--- /dev/null
+++ b/cli/internal/coding/hook/cursor/handle.go
@@ -0,0 +1,787 @@
+package cursor
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/classify"
+ "github.com/openlit/openlit/cli/internal/coding/detect"
+ "github.com/openlit/openlit/cli/internal/coding/git"
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/pricing"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+// cursorPayload is a wide JSON struct that covers every field across
+// all 13+ Cursor hook events we subscribe to. Each event populates a
+// different subset; we union them so we don't have to multiplex on the
+// event name at unmarshal time. Unknown fields are ignored, so if
+// Cursor adds keys we silently keep working.
+//
+// Field reference: cursor.com/docs/hooks (2026-05).
+type cursorPayload struct {
+ HookEventName string `json:"hook_event_name"`
+
+ // Common identifiers across most events.
+ ConversationID string `json:"conversation_id"`
+ GenerationID string `json:"generation_id"`
+ SessionID string `json:"session_id"`
+ UserEmail string `json:"user_email"`
+ CursorVersion string `json:"cursor_version"`
+ WorkspaceRoots []string `json:"workspace_roots"`
+ IsBackground bool `json:"is_background_agent"`
+ ComposerMode string `json:"composer_mode"`
+ Model string `json:"model"`
+
+ // beforeSubmitPrompt
+ Prompt string `json:"prompt"`
+ Attachments []cursorAttachment `json:"attachments"`
+
+ // afterAgentResponse / afterAgentThought
+ Text string `json:"text"`
+ DurationMs int64 `json:"duration_ms"`
+
+ // preToolUse / postToolUse / postToolUseFailure
+ ToolName string `json:"tool_name"`
+ ToolUseID string `json:"tool_use_id"`
+ ToolInput json.RawMessage `json:"tool_input"`
+ ToolOutput string `json:"tool_output"`
+ ResultJSON string `json:"result_json"`
+ AgentMessage string `json:"agent_message"`
+ ErrorMessage string `json:"error_message"`
+ FailureType string `json:"failure_type"`
+ IsInterrupt bool `json:"is_interrupt"`
+ Duration int64 `json:"duration"` // postToolUse uses `duration`, not `duration_ms`
+
+ // beforeShellExecution / afterShellExecution
+ Command string `json:"command"`
+ Output string `json:"output"`
+ Sandbox bool `json:"sandbox"`
+ CWD string `json:"cwd"`
+
+ // beforeReadFile
+ FilePath string `json:"file_path"`
+ Content string `json:"content"`
+
+ // afterFileEdit
+ Edits []cursorEdit `json:"edits"`
+
+ // preCompact
+ Trigger string `json:"trigger"`
+ ContextUsagePct int `json:"context_usage_percent"`
+ ContextTokens int64 `json:"context_tokens"`
+ ContextWindowSize int64 `json:"context_window_size"`
+ MessageCount int `json:"message_count"`
+ MessagesToCompact int `json:"messages_to_compact"`
+ IsFirstCompaction bool `json:"is_first_compaction"`
+
+ // stop / sessionEnd
+ Status string `json:"status"`
+ LoopCount int `json:"loop_count"`
+ Reason string `json:"reason"`
+ FinalStatus string `json:"final_status"`
+
+ // subagentStart
+ SubagentID string `json:"subagent_id"`
+ SubagentType string `json:"subagent_type"`
+ Task string `json:"task"`
+ ParentConversationID string `json:"parent_conversation_id"`
+ ToolCallID string `json:"tool_call_id"`
+ SubagentModel string `json:"subagent_model"`
+ IsParallelWorker bool `json:"is_parallel_worker"`
+ GitBranch string `json:"git_branch"`
+
+ // subagentStop
+ Description string `json:"description"`
+ Summary string `json:"summary"`
+ SubMessageCount int `json:"message_count_subagent"` // alias avoidance — see normalize step
+ ToolCallCount int `json:"tool_call_count"`
+ ModifiedFiles []string `json:"modified_files"`
+ TranscriptPath string `json:"agent_transcript_path"`
+}
+
+type cursorAttachment struct {
+ Type string `json:"type"`
+ FilePath string `json:"file_path"`
+}
+
+type cursorEdit struct {
+ OldString string `json:"old_string"`
+ NewString string `json:"new_string"`
+ OldLine string `json:"old_line"`
+ NewLine string `json:"new_line"`
+}
+
+func handle(ctx context.Context, in normalize.Input) error {
+ var p cursorPayload
+ if err := json.Unmarshal(in.Payload, &p); err != nil {
+ fmt.Fprintf(os.Stderr, "openlit: cursor payload parse failed: %v\n", err)
+ return nil
+ }
+ event := in.Event
+ if event == "" {
+ event = p.HookEventName
+ }
+
+ cwd := p.CWD
+ if cwd == "" && len(p.WorkspaceRoots) > 0 {
+ cwd = p.WorkspaceRoots[0]
+ }
+ if cwd == "" {
+ // last resort — use process cwd
+ if wd, err := os.Getwd(); err == nil {
+ cwd = wd
+ }
+ }
+
+ vcs := git.Snapshot(ctx, cwd)
+ // v1: the CLI has no path to the org's API-key allowlist, so we
+ // flag the API-key signal as unknown (APIKeyAllowlistKnown=false)
+ // and let the classifier lean on the repo signal. The earlier
+ // "OPENLIT_API_KEY != \"\"" heuristic was actively wrong — having
+ // the env var set says nothing about whether the key is recognised
+ // by the org and was producing spurious `personal` labels.
+ cls := classify.Classify(classify.Inputs{
+ APIKeyAllowlistKnown: false,
+ APIKeyOnAllowlist: false,
+ RepoURL: vcs.RepoURL,
+ RepoAllowlist: classify.SplitAllowlist(os.Getenv("OPENLIT_CODING_REPO_ALLOWLIST")),
+ })
+
+ // Chat-thread key. Cursor exposes two ids:
+ // - conversation_id: the composer / chat-thread id, stable for
+ // the life of the chat (survives Cursor restarts, plan-mode
+ // toggles, subagent spawns inside the same thread).
+ // - session_id: a per-process / per-invocation id that can be
+ // absent on some events and is not guaranteed stable across
+ // the lifetime of one chat.
+ // We use conversation_id as the primary key so every span fired
+ // by one chat (including subagents the chat spawns) folds into
+ // one chat row. session_id is the fallback when conversation_id
+ // is missing (early-lifecycle events on older Cursor builds).
+ sessionID := p.ConversationID
+ if sessionID == "" {
+ sessionID = p.SessionID
+ }
+
+ // Mode + model transition events are now emitted centrally in
+ // cli/internal/coding/hook/hook.go for ALL three coding agents
+ // (Cursor / Claude Code / Codex), so we don't duplicate that
+ // logic here. The cache update for the latest value still
+ // happens via peekContext + sessionstate.Save in hook.go.
+
+ switch event {
+ case "sessionStart":
+ return in.Emit.EmitSession(buildSession(in, p, sessionID, vcs, cls, "started", time.Time{}))
+
+ case "sessionEnd":
+ // sessionEnd is the authoritative session-closing event. We
+ // stamp the outcome from the `reason` / `final_status` fields
+ // rather than guessing.
+ startedAt := time.Now().Add(-time.Duration(p.DurationMs) * time.Millisecond)
+ s := buildSession(in, p, sessionID, vcs, cls, "ended", time.Now())
+ if !startedAt.IsZero() && p.DurationMs > 0 {
+ s.StartedAt = startedAt
+ s.Duration = time.Duration(p.DurationMs) * time.Millisecond
+ }
+ s.Outcome = outcomeFromReason(p.Reason, p.FinalStatus)
+ return in.Emit.EmitSession(s)
+
+ case "stop":
+ // Cursor's `stop` fires when the agent loop terminates. We
+ // emit a small event so dashboards can count loop turns; the
+ // authoritative session end span comes from sessionEnd.
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.session.loop.stop",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "coding_agent.hook.event": event,
+ "coding_agent.session.loop.status": p.Status,
+ "coding_agent.session.loop.count": p.LoopCount,
+ },
+ })
+
+ case "beforeSubmitPrompt":
+ return in.Emit.EmitLLMTurn(buildPromptTurn(in, p, sessionID))
+
+ case "afterAgentResponse":
+ return in.Emit.EmitLLMTurn(buildResponseTurn(in, p, sessionID))
+
+ case "afterAgentThought":
+ // Reasoning / thinking text is real model output: the provider
+ // charged tokens for it just like for the final assistant
+ // message. Estimate output tokens from the thought text and
+ // run them through the same pricing path as a normal response
+ // turn — without this the session cost rolled-up at the UI
+ // level under-counts thinking-heavy models (Claude
+ // extended-thinking, GPT-5 reasoning) by a wide margin.
+ thoughtTokens := pricing.EstimateTokens(p.Text)
+ thoughtRate := pricing.Lookup(p.Model)
+ thoughtCost := thoughtRate.Cost(0, thoughtTokens, 0, 0)
+ return in.Emit.EmitLLMTurn(normalize.LLMTurn{
+ SessionID: sessionID,
+ ConversationID: p.ConversationID,
+ Vendor: in.Vendor,
+ Model: p.Model,
+ StartedAt: time.Now().Add(-time.Duration(p.DurationMs) * time.Millisecond),
+ EndedAt: time.Now(),
+ ThoughtText: p.Text,
+ ThoughtMs: p.DurationMs,
+ OutputTokens: thoughtTokens,
+ TotalTokens: thoughtTokens,
+ CostUSD: thoughtCost,
+ })
+
+ case "preToolUse":
+ // Pre is intentionally a low-cost event; the full tool span
+ // is emitted at postToolUse or postToolUseFailure time so we
+ // don't double-count.
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.tool.requested",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "gen_ai.tool.name": p.ToolName,
+ "gen_ai.tool.call.id": p.ToolUseID,
+ "code.cwd": p.CWD,
+ "gen_ai.request.model": p.Model,
+ },
+ })
+
+ case "postToolUse":
+ return in.Emit.EmitToolCall(buildToolCallSuccess(in, p, sessionID))
+
+ case "postToolUseFailure":
+ return in.Emit.EmitToolCall(buildToolCallFailure(in, p, sessionID))
+
+ case "subagentStart":
+ return in.Emit.EmitSubagent(normalize.Subagent{
+ SessionID: sessionID,
+ ParentConversationID: p.ParentConversationID,
+ SubagentID: p.SubagentID,
+ SubagentType: p.SubagentType,
+ Task: p.Task,
+ Vendor: in.Vendor,
+ Model: p.SubagentModel,
+ GitBranch: p.GitBranch,
+ IsParallelWorker: p.IsParallelWorker,
+ ToolCallID: p.ToolCallID,
+ Status: "started",
+ StartedAt: time.Now(),
+ })
+
+ case "subagentStop":
+ startedAt := time.Now().Add(-time.Duration(p.DurationMs) * time.Millisecond)
+ // Re-stamp every linkage attribute we know about. The earlier
+ // version dropped SubagentID + ParentConversationID + ToolCallID
+ // on Stop, which broke parent ↔ child ↔ tool-call joins in the
+ // trace view (we'd see the subagent.stop span with no way to
+ // match it against the subagent.start span or the spawning
+ // Task tool call). Status is the only non-Start field that
+ // genuinely differs between the two events.
+ return in.Emit.EmitSubagent(normalize.Subagent{
+ SessionID: sessionID,
+ ParentConversationID: p.ParentConversationID,
+ SubagentID: p.SubagentID,
+ SubagentType: p.SubagentType,
+ Task: p.Task,
+ Description: p.Description,
+ Summary: p.Summary,
+ Vendor: in.Vendor,
+ Model: p.SubagentModel,
+ GitBranch: p.GitBranch,
+ IsParallelWorker: p.IsParallelWorker,
+ ToolCallID: p.ToolCallID,
+ DurationMs: p.DurationMs,
+ MessageCount: p.MessageCount,
+ ToolCallCount: p.ToolCallCount,
+ LoopCount: p.LoopCount,
+ Status: nonEmpty(p.Status, "completed"),
+ ModifiedFiles: p.ModifiedFiles,
+ StartedAt: startedAt,
+ EndedAt: time.Now(),
+ })
+
+ case "beforeShellExecution":
+ // Pre-event for shell — small request event, full span on after.
+ // B4 fix: in metadata mode we leak just the command's first
+ // token (binary name) so dashboards still get "git" vs "rm"
+ // counts, but no flags or paths or remote URLs that may
+ // contain secrets / customer identifiers. Full mode keeps
+ // the entire command for forensic detail.
+ attrs := map[string]any{
+ "coding_agent.client": in.Vendor,
+ "coding_agent.tool.sandboxed": p.Sandbox,
+ "code.cwd": p.CWD,
+ }
+ if cmdAttr := commandForMode(in.ContentCapture, p.Command); cmdAttr != "" {
+ attrs["coding_agent.tool.command"] = cmdAttr
+ }
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.shell.requested",
+ At: time.Now(),
+ Attrs: attrs,
+ })
+
+ case "afterShellExecution":
+ // Detect agent-attributed git commits + PR creations from the
+ // shell tool's command body. We always inspect the verbatim
+ // command (regardless of content-capture mode) because the
+ // detection is structural — the helpers only carry SHAs /
+ // URLs onto the emitted spans, and ExtractCommitMessage /
+ // ExtractPRTitle are gated on `full` capture by the emitter.
+ emitGitArtifacts(in, p, sessionID)
+ return in.Emit.EmitToolCall(normalize.ToolCall{
+ SessionID: sessionID,
+ ToolName: "shell",
+ Vendor: in.Vendor,
+ // Gate Command + Args together so a viewer in metadata
+ // mode sees only the binary name on the tool.call span.
+ Command: commandForMode(in.ContentCapture, p.Command),
+ Sandboxed: p.Sandbox,
+ WorkingDir: p.CWD,
+ StartedAt: time.Now().Add(-time.Duration(p.Duration) * time.Millisecond),
+ EndedAt: time.Now(),
+ Args: captureIfFull(in.ContentCapture, p.Command),
+ Result: captureIfFull(in.ContentCapture, p.Output),
+ })
+
+ case "beforeMCPExecution":
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.mcp.tool.requested",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "gen_ai.tool.name": p.ToolName,
+ "coding_agent.mcp.server.name": serverNameFromMCPInput(p.ToolInput),
+ },
+ })
+
+ case "afterMCPExecution":
+ return in.Emit.EmitToolCall(normalize.ToolCall{
+ SessionID: sessionID,
+ ToolName: p.ToolName,
+ Vendor: in.Vendor,
+ MCPServerName: serverNameFromMCPInput(p.ToolInput),
+ MCPSource: semconv.CodingAgentMCPSourceMarketplace,
+ StartedAt: time.Now().Add(-time.Duration(p.Duration) * time.Millisecond),
+ EndedAt: time.Now(),
+ Args: captureIfFull(in.ContentCapture, string(p.ToolInput)),
+ Result: captureIfFull(in.ContentCapture, p.ResultJSON),
+ })
+
+ case "beforeReadFile":
+ return in.Emit.EmitToolCall(normalize.ToolCall{
+ SessionID: sessionID,
+ ToolName: "read_file",
+ Vendor: in.Vendor,
+ WorkingDir: p.CWD,
+ StartedAt: time.Now(),
+ EndedAt: time.Now(),
+ Args: captureIfFull(in.ContentCapture, p.FilePath),
+ })
+
+ case "afterFileEdit":
+ // Each edit becomes one EditDecision so dashboards can count
+ // per-file edits. Cursor gives us old/new strings, no
+ // permission_mode, so we infer auto_accepted (Cursor edits
+ // are always auto-applied; the user reviews after the fact).
+ //
+ // We also accumulate the per-session LOC + edit counters in
+ // sessionstate so sessionEnd can stamp the totals on the
+ // root span without re-reading every per-edit span.
+ linesAdded, linesRemoved := totalLines(p.Edits)
+ sessionstate.BumpCodeCounters(sessionID, in.Vendor, linesAdded, linesRemoved, linesAdded, 0, 1, 0)
+ return in.Emit.EmitEditDecision(normalize.EditDecision{
+ SessionID: sessionID,
+ Decision: semconv.CodingAgentEditDecisionAutoAccepted,
+ Source: semconv.CodingAgentEditDecisionSourcePolicy,
+ Tool: "afterFileEdit",
+ LinesAdded: linesAdded,
+ LinesRemoved: linesRemoved,
+ FilePath: p.FilePath,
+ Vendor: in.Vendor,
+ At: time.Now(),
+ })
+
+ case "preCompact":
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.session.compact",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.client": in.Vendor,
+ "coding_agent.session.compact.trigger": p.Trigger,
+ "coding_agent.session.compact.usage_pct": p.ContextUsagePct,
+ "coding_agent.session.compact.tokens": p.ContextTokens,
+ "coding_agent.session.compact.window_size": p.ContextWindowSize,
+ "coding_agent.session.compact.message_count": p.MessageCount,
+ "coding_agent.session.compact.messages_to_compact": p.MessagesToCompact,
+ "coding_agent.session.compact.is_first": p.IsFirstCompaction,
+ },
+ })
+
+ default:
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.hook.unknown_event",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.hook.event": event,
+ "coding_agent.client": in.Vendor,
+ },
+ })
+ }
+}
+
+func buildSession(in normalize.Input, p cursorPayload, sessionID string, vcs git.Context, cls classify.Classification, kind string, endedAt time.Time) normalize.Session {
+ startedAt := time.Now()
+ if !endedAt.IsZero() && p.DurationMs > 0 {
+ startedAt = endedAt.Add(-time.Duration(p.DurationMs) * time.Millisecond)
+ }
+ cwd := p.CWD
+ if cwd == "" && len(p.WorkspaceRoots) > 0 {
+ cwd = p.WorkspaceRoots[0]
+ }
+ s := normalize.Session{
+ SessionID: sessionID,
+ ConversationID: p.ConversationID,
+ Vendor: in.Vendor,
+ ClientVersion: p.CursorVersion,
+ Model: p.Model,
+ StartedAt: startedAt,
+ EndedAt: endedAt,
+ PermissionMode: p.ComposerMode,
+ UserID: p.UserEmail,
+ CWD: cwd,
+ RepoURL: vcs.RepoURL,
+ HeadSHA: vcs.HeadSHA,
+ BranchName: vcs.Branch,
+ VCSDirty: vcs.Dirty,
+ UserClassification: cls.Value,
+ ClassificationReason: cls.Reason,
+ Extras: map[string]string{
+ "coding_agent.hook.event": p.HookEventName,
+ "cursor.session.lifecycle": kind,
+ "cursor.session.composer_mode": p.ComposerMode,
+ },
+ }
+ if p.IsBackground {
+ s.Extras["cursor.session.is_background_agent"] = "true"
+ }
+ if p.Reason != "" {
+ s.Extras["cursor.session.end.reason"] = p.Reason
+ }
+ if p.FinalStatus != "" {
+ s.Extras["cursor.session.end.final_status"] = p.FinalStatus
+ }
+ // D6: high-value identifiers Cursor exposes but we previously
+ // dropped. These let support / forensic tooling jump from a
+ // session row back to the on-disk transcript and reproduce what
+ // the user saw inside their IDE.
+ if len(p.WorkspaceRoots) > 0 {
+ // Joined with `;` so the dashboard query can split it back
+ // out. The OTel-standard `code.workspace.roots` is a string
+ // array; we encode as semicolons here because Extras is a
+ // flat map[string]string.
+ s.Extras["code.workspace.roots"] = strings.Join(p.WorkspaceRoots, ";")
+ }
+ if p.TranscriptPath != "" {
+ s.Extras["coding_agent.session.transcript_path"] = p.TranscriptPath
+ }
+ return s
+}
+
+func buildPromptTurn(in normalize.Input, p cursorPayload, sessionID string) normalize.LLMTurn {
+ paths := make([]string, 0, len(p.Attachments))
+ for _, a := range p.Attachments {
+ if a.FilePath != "" {
+ paths = append(paths, a.FilePath)
+ }
+ }
+ now := time.Now()
+ // Cursor doesn't expose token counts on hook payloads, so we
+ // estimate from prompt length and apply the static pricing table.
+ // This is intentionally a lower bound — when the model surfaces
+ // real usage (Codex rollout, Claude transcript), prefer that.
+ inputTokens := pricing.EstimateTokens(p.Prompt)
+ rate := pricing.Lookup(p.Model)
+ cost := rate.Cost(inputTokens, 0, 0, 0)
+ return normalize.LLMTurn{
+ SessionID: sessionID,
+ ConversationID: p.ConversationID,
+ GenerationID: p.GenerationID,
+ Vendor: in.Vendor,
+ Model: p.Model,
+ StartedAt: now,
+ EndedAt: now,
+ Prompt: p.Prompt,
+ AttachmentPaths: paths,
+ UserEmail: p.UserEmail,
+ InputTokens: inputTokens,
+ TotalTokens: inputTokens,
+ CostUSD: cost,
+ }
+}
+
+func buildResponseTurn(in normalize.Input, p cursorPayload, sessionID string) normalize.LLMTurn {
+ now := time.Now()
+ outputTokens := pricing.EstimateTokens(p.Text)
+ rate := pricing.Lookup(p.Model)
+ cost := rate.Cost(0, outputTokens, 0, 0)
+ return normalize.LLMTurn{
+ SessionID: sessionID,
+ ConversationID: p.ConversationID,
+ GenerationID: p.GenerationID,
+ Vendor: in.Vendor,
+ Model: p.Model,
+ StartedAt: now,
+ EndedAt: now,
+ Response: p.Text,
+ AssistantMessageOnly: true,
+ OutputTokens: outputTokens,
+ TotalTokens: outputTokens,
+ CostUSD: cost,
+ }
+}
+
+func buildToolCallSuccess(in normalize.Input, p cursorPayload, sessionID string) normalize.ToolCall {
+ startedAt := time.Now().Add(-time.Duration(p.Duration) * time.Millisecond)
+ return normalize.ToolCall{
+ SessionID: sessionID,
+ ToolName: p.ToolName,
+ ToolUseID: p.ToolUseID,
+ Vendor: in.Vendor,
+ Model: p.Model,
+ WorkingDir: p.CWD,
+ StartedAt: startedAt,
+ EndedAt: time.Now(),
+ Args: captureIfFull(in.ContentCapture, string(p.ToolInput)),
+ Result: captureIfFull(in.ContentCapture, p.ToolOutput),
+ AgentMessage: captureIfFull(in.ContentCapture, p.AgentMessage),
+ TriggeringLLMRequestID: p.GenerationID,
+ MCPServerName: serverNameFromMCPInput(p.ToolInput),
+ MCPScope: mcpScopeFromTool(p.ToolName, p.ToolInput),
+ MCPTransport: mcpTransportFromTool(p.ToolName, p.ToolInput),
+ }
+}
+
+func buildToolCallFailure(in normalize.Input, p cursorPayload, sessionID string) normalize.ToolCall {
+ startedAt := time.Now().Add(-time.Duration(p.Duration) * time.Millisecond)
+ return normalize.ToolCall{
+ SessionID: sessionID,
+ ToolName: p.ToolName,
+ ToolUseID: p.ToolUseID,
+ Vendor: in.Vendor,
+ Errored: true,
+ ErrorMsg: p.ErrorMessage,
+ FailureType: p.FailureType,
+ IsInterrupt: p.IsInterrupt,
+ WorkingDir: p.CWD,
+ StartedAt: startedAt,
+ EndedAt: time.Now(),
+ Args: captureIfFull(in.ContentCapture, string(p.ToolInput)),
+ AgentMessage: captureIfFull(in.ContentCapture, p.AgentMessage),
+ TriggeringLLMRequestID: p.GenerationID,
+ }
+}
+
+// mcpScopeFromTool / mcpTransportFromTool tease the MCP metadata out
+// of a tool-input JSON blob. Cursor packs both fields into tool_input
+// for MCP tools (`scope`: user|workspace, `transport`: stdio|sse). We
+// surface them as separate attributes so dashboards can group by
+// trust boundary without parsing JSON at query time.
+func mcpScopeFromTool(toolName string, raw json.RawMessage) string {
+ if !strings.HasPrefix(toolName, "mcp_") || len(raw) == 0 {
+ return ""
+ }
+ var m struct {
+ Scope string `json:"scope"`
+ }
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return ""
+ }
+ return m.Scope
+}
+
+func mcpTransportFromTool(toolName string, raw json.RawMessage) string {
+ if !strings.HasPrefix(toolName, "mcp_") || len(raw) == 0 {
+ return ""
+ }
+ var m struct {
+ Transport string `json:"transport"`
+ }
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return ""
+ }
+ return m.Transport
+}
+
+// outcomeFromReason maps Cursor's sessionEnd `reason` + `final_status`
+// onto our coding_agent.session.outcome enum. Cursor doesn't have a
+// "merged"/"committed" concept; that's GitHub-App territory in v2.
+//
+// D3 fix: previously "completed" → "abandoned_no_change", which is the
+// opposite of what the word means and made the Outcome column in the
+// dashboard misleading. Now:
+// - completed → completed (literally)
+// - user_close / window_close / aborted → cancelled
+// - error → abandoned_with_change (we know edits happened but the
+// run errored; safer to treat as needing review)
+func outcomeFromReason(reason, final string) string {
+ switch reason {
+ case "completed":
+ return semconv.CodingAgentSessionOutcomeCompleted
+ case "user_close", "window_close":
+ return semconv.CodingAgentSessionOutcomeCancelled
+ case "aborted":
+ return semconv.CodingAgentSessionOutcomeCancelled
+ case "error":
+ return semconv.CodingAgentSessionOutcomeAbandonedWithChange
+ }
+ switch final {
+ case "completed":
+ return semconv.CodingAgentSessionOutcomeCompleted
+ case "aborted":
+ return semconv.CodingAgentSessionOutcomeCancelled
+ }
+ return ""
+}
+
+func serverNameFromMCPInput(raw json.RawMessage) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var m struct {
+ URL string `json:"url"`
+ Command string `json:"command"`
+ Server string `json:"server"`
+ }
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return ""
+ }
+ if m.Server != "" {
+ return m.Server
+ }
+ if m.URL != "" {
+ return m.URL
+ }
+ if m.Command != "" {
+ fields := strings.Fields(m.Command)
+ if len(fields) > 0 {
+ return fields[0]
+ }
+ }
+ return ""
+}
+
+// totalLines counts roughly how many lines were added/removed across an
+// edits[] array. Cursor doesn't provide pre-computed counts, so we run
+// detect.CountInlineDiff over every entry's `old_string` / `new_string`
+// pair. CountInlineDiff handles the empty / one-sided cases correctly
+// (insertions and deletions); the older newline-count heuristic was
+// reporting `0 lines added` whenever the new content fit on a single
+// line, which is the common edit pattern for in-place rewrites.
+func totalLines(edits []cursorEdit) (added, removed int) {
+ for _, e := range edits {
+ a, r := detect.CountInlineDiff(e.OldString, e.NewString)
+ added += a
+ removed += r
+ }
+ return added, removed
+}
+
+// emitGitArtifacts inspects a Cursor `afterShellExecution` payload and
+// emits a GitCommit / GitPullRequest span (and bumps the matching
+// session-state counter) when the command was a `git commit` / PR
+// creation. We DO NOT gate on content-capture mode because the
+// detection helpers only carry safe scalars (SHA, URL, number) — the
+// body-bearing fields (message, title) are gated downstream in the
+// emitter.
+func emitGitArtifacts(in normalize.Input, p cursorPayload, sessionID string) {
+ if p.Command == "" {
+ return
+ }
+ now := time.Now()
+ if detect.IsGitCommit(p.Command) {
+ sha := detect.ExtractCommitSHA(p.Output)
+ _ = in.Emit.EmitGitCommit(normalize.GitCommit{
+ SessionID: sessionID,
+ Vendor: in.Vendor,
+ UserID: p.UserEmail,
+ Tool: "shell",
+ SHA: sha,
+ Message: captureIfFull(in.ContentCapture, detect.ExtractCommitMessage(p.Command)),
+ WorkingDir: p.CWD,
+ At: now,
+ })
+ sessionstate.BumpCommitCount(sessionID, in.Vendor)
+ }
+ if detect.IsPullRequest(p.Command) {
+ url, num := detect.ExtractPRURLAndNumber(p.Output)
+ _ = in.Emit.EmitGitPullRequest(normalize.GitPullRequest{
+ SessionID: sessionID,
+ Vendor: in.Vendor,
+ UserID: p.UserEmail,
+ Tool: "shell",
+ URL: url,
+ Number: num,
+ Title: captureIfFull(in.ContentCapture, detect.ExtractPRTitle(p.Command)),
+ WorkingDir: p.CWD,
+ At: now,
+ })
+ sessionstate.BumpPRCount(sessionID, in.Vendor)
+ }
+}
+
+func captureIfFull(mode, s string) string {
+ if mode != semconv.CodingAgentContentCaptureFull {
+ return ""
+ }
+ return s
+}
+
+// commandForMode trims an executable's full command line to whatever
+// the active capture mode permits. Used for any pre-execution event
+// where we want a metric (binary name, frequency) but must not leak
+// the arguments, which routinely contain customer paths, tokens, and
+// remote URLs. Full mode keeps the entire command (truncated at 4KB);
+// metadata / minimal keep just the first token.
+func commandForMode(mode, raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return ""
+ }
+ if mode == semconv.CodingAgentContentCaptureFull {
+ return truncateStr(raw, 4096)
+ }
+ // metadata + minimal: first token (binary), no flags, no paths.
+ if i := strings.IndexAny(raw, " \t"); i > 0 {
+ return raw[:i]
+ }
+ return raw
+}
+
+func nonEmpty(s, fallback string) string {
+ if s == "" {
+ return fallback
+ }
+ return s
+}
+
+func truncateStr(s string, max int) string {
+ if len(s) <= max {
+ return s
+ }
+ return s[:max] + "..."
+}
diff --git a/cli/internal/coding/hook/cursor/handle_test.go b/cli/internal/coding/hook/cursor/handle_test.go
new file mode 100644
index 00000000..d9daf394
--- /dev/null
+++ b/cli/internal/coding/hook/cursor/handle_test.go
@@ -0,0 +1,212 @@
+package cursor
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "testing"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+)
+
+// recordingEmitter mirrors the same shape used by codex / claudecode
+// adapter tests. Kept local on purpose — see the comment in
+// claudecode/handle_test.go for the rationale.
+type recordingEmitter struct {
+ sessions []normalize.Session
+ toolCalls []normalize.ToolCall
+ editDecisions []normalize.EditDecision
+ llmTurns []normalize.LLMTurn
+ subagents []normalize.Subagent
+ events []normalize.EventEmission
+ gitCommits []normalize.GitCommit
+ gitPRs []normalize.GitPullRequest
+}
+
+func (e *recordingEmitter) EmitSession(s normalize.Session) error {
+ e.sessions = append(e.sessions, s)
+ return nil
+}
+func (e *recordingEmitter) EmitToolCall(t normalize.ToolCall) error {
+ e.toolCalls = append(e.toolCalls, t)
+ return nil
+}
+func (e *recordingEmitter) EmitEditDecision(d normalize.EditDecision) error {
+ e.editDecisions = append(e.editDecisions, d)
+ return nil
+}
+func (e *recordingEmitter) EmitLLMTurn(t normalize.LLMTurn) error {
+ e.llmTurns = append(e.llmTurns, t)
+ return nil
+}
+func (e *recordingEmitter) EmitSubagent(s normalize.Subagent) error {
+ e.subagents = append(e.subagents, s)
+ return nil
+}
+func (e *recordingEmitter) EmitEvent(ev normalize.EventEmission) error {
+ e.events = append(e.events, ev)
+ return nil
+}
+func (e *recordingEmitter) EmitGitCommit(c normalize.GitCommit) error {
+ e.gitCommits = append(e.gitCommits, c)
+ return nil
+}
+func (e *recordingEmitter) EmitGitPullRequest(p normalize.GitPullRequest) error {
+ e.gitPRs = append(e.gitPRs, p)
+ return nil
+}
+
+// withIsolatedCache redirects sessionstate to a temp dir.
+func withIsolatedCache(t *testing.T) {
+ t.Helper()
+ dir := t.TempDir()
+ t.Setenv("XDG_CACHE_HOME", dir)
+ if home := os.Getenv("HOME"); home != "" {
+ t.Setenv("HOME", dir)
+ }
+}
+
+func inputBuilder(t *testing.T, em *recordingEmitter) func(event string, payload any) normalize.Input {
+ t.Helper()
+ return func(event string, payload any) normalize.Input {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("payload marshal: %v", err)
+ }
+ return normalize.Input{
+ Vendor: "cursor",
+ Event: event,
+ Payload: body,
+ ContentCapture: "full",
+ Emit: em,
+ }
+ }
+}
+
+// TestCursorSubagentStopReStampsLinkage covers W2.1 — every linkage
+// attribute (SubagentID, ParentConversationID, ToolCallID, Model,
+// GitBranch, IsParallelWorker) must be present on both
+// subagentStart AND subagentStop. The earlier implementation dropped
+// these on Stop, which broke the trace-view join between subagent
+// start / stop spans and the spawning Task tool call.
+func TestCursorSubagentStopReStampsLinkage(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ in := inputBuilder(t, em)
+
+ stopPayload := map[string]any{
+ "hook_event_name": "subagentStop",
+ "conversation_id": "cur-chat-1",
+ "subagent_id": "sub-42",
+ "parent_conversation_id": "cur-chat-1",
+ "subagent_type": "edit",
+ "task": "refactor",
+ "tool_call_id": "tc-99",
+ "subagent_model": "claude-3.5-sonnet",
+ "git_branch": "feat/sub",
+ "is_parallel_worker": true,
+ "duration_ms": int64(2400),
+ "message_count": 5,
+ "tool_call_count": 3,
+ "modified_files": []string{"a.go", "b.go"},
+ "status": "completed",
+ }
+ if err := handle(context.Background(), in("subagentStop", stopPayload)); err != nil {
+ t.Fatalf("subagentStop: %v", err)
+ }
+ if len(em.subagents) != 1 {
+ t.Fatalf("expected one subagent emission; got %d", len(em.subagents))
+ }
+ got := em.subagents[0]
+
+ checks := []struct {
+ name string
+ want any
+ got any
+ }{
+ {"SubagentID", "sub-42", got.SubagentID},
+ {"ParentConversationID", "cur-chat-1", got.ParentConversationID},
+ {"ToolCallID", "tc-99", got.ToolCallID},
+ {"Model", "claude-3.5-sonnet", got.Model},
+ {"GitBranch", "feat/sub", got.GitBranch},
+ {"IsParallelWorker", true, got.IsParallelWorker},
+ {"DurationMs", int64(2400), got.DurationMs},
+ }
+ for _, c := range checks {
+ if c.got != c.want {
+ t.Errorf("subagentStop %s = %v, want %v", c.name, c.got, c.want)
+ }
+ }
+ if got.Status != "completed" {
+ t.Errorf("subagentStop Status = %q, want %q", got.Status, "completed")
+ }
+ if len(got.ModifiedFiles) != 2 {
+ t.Errorf("subagentStop ModifiedFiles len = %d, want 2", len(got.ModifiedFiles))
+ }
+}
+
+// TestCursorSubagentStartLinkage is the matching positive case for
+// subagentStart. We assert the same fields land on the Start span
+// so the chat view's start ↔ stop pair both carry the linkage.
+func TestCursorSubagentStartLinkage(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ in := inputBuilder(t, em)
+
+ startPayload := map[string]any{
+ "hook_event_name": "subagentStart",
+ "conversation_id": "cur-chat-2",
+ "subagent_id": "sub-7",
+ "parent_conversation_id": "cur-chat-2",
+ "subagent_type": "research",
+ "task": "explore types",
+ "tool_call_id": "tc-7",
+ "subagent_model": "gpt-5",
+ "git_branch": "feat/types",
+ "is_parallel_worker": false,
+ }
+ if err := handle(context.Background(), in("subagentStart", startPayload)); err != nil {
+ t.Fatalf("subagentStart: %v", err)
+ }
+ if len(em.subagents) != 1 {
+ t.Fatalf("expected one subagent emission; got %d", len(em.subagents))
+ }
+ got := em.subagents[0]
+ if got.SubagentID != "sub-7" || got.ToolCallID != "tc-7" || got.ParentConversationID != "cur-chat-2" {
+ t.Errorf("subagentStart linkage = %+v, want sub-7/tc-7/cur-chat-2", got)
+ }
+ if got.Status != "started" {
+ t.Errorf("subagentStart Status = %q, want %q", got.Status, "started")
+ }
+}
+
+// TestCursorSessionIDPrefersConversation covers the chat-thread key
+// resolution: when both conversation_id and session_id are present,
+// the adapter must use conversation_id (stable across Cursor
+// restarts and subagent spawns). session_id is a per-process fallback
+// only.
+func TestCursorSessionIDPrefersConversation(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ in := inputBuilder(t, em)
+
+ if err := handle(context.Background(), in("sessionStart", map[string]any{
+ "hook_event_name": "sessionStart",
+ "conversation_id": "convo-stable",
+ "session_id": "proc-tmp",
+ "cwd": "/tmp",
+ "model": "claude-3.5-sonnet",
+ })); err != nil {
+ t.Fatalf("sessionStart: %v", err)
+ }
+ if len(em.sessions) != 1 {
+ t.Fatalf("expected one session emission; got %d", len(em.sessions))
+ }
+ if em.sessions[0].SessionID != "convo-stable" {
+ t.Errorf("session.SessionID = %q, want %q (conversation_id must win over session_id)",
+ em.sessions[0].SessionID, "convo-stable")
+ }
+}
diff --git a/cli/internal/coding/hook/hook.go b/cli/internal/coding/hook/hook.go
new file mode 100644
index 00000000..1a844643
--- /dev/null
+++ b/cli/internal/coding/hook/hook.go
@@ -0,0 +1,660 @@
+// Package hook implements `openlit coding hook --vendor=... --event=...`.
+//
+// This is the hot path: invoked once per agent event by the per-vendor
+// host plugin manifests under plugins/<vendor>/. The subcommand reads
+// the agent's payload from stdin, normalizes it into coding_agent.* OTel
+// spans/events via the per-vendor adapters under hook/<vendor>/, and
+// exports via internal/otlp.
+//
+// Crash isolation rules (non-negotiable):
+// - exits 0 on telemetry-path failure (a broken pipe never blocks the dev)
+// - 5s hard timeout on the entire invocation; 3s of that for OTLP flush
+// - panic-recover wraps the body
+// - never writes to stdout (Claude Code parses stdout for JSON)
+package hook
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime/debug"
+ "strings"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/git"
+ "github.com/openlit/openlit/cli/internal/coding/hook/claudecode"
+ "github.com/openlit/openlit/cli/internal/coding/hook/codex"
+ "github.com/openlit/openlit/cli/internal/coding/hook/cursor"
+ "github.com/openlit/openlit/cli/internal/coding/identity"
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/cli/internal/config"
+ "github.com/openlit/openlit/cli/internal/otlp"
+ "github.com/spf13/cobra"
+)
+
+const (
+ // hardTimeout caps the entire hook invocation. Each adapter is
+ // expected to finish well under this, but if any part hangs we'd
+ // rather drop the data than wedge the agent.
+ hardTimeout = 5 * time.Second
+ // flushTimeout is reserved at the end for OTLP shutdown/flush.
+ flushTimeout = 3 * time.Second
+)
+
+// NewCmd returns the cobra command for `openlit coding hook`.
+func NewCmd() *cobra.Command {
+ var (
+ vendor string
+ event string
+ )
+
+ cmd := &cobra.Command{
+ Use: "hook",
+ Short: "Process a coding-agent hook event (invoked by host plugin manifests)",
+ Long: `Process a coding-agent hook event.
+
+Reads the host plugin's payload from stdin, normalizes it to
+coding_agent.* OTel spans/events, and exports via OTLP. The subcommand
+always exits 0 on telemetry-path failure so a broken telemetry pipeline
+never blocks a developer's prompt.`,
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ return run(cmd, vendor, event)
+ },
+ }
+
+ cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor: cc | claude-code | cursor | codex")
+ cmd.Flags().StringVar(&event, "event", "", "Hook event name (vendor-specific; e.g. SessionStart, PreToolUse)")
+ _ = cmd.MarkFlagRequired("vendor")
+
+ return cmd
+}
+
+func run(cmd *cobra.Command, vendor, event string) (rerr error) {
+ // Top-level recover — we promise to never crash the host agent.
+ defer func() {
+ if r := recover(); r != nil {
+ logErrorf("hook panic: %v\n%s", r, debug.Stack())
+ rerr = nil
+ }
+ }()
+
+ // Canonicalize the vendor key once. Plugin manifests historically
+ // invoked `--vendor=cc` (short alias) for Claude Code, while
+ // sessionstate / adapters / queries.ts all use `claude-code`. The
+ // split produced two on-disk caches per session (one under `cc`,
+ // one under `claude-code`) that never merged, breaking identity
+ // promotion + parent_id replay across consecutive hook events. We
+ // no longer need the alias for back-compat, so collapse it here
+ // before any downstream code sees the raw flag.
+ vendor = canonicalVendor(vendor)
+
+ ctx, cancel := context.WithTimeout(cmd.Context(), hardTimeout)
+ defer cancel()
+
+ // Read the entire payload up-front. Hooks send small JSON blobs
+ // (a few KB at most), so buffering is fine and lets adapters work
+ // against bytes instead of streaming readers.
+ payload, err := io.ReadAll(io.LimitReader(os.Stdin, 8<<20)) // 8 MB cap
+ if err != nil {
+ logErrorf("hook stdin read: %v", err)
+ return nil
+ }
+
+ // Optional debug tee. When OPENLIT_DEBUG_PAYLOAD_DIR is set we
+ // append the raw inbound payload (with a header line) to
+ // <dir>/<vendor>-<event>.jsonl. Off by default; exists for
+ // "why isn't my prompt landing?" triage where the only way to
+ // know what the vendor sent is to inspect the byte stream they
+ // piped to stdin. Kept here rather than behind a flag because
+ // it has zero cost when the env var is unset.
+ if debugDir := strings.TrimSpace(os.Getenv("OPENLIT_DEBUG_PAYLOAD_DIR")); debugDir != "" {
+ _ = teePayload(debugDir, vendor, event, payload)
+ }
+
+ // Host-mismatch guard.
+ //
+ // Cursor 3.4+ ships a Claude Code compatibility shim that reads
+ // `~/.claude/plugins/<plugin>/hooks/hooks.json` (and Anthropic's
+ // CLAUDE_PLUGIN_ROOT / CLAUDE_PROJECT_DIR env envelope) and
+ // invokes those hook commands for ITS OWN agent turns, in
+ // addition to firing the native `~/.cursor/plugins/*` hooks. So
+ // a user who installed both
+ // `openlit coding install --vendor=cursor` AND
+ // `--vendor=claude-code` would otherwise get every Cursor chat
+ // double-emitted: once with --vendor=cursor (the real Cursor
+ // plugin) and once with --vendor=cc (Cursor masquerading as
+ // Claude Code through the compat shim). The UI then shows the
+ // same chat thread on both vendor detail pages, with the
+ // Claude Code row carrying Cursor-shaped events
+ // (sessionStart instead of SessionStart, etc.).
+ //
+ // `isRealClaudeCodeInvocation` returns true ONLY when
+ // `CLAUDECODE=1` is set — that's the single env signal Claude
+ // Code's own runtime sets on every hook subprocess. Cursor's
+ // compat shim deliberately mimics CLAUDE_PROJECT_DIR /
+ // CLAUDE_PLUGIN_ROOT but does NOT set CLAUDECODE=1 (because the
+ // agent driving the turn is Cursor, not Claude Code). So this
+ // guard suppresses every Cursor-shaped event reaching the
+ // Claude Code adapter while letting real `claude` CLI events
+ // through unchanged. Always exits 0 so the host doesn't notice.
+ if isClaudeCodeVendor(vendor) && !isRealClaudeCodeInvocation() {
+ return nil
+ }
+
+ // Surface allow-listed values from ~/.config/openlit/config.env
+ // into the process environment BEFORE adapters read them. Per-vendor
+ // adapters call os.Getenv directly (e.g. for the repo allowlist),
+ // so without this step a value set in config.env would be invisible
+ // to them. Existing env vars take precedence so a user's shell
+ // override always wins.
+ if err := config.PromoteFileToEnv(); err != nil {
+ logErrorf("hook config-file env promote: %v", err)
+ // non-fatal — the rest of the hook can still proceed without it
+ }
+
+ // Resolve the canonical user identity BEFORE the OTel SDK boots so
+ // every resource attribute on every span the process emits carries
+ // the same value. Without this, the hub's "Users" tab shows two
+ // rows for the same human — one with the OAuth email (when
+ // OPENLIT_USER is exported), one with the OS username (the last-
+ // resort fallback in resolveLocalUser).
+ //
+ // Priority (highest first):
+ // 1. OPENLIT_USER env var (explicit override, usually exported
+ // by the user's shell rc).
+ // 2. Vendor's hook payload (Cursor's `user_email`, etc.).
+ // 3. Per-session cache (vendor only emits identity on lifecycle
+ // events; cache survives between hook invocations).
+ // 4. Per-vendor authoritative file: ~/.claude.json for Claude
+ // Code, ~/.codex/auth.json's JWT for Codex.
+ // 5. `git config user.email` — cross-vendor canonical identity
+ // every developer has set.
+ // 6. Falls through to OS username inside the OTel exporter.
+ //
+ // The resolved identity is also persisted to sessionstate so
+ // follow-up events that lack an email field in their payload
+ // still emit consistently-labeled spans.
+ probe := peekContext(payload)
+ sessionID := probe.SessionID
+ // Cache is partitioned by (sessionID, vendor) — see sessionstate
+ // docs for the cross-vendor poisoning case that motivates this.
+ cached := sessionstate.Load(sessionID, vendor)
+ resolvedUser := strings.TrimSpace(os.Getenv("OPENLIT_USER"))
+ if resolvedUser == "" {
+ resolvedUser = probe.User
+ }
+ if resolvedUser == "" {
+ resolvedUser = cached.User
+ }
+ if resolvedUser == "" {
+ resolvedUser = identity.ResolveForVendor(vendor)
+ }
+ if resolvedUser == "" {
+ resolvedUser = identity.FromGitConfig()
+ }
+ if resolvedUser != "" {
+ _ = os.Setenv("OPENLIT_USER", resolvedUser)
+ cached.User = resolvedUser
+ }
+
+ // Working folder, permission mode, and VCS snapshot — sticky
+ // session-level facts the trace-detail header expects on every
+ // span, even on a tool-call or llm.turn that doesn't itself carry
+ // them. We cache the first sighting and replay it as a resource
+ // attribute so child spans inherit the session's context. The
+ // CLI is short-lived (one process per hook event) so resource
+ // attrs are scoped to a single event, which is what we want.
+ if probe.CWD != "" {
+ cached.CWD = probe.CWD
+ }
+ // Detect permission-mode and model transitions BEFORE we overwrite
+ // the cached values, then emit a small change event so the UI can
+ // chart "developer toggled from agent → plan" or "model swapped"
+ // for any of the three coding agents (Cursor exposes this as
+ // composer_mode, Claude Code as permission_mode, Codex as
+ // approval_mode — all collapsed in peekContext into PermissionMode).
+ // We need to emit BEFORE OTLP boots so we wait — see the
+ // post-emitter detectModeChanges call below.
+ prevMode := cached.PermissionMode
+ prevModel := cached.Model
+ if probe.PermissionMode != "" {
+ cached.PermissionMode = probe.PermissionMode
+ }
+ if probe.Model != "" {
+ cached.Model = probe.Model
+ }
+ if probe.ConversationID != "" {
+ cached.ConversationID = probe.ConversationID
+ }
+ if probe.ParentConversationID != "" {
+ cached.ParentConversationID = probe.ParentConversationID
+ }
+ if probe.IsBackgroundAgent {
+ cached.IsBackgroundAgent = true
+ }
+ // Git snapshot is best-effort: we only run it if we have a CWD
+ // (either from the payload or from the cache) AND the cache
+ // hasn't already populated it. `git remote -v` per hook event
+ // would be wasteful, so the first hook for a session pays the
+ // snapshot cost and subsequent hooks read the cached value.
+ // Cursor only sends `workspace_roots` on session lifecycle and
+ // prompt events; the per-tool / per-edit hooks come in without
+ // any CWD field. We fall back to the process cwd (the editor
+ // launches the hook from the workspace root) and — critically —
+ // persist that fallback so subsequent hook events in the same
+ // session don't keep re-resolving it. Without this persistence,
+ // the trace-detail "Working Folder" + "Repository" pills stay
+ // empty on every non-lifecycle span.
+ if cached.CWD == "" {
+ if wd, err := os.Getwd(); err == nil && wd != "" && wd != "/" {
+ cached.CWD = wd
+ }
+ }
+ if cached.CWD != "" && (cached.RepoURL == "" || cached.Branch == "") {
+ vcs := git.Snapshot(ctx, cached.CWD)
+ if vcs.RepoURL != "" {
+ cached.RepoURL = vcs.RepoURL
+ }
+ if vcs.Branch != "" {
+ cached.Branch = vcs.Branch
+ }
+ }
+ if sessionID != "" && (cached.User != "" || cached.CWD != "" ||
+ cached.PermissionMode != "" || cached.Model != "" ||
+ cached.RepoURL != "" || cached.Branch != "" ||
+ cached.ConversationID != "" || cached.ParentConversationID != "" ||
+ cached.IsBackgroundAgent) {
+ sessionstate.Save(sessionID, vendor, cached)
+ }
+
+ cfg, err := config.Load(nil)
+ if err != nil {
+ logErrorf("hook config load: %v", err)
+ return nil
+ }
+
+ adapter, err := pickAdapter(vendor)
+ if err != nil {
+ logErrorf("hook adapter: %v", err)
+ return nil
+ }
+
+ // Default service.name to the vendor identifier ("cursor",
+ // "claude-code", "codex") so the trace-detail header's
+ // SERVICE pill matches Claude Code's monitoring convention and
+ // the per-vendor materializer can group by service.name. The
+ // user-set OPENLIT_APPLICATION_NAME (file or env) still wins;
+ // only the implicit default is overridden.
+ if src := cfg.Source["application_name"]; src == "default" || src == "" {
+ if v := adapter.Vendor(); v != "" {
+ cfg.ApplicationName = v
+ cfg.Source["application_name"] = "vendor-default"
+ }
+ }
+
+ // Stamp session-level facts on every span this process emits.
+ // This is what makes the trace-detail header pills (Working
+ // Folder, Repository, Branch, Mode) stay populated even when
+ // the developer drills into a child span (llm.turn, tool.call)
+ // that doesn't itself carry these attributes.
+ sessionAttrs := map[string]string{}
+ if cached.CWD != "" {
+ sessionAttrs["code.cwd"] = cached.CWD
+ }
+ if cached.RepoURL != "" {
+ sessionAttrs["vcs.repository.url.full"] = cached.RepoURL
+ }
+ if cached.Branch != "" {
+ sessionAttrs["vcs.ref.head.name"] = cached.Branch
+ }
+ if cached.PermissionMode != "" {
+ sessionAttrs["coding_agent.policy.permission_mode"] = cached.PermissionMode
+ }
+ if sessionID != "" {
+ sessionAttrs["coding_agent.session.id"] = sessionID
+ }
+ // Conversation id — vendor's chat-thread identifier, distinct
+ // from session_id on Cursor (and equal on most others). Stamping
+ // it as a resource attribute lets the UI roll up by chat thread
+ // without depending on the session-root span carrying it.
+ if cached.ConversationID != "" {
+ sessionAttrs["gen_ai.conversation.id"] = cached.ConversationID
+ }
+ // Parent linkage — when this hook process is running inside a
+ // subagent that knows its parent's chat id, stamp it so the UI
+ // can fold the subagent's spans under the parent's chat row
+ // instead of listing the subagent as a separate session.
+ if cached.ParentConversationID != "" {
+ sessionAttrs["coding_agent.agent.parent_id"] = cached.ParentConversationID
+ }
+ // Subagent flag — toggled by Cursor's is_background_agent /
+ // is_parallel_worker on subagent payloads. Used by the Sessions
+ // list to default-hide subagents from the main view.
+ if cached.IsBackgroundAgent {
+ sessionAttrs["coding_agent.session.is_subagent"] = "true"
+ }
+ // Promote the cached terminal/host (set by Claude Code's
+ // transcript `entrypoint` on a previous event in the same
+ // session) to a resource attribute so every span — including the
+ // session-root span emitted on SessionStart — agrees on the host.
+ // Wins over env / process-tree detection in the OTel exporter
+ // because Claude Code's own self-report is the most reliable
+ // signal.
+ if cached.TerminalType != "" {
+ sessionAttrs["terminal.type"] = cached.TerminalType
+ }
+ // Capture mode — clarifies in audit logs which mode the session
+ // was recorded under. Stamped from the CLI config; downstream
+ // consumers (the disputes UI, eDiscovery) can rely on this
+ // without having to infer from the presence/absence of bodies.
+ if mode := strings.TrimSpace(cfg.CodingContentCapture); mode != "" {
+ sessionAttrs["coding_agent.content_capture_mode"] = mode
+ }
+
+ emit, err := otlp.NewEmitter(ctx, cfg, adapter.Vendor(), sessionAttrs)
+ if err != nil {
+ logErrorf("hook otlp init: %v", err)
+ return nil
+ }
+ defer func() {
+ fctx, fcancel := context.WithTimeout(context.Background(), flushTimeout)
+ defer fcancel()
+ if ferr := emit.Shutdown(fctx); ferr != nil {
+ logErrorf("hook otlp shutdown: %v", ferr)
+ }
+ }()
+
+ // Emit cross-vendor change events for permission_mode and model.
+ // We do this AFTER the emitter is initialised but BEFORE the
+ // per-vendor adapter runs, so the change event is the first thing
+ // the trace carries when the same hook event also pulls in a new
+ // turn span. The check skips informational "first sighting" cases
+ // (prev == "") so the timeline doesn't get spammed with a fake
+ // "transition" on every SessionStart.
+ if sessionID != "" {
+ if probe.PermissionMode != "" && prevMode != "" && probe.PermissionMode != prevMode {
+ _ = emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.session.permission_mode.changed",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.client": adapter.Vendor(),
+ "coding_agent.hook.event": event,
+ "coding_agent.session.permission_mode.from": prevMode,
+ "coding_agent.session.permission_mode.to": probe.PermissionMode,
+ },
+ })
+ }
+ if probe.Model != "" && prevModel != "" && probe.Model != prevModel {
+ _ = emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.session.model.changed",
+ At: time.Now(),
+ Attrs: map[string]any{
+ "coding_agent.client": adapter.Vendor(),
+ "coding_agent.hook.event": event,
+ "coding_agent.session.model.from": prevModel,
+ "coding_agent.session.model.to": probe.Model,
+ "gen_ai.request.model": probe.Model,
+ },
+ })
+ }
+ }
+
+ if err := adapter.Handle(ctx, normalize.Input{
+ Vendor: adapter.Vendor(),
+ Event: event,
+ Payload: payload,
+ ContentCapture: cfg.CodingContentCapture,
+ Emit: emit,
+ }); err != nil {
+ logErrorf("hook adapter handle: %v", err)
+ }
+
+ // Always succeed back to the agent.
+ return nil
+}
+
+// canonicalVendor folds the various vendor aliases the plugin manifests
+// have used historically (`cc`, `claudecode`, `claude_code`, …) onto
+// the canonical names used everywhere else: `cursor`, `claude-code`,
+// `codex`. Returns the input unchanged when it's already canonical or
+// unrecognized — pickAdapter then surfaces the unknown-vendor error.
+// Empty input is preserved so the "--vendor required" error fires as
+// before.
+func canonicalVendor(vendor string) string {
+ v := strings.ToLower(strings.TrimSpace(vendor))
+ switch v {
+ case "cc", "claude-code", "claudecode", "claude_code":
+ return "claude-code"
+ case "cursor":
+ return "cursor"
+ case "codex":
+ return "codex"
+ default:
+ return v
+ }
+}
+
+// pickAdapter resolves the (already-canonicalized) vendor key to a
+// hook adapter. Aliases were folded by canonicalVendor at run() entry,
+// so this switch only needs the canonical names.
+func pickAdapter(vendor string) (normalize.Adapter, error) {
+ switch vendor {
+ case "claude-code":
+ return claudecode.New(), nil
+ case "cursor":
+ return cursor.New(), nil
+ case "codex":
+ return codex.New(), nil
+ case "":
+ return nil, errors.New("--vendor is required")
+ default:
+ return nil, fmt.Errorf("unknown --vendor %q", vendor)
+ }
+}
+
+// isClaudeCodeVendor returns true when the vendor key resolves to the
+// Claude Code adapter. Accepts any of the historical aliases the host
+// plugins have used (`cc`, `claudecode`, `claude_code`, …) so callers
+// can pass the raw --vendor flag without pre-canonicalising.
+func isClaudeCodeVendor(vendor string) bool {
+ return canonicalVendor(vendor) == "claude-code"
+}
+
+// isRealClaudeCodeInvocation returns true when the current process was
+// spawned by an actual Claude Code agent runtime (not by a host that
+// happens to honour Claude Code's hook spec, e.g. Cursor 3.4+).
+//
+// Detection rule (intentionally strict):
+//
+// A real Claude Code hook subprocess ALWAYS has `CLAUDECODE=1`
+// in its environment — this is documented at
+// code.claude.com/docs/en/hooks and observed unconditionally in
+// practice. We treat that single variable as the authoritative
+// positive signal.
+//
+// We deliberately do NOT key off `CLAUDE_PROJECT_DIR` or
+// `CLAUDE_SESSION_ID` even though Anthropic's own docs list them —
+// Cursor 3.4+ ships a Claude Code compatibility shim that reads
+// `~/.claude/plugins/<plugin>/hooks/hooks.json` and invokes the bundled
+// hook command for *Cursor's own* agent turns. That shim mirrors
+// Anthropic's `CLAUDE_*` envelope (including `CLAUDE_PROJECT_DIR` and
+// `CLAUDE_PLUGIN_ROOT`) so the plugin "just works" — but `CLAUDECODE=1`
+// is NEVER set, because the agent talking to the LLM is Cursor, not
+// Claude Code. Captured env from a real Cursor 3.4.17 masquerade:
+//
+// CLAUDE_PROJECT_DIR=/Users/.../.claude/plugins/cache/openlit/openlit-cc/0.1.0
+// CLAUDE_PLUGIN_ROOT=/Users/.../.claude/plugins/cache/openlit/openlit-cc/0.1.0
+// CURSOR_VERSION=3.4.17
+// CURSOR_PLUGIN_ROOT=/Users/.../.claude/plugins/cache/openlit/openlit-cc/0.1.0
+// CURSOR_USER_EMAIL=...
+// CURSOR_LAYOUT=unifiedAgent
+// CURSOR_EXTENSION_HOST_ROLE=always-local
+// (CLAUDECODE is unset)
+//
+// Anchoring on `CLAUDECODE=1` makes the masquerade detection
+// configuration-free — we don't have to keep chasing the set of
+// `CURSOR_*` markers Cursor decides to set on hook subprocesses in
+// future releases. It also makes the rule symmetric for hypothetical
+// future hosts that honour the Claude Code plugin spec: only the real
+// thing gets through.
+func isRealClaudeCodeInvocation() bool {
+ return strings.TrimSpace(os.Getenv("CLAUDECODE")) == "1"
+}
+
+// logErrorf writes to stderr only. Stdout is reserved for the agent's
+// own JSON channel (Claude Code in particular parses stdout); writing
+// to it from a hook can corrupt the session.
+func logErrorf(format string, args ...any) {
+ fmt.Fprintf(os.Stderr, "openlit hook: "+format+"\n", args...)
+}
+
+// teePayload appends `payload` (and a small header line) to a
+// per-(vendor,event) jsonl file under dir. Used purely for "what is
+// the vendor actually sending us?" triage when content fields appear
+// to be missing on the resulting spans. Errors are swallowed: this
+// is debug code, never on the hot path. The header doubles as a
+// jsonl pre-line so readers can ignore non-JSON lines easily.
+func teePayload(dir, vendor, event string, payload []byte) error {
+ // 0o700 mirrors the file-mode tightening below; otherwise a
+ // freshly-created debug directory would briefly be world-
+ // listable, leaking the (vendor, event) tuples even if the
+ // payload files are 0o600.
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return err
+ }
+ name := fmt.Sprintf("%s-%s.jsonl", vendor, event)
+ // 0o600: these payloads frequently contain prompt bodies, file
+ // paths under the user's home, and (despite tier-1 redaction)
+ // the occasional unredacted token. Keep them owner-readable
+ // only so a shared developer workstation doesn't leak between
+ // accounts.
+ f, err := os.OpenFile(filepath.Join(dir, name), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ fmt.Fprintf(f, "--- %s vendor=%s event=%s bytes=%d ---\n", time.Now().UTC().Format(time.RFC3339Nano), vendor, event, len(payload))
+ _, _ = f.Write(payload)
+ if len(payload) == 0 || payload[len(payload)-1] != '\n' {
+ _, _ = f.Write([]byte("\n"))
+ }
+ return nil
+}
+
+// peekedContext is the vendor-agnostic slice of facts we extract from a
+// hook payload BEFORE the OTel SDK is initialised, so we can stamp them
+// as resource attributes on every span this process emits. Adapters
+// later populate the typed payload onto per-span attributes; this
+// preflight is purely for resource-level stickiness.
+type peekedContext struct {
+ SessionID string
+ ConversationID string
+ ParentConversationID string
+ User string
+ CWD string
+ PermissionMode string
+ Model string
+ IsBackgroundAgent bool
+}
+
+// peekContext scans a hook payload for session id, user identity,
+// working folder, permission mode, and model using a small set of
+// well-known JSON keys. All fields can be empty — callers handle the
+// fallbacks (sessionstate cache, env vars, OS context).
+func peekContext(payload []byte) peekedContext {
+ out := peekedContext{}
+ if len(payload) == 0 {
+ return out
+ }
+ var probe map[string]any
+ if err := json.Unmarshal(payload, &probe); err != nil {
+ return out
+ }
+ pickString := func(keys ...string) string {
+ for _, k := range keys {
+ v, ok := probe[k]
+ if !ok {
+ continue
+ }
+ if s, ok := v.(string); ok {
+ s = strings.TrimSpace(s)
+ if s != "" {
+ return s
+ }
+ }
+ }
+ return ""
+ }
+ out.SessionID = pickString("session_id", "conversation_id", "sessionId", "thread_id")
+ // Distinct conversation id (when the vendor reports one) — this is
+ // what survives subagent spawns and, on a few vendors, IDE
+ // restarts. UI uses it as the rollup key in preference to
+ // session_id so multi-process chats fold into one row.
+ out.ConversationID = pickString("conversation_id", "conversationId", "thread_id", "threadId")
+ // `parent_conversation_id` is Cursor's link from a subagent back
+ // to its parent chat thread. When present we promote it to a
+ // resource attribute so every span the subagent emits carries
+ // the parent's id, and the UI can roll the subagent up under
+ // the chat that spawned it.
+ out.ParentConversationID = pickString("parent_conversation_id", "parentConversationId", "parent_session_id")
+ // Cursor exposes `user_email` on every event that carries
+ // identity (sessionStart, beforeSubmitPrompt, sessionEnd, ...).
+ // Claude Code transcript hooks include the user-message author
+ // email; Codex rollouts surface a similar field. We accept any
+ // of these so adding new vendors stays mechanical.
+ out.User = pickString("user_email", "user_id", "user", "author_email", "actor_email", "identity")
+ // Cursor calls it `cwd`; Claude Code sets the env CLAUDE_PROJECT_DIR
+ // (handled by resolveTerminalType, not the payload). For the
+ // payload path we accept either.
+ out.CWD = pickString("cwd", "working_directory", "workingDirectory")
+ if out.CWD == "" {
+ // Cursor sometimes only sends `workspace_roots: []`. Pick
+ // the first entry as a best-effort cwd.
+ if v, ok := probe["workspace_roots"]; ok {
+ if arr, ok := v.([]any); ok && len(arr) > 0 {
+ if s, ok := arr[0].(string); ok {
+ out.CWD = strings.TrimSpace(s)
+ }
+ }
+ }
+ }
+ // Permission mode is the same concept under three different
+ // names across vendors:
+ // - Cursor: composer_mode ("agent" | "plan" | "ask")
+ // - Claude Code: permission_mode ("default" | "acceptEdits" | "bypassPermissions" | "plan")
+ // - Codex: approval_mode ("untrusted" | "on-failure" | "on-request" | "never")
+ // We coalesce all of them into the canonical
+ // coding_agent.policy.permission_mode resource attribute so the
+ // UI can chart mode toggles with one query.
+ out.PermissionMode = pickString(
+ "composer_mode",
+ "permission_mode", "permissionMode",
+ "approval_mode", "approvalMode",
+ )
+ out.Model = pickString("model", "request_model", "requestModel")
+ if v, ok := probe["is_background_agent"]; ok {
+ if b, ok := v.(bool); ok {
+ out.IsBackgroundAgent = b
+ }
+ }
+ if !out.IsBackgroundAgent {
+ if v, ok := probe["is_parallel_worker"]; ok {
+ if b, ok := v.(bool); ok && b {
+ // Parallel workers are background agents in
+ // every dashboard we care about; collapse the
+ // flag so the UI doesn't need to know both.
+ out.IsBackgroundAgent = true
+ }
+ }
+ }
+ return out
+}
diff --git a/cli/internal/coding/hook/hook_test.go b/cli/internal/coding/hook/hook_test.go
new file mode 100644
index 00000000..2e4393e8
--- /dev/null
+++ b/cli/internal/coding/hook/hook_test.go
@@ -0,0 +1,171 @@
+package hook
+
+import (
+ "os"
+ "testing"
+)
+
+// TestIsClaudeCodeVendor covers the small whitelist that drives the
+// host-mismatch guard's left-hand side. The list is small but the
+// downstream behaviour (emit vs. drop) is binary, so we want a
+// regression test for the spellings actually shipped on plugin
+// manifests today.
+func TestIsClaudeCodeVendor(t *testing.T) {
+ cases := []struct {
+ vendor string
+ want bool
+ }{
+ {"cc", true},
+ {"CC", true},
+ {" cc ", true},
+ {"claude-code", true},
+ {"Claude-Code", true},
+ {"claudecode", true},
+ {"cursor", false},
+ {"codex", false},
+ {"", false},
+ {"cc-cursor", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.vendor, func(t *testing.T) {
+ if got := isClaudeCodeVendor(tc.vendor); got != tc.want {
+ t.Fatalf("isClaudeCodeVendor(%q) = %v, want %v", tc.vendor, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestIsRealClaudeCodeInvocation pins down the rule that drives the
+// host-mismatch guard's right-hand side: only `CLAUDECODE=1` is
+// authoritative. Cursor 3.4+ honours the Claude Code plugin spec and
+// fires our --vendor=cc hook for Cursor's own agent turns, mirroring
+// Anthropic's `CLAUDE_*` env envelope but NOT setting `CLAUDECODE=1`
+// — the env captured here matches a real production masquerade.
+//
+// Reverting the rule (e.g. accepting `CLAUDE_PROJECT_DIR` as a
+// positive marker) reintroduces duplicate sessions on the Coding
+// Agents UI; this test is the trip-wire.
+func TestIsRealClaudeCodeInvocation(t *testing.T) {
+ // Variables we touch across cases. We snapshot+restore them per
+ // test so the suite remains hermetic when run with -run or in
+ // parallel-discovery mode.
+ managed := []string{
+ "CLAUDECODE",
+ "CLAUDE_PROJECT_DIR",
+ "CLAUDE_PLUGIN_ROOT",
+ "CLAUDE_SESSION_ID",
+ "CURSOR_VERSION",
+ "CURSOR_PLUGIN_ROOT",
+ "CURSOR_USER_EMAIL",
+ "CURSOR_LAYOUT",
+ "CURSOR_EXTENSION_HOST_ROLE",
+ "VSCODE_IPC_HOOK",
+ }
+
+ cases := []struct {
+ name string
+ env map[string]string
+ want bool
+ }{
+ {
+ name: "real_claude_code_minimal",
+ env: map[string]string{
+ "CLAUDECODE": "1",
+ },
+ want: true,
+ },
+ {
+ name: "real_claude_code_full_envelope",
+ env: map[string]string{
+ "CLAUDECODE": "1",
+ "CLAUDE_PROJECT_DIR": "/Users/me/repo",
+ "CLAUDE_PLUGIN_ROOT": "/Users/me/.claude/plugins/cache/openlit/openlit-cc/0.1.0",
+ "CLAUDE_SESSION_ID": "8f3a...",
+ },
+ want: true,
+ },
+ {
+ name: "real_claude_code_inside_cursor_terminal",
+ env: map[string]string{
+ // User opens a Cursor terminal and runs `claude`.
+ // The shell inherits CURSOR_* from the IDE but
+ // claude itself still sets CLAUDECODE=1. The
+ // guard must let this through.
+ "CLAUDECODE": "1",
+ "CURSOR_VERSION": "3.4.17",
+ "VSCODE_IPC_HOOK": "/Users/me/Library/Application Support/Cursor/3.4.-main.sock",
+ },
+ want: true,
+ },
+ {
+ name: "cursor_compat_shim_masquerade",
+ env: map[string]string{
+ // Captured verbatim from Cursor 3.4.17 invoking
+ // our cc hook through its compat shim. Note the
+ // absence of CLAUDECODE=1 — that's the single
+ // signal we anchor on.
+ "CLAUDE_PROJECT_DIR": "/Users/me/repo",
+ "CLAUDE_PLUGIN_ROOT": "/Users/me/.claude/plugins/cache/openlit/openlit-cc/0.1.0",
+ "CURSOR_VERSION": "3.4.17",
+ "CURSOR_PLUGIN_ROOT": "/Users/me/.claude/plugins/cache/openlit/openlit-cc/0.1.0",
+ "CURSOR_USER_EMAIL": "[email protected]",
+ "CURSOR_LAYOUT": "unifiedAgent",
+ "CURSOR_EXTENSION_HOST_ROLE": "always-local",
+ "VSCODE_IPC_HOOK": "/Users/me/Library/Application Support/Cursor/3.4.-main.sock",
+ },
+ want: false,
+ },
+ {
+ name: "claude_project_dir_alone_is_not_enough",
+ env: map[string]string{
+ // Pre-fix the guard treated this as positive,
+ // which is what let the masquerade through.
+ "CLAUDE_PROJECT_DIR": "/Users/me/repo",
+ },
+ want: false,
+ },
+ {
+ name: "empty_env",
+ env: map[string]string{},
+ want: false,
+ },
+ {
+ name: "claudecode_zero_is_not_one",
+ env: map[string]string{"CLAUDECODE": "0"},
+ want: false,
+ },
+ {
+ name: "claudecode_whitespace_only_is_not_one",
+ env: map[string]string{"CLAUDECODE": " "},
+ want: false,
+ },
+ {
+ name: "claudecode_with_padding_is_accepted",
+ // TrimSpace exists so users sourcing env from a file
+ // with stray whitespace don't fail-closed silently.
+ env: map[string]string{"CLAUDECODE": " 1 "},
+ want: true,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ for _, k := range managed {
+ // t.Setenv handles restoration on test exit.
+ // We Setenv first so the cleanup hook is
+ // registered, then Unsetenv to give the guard
+ // strict-absence semantics during the test.
+ t.Setenv(k, "")
+ if err := os.Unsetenv(k); err != nil {
+ t.Fatalf("unset %s: %v", k, err)
+ }
+ }
+ for k, v := range tc.env {
+ t.Setenv(k, v)
+ }
+ if got := isRealClaudeCodeInvocation(); got != tc.want {
+ t.Fatalf("isRealClaudeCodeInvocation() = %v, want %v (env=%v)", got, tc.want, tc.env)
+ }
+ })
+ }
+}
diff --git a/cli/internal/coding/identity/base64.go b/cli/internal/coding/identity/base64.go
new file mode 100644
index 00000000..538cb359
--- /dev/null
+++ b/cli/internal/coding/identity/base64.go
@@ -0,0 +1,12 @@
+package identity
+
+import "encoding/base64"
+
+// base64URLDecode is a thin wrapper around encoding/base64's URL
+// decoder so the caller's intent is obvious at the call site. We use
+// the URL alphabet (with `-` and `_` instead of `+` and `/`) because
+// that's what JWT specifies; the no-padding variant is required
+// because callers append `=` themselves before invoking us.
+func base64URLDecode(seg string) ([]byte, error) {
+ return base64.URLEncoding.DecodeString(seg)
+}
diff --git a/cli/internal/coding/identity/identity.go b/cli/internal/coding/identity/identity.go
new file mode 100644
index 00000000..06f66243
--- /dev/null
+++ b/cli/internal/coding/identity/identity.go
@@ -0,0 +1,156 @@
+// Package identity resolves the canonical user identity to stamp on
+// every emitted span.
+//
+// The hub's "Users" tab rolls up per user, so we need ONE stable
+// identifier per human. Different vendors expose identity differently:
+//
+// - Cursor ships `user_email` in its hook payload.
+// - Claude Code stores it in ~/.claude.json (`oauthAccount.emailAddress`).
+// - Codex authenticates via OAuth and stores the email inside the
+// JWT under tokens.id_token (we don't decode JWTs in v1).
+//
+// Without a per-vendor authoritative source we end up with two rows for
+// the same human: one labeled with the OAuth email (when OPENLIT_USER
+// is set) and one labeled with the OS username (the fallback in
+// resolveLocalUser). This file is the single place that knows how to
+// extract the email-shaped identity from each vendor's local config.
+//
+// Lookup order:
+// 1. OPENLIT_USER (explicit override)
+// 2. Per-vendor authoritative source (see ResolveForVendor)
+// 3. `git config --get user.email` (cross-vendor canonical)
+// 4. Caller falls through to OS username (resolveLocalUser).
+//
+// All functions return "" on any failure — telemetry is best-effort.
+package identity
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// ResolveForVendor returns the canonical user identity for `vendor` by
+// reading the vendor's local OAuth/config file. Returns "" when the
+// file is missing, malformed, or doesn't carry an email. The vendor
+// argument is the canonical vendor id ("claude-code", "codex",
+// "cursor"); unknown vendors return "".
+func ResolveForVendor(vendor string) string {
+ switch vendor {
+ case "claude-code", "cc", "claudecode":
+ return claudeCodeEmail()
+ case "codex":
+ return codexEmail()
+ }
+ return ""
+}
+
+// FromGitConfig returns `git config --get user.email` with a hard
+// timeout. Returns "" on any failure (git not installed, no config
+// value, slow filesystem).
+func FromGitConfig() string {
+ if _, err := exec.LookPath("git"); err != nil {
+ return ""
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "git", "config", "--get", "user.email").Output()
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(out))
+}
+
+// claudeCodeEmail reads ~/.claude.json and returns
+// `oauthAccount.emailAddress` — the same canonical identity Claude
+// Code itself uses for billing and audit.
+func claudeCodeEmail() string {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return ""
+ }
+ data, err := os.ReadFile(filepath.Join(home, ".claude.json"))
+ if err != nil {
+ return ""
+ }
+ var parsed struct {
+ OAuthAccount struct {
+ EmailAddress string `json:"emailAddress"`
+ } `json:"oauthAccount"`
+ }
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ return ""
+ }
+ return strings.TrimSpace(parsed.OAuthAccount.EmailAddress)
+}
+
+// codexEmail extracts the email from Codex's OAuth credentials at
+// ~/.codex/auth.json. The email is embedded as a claim in the JWT
+// id_token; we don't have a JWT verifier in the hook hot path, so we
+// do a minimal claim extraction (payload-only base64url decode, no
+// signature check — read-only use, never used for auth decisions).
+//
+// Returns "" when:
+// - the file is missing (Codex not signed in)
+// - the JSON / JWT layout doesn't match
+// - the `email` claim is empty
+func codexEmail() string {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return ""
+ }
+ data, err := os.ReadFile(filepath.Join(home, ".codex", "auth.json"))
+ if err != nil {
+ return ""
+ }
+ var parsed struct {
+ Tokens struct {
+ IDToken string `json:"id_token"`
+ } `json:"tokens"`
+ }
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ return ""
+ }
+ return emailFromJWT(parsed.Tokens.IDToken)
+}
+
+// emailFromJWT extracts the `email` claim from a JWT payload. It does
+// NOT verify the signature — we trust the file because it lives in the
+// user's $HOME and is owned by their OS account. Returns "" when the
+// token isn't well-formed or doesn't carry an email claim.
+func emailFromJWT(token string) string {
+ parts := strings.Split(token, ".")
+ if len(parts) < 2 {
+ return ""
+ }
+ payload, err := decodeJWTSegment(parts[1])
+ if err != nil {
+ return ""
+ }
+ var claims struct {
+ Email string `json:"email"`
+ }
+ if err := json.Unmarshal(payload, &claims); err != nil {
+ return ""
+ }
+ return strings.TrimSpace(claims.Email)
+}
+
+// decodeJWTSegment decodes a base64url-encoded JWT segment, tolerating
+// missing padding (JWT spec strips the `=` chars).
+func decodeJWTSegment(seg string) ([]byte, error) {
+ // JWT uses base64url WITHOUT padding. We can't import encoding/base64
+ // without expanding the package's dependency surface — but we already
+ // have it via stdlib elsewhere. Use it directly.
+ switch len(seg) % 4 {
+ case 2:
+ seg += "=="
+ case 3:
+ seg += "="
+ }
+ return base64URLDecode(seg)
+}
diff --git a/cli/internal/coding/identity/identity_test.go b/cli/internal/coding/identity/identity_test.go
new file mode 100644
index 00000000..b686f0a3
--- /dev/null
+++ b/cli/internal/coding/identity/identity_test.go
@@ -0,0 +1,75 @@
+package identity
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestResolveForVendor_ClaudeCodeReadsOAuthEmail(t *testing.T) {
+ tmp := t.TempDir()
+ t.Setenv("HOME", tmp)
+ const wantEmail = "[email protected]"
+ body := `{"oauthAccount":{"accountUuid":"abc","emailAddress":"` + wantEmail + `"}}`
+ if err := os.WriteFile(filepath.Join(tmp, ".claude.json"), []byte(body), 0o600); err != nil {
+ t.Fatalf("write .claude.json: %v", err)
+ }
+
+ if got := ResolveForVendor("claude-code"); got != wantEmail {
+ t.Fatalf("claude-code email mismatch: want=%q got=%q", wantEmail, got)
+ }
+ // Aliases must resolve to the same email.
+ if got := ResolveForVendor("cc"); got != wantEmail {
+ t.Fatalf("cc alias mismatch: want=%q got=%q", wantEmail, got)
+ }
+}
+
+func TestResolveForVendor_MissingFileReturnsEmpty(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ if got := ResolveForVendor("claude-code"); got != "" {
+ t.Fatalf("expected empty when ~/.claude.json missing, got %q", got)
+ }
+ if got := ResolveForVendor("codex"); got != "" {
+ t.Fatalf("expected empty when ~/.codex/auth.json missing, got %q", got)
+ }
+}
+
+func TestResolveForVendor_MalformedJSONReturnsEmpty(t *testing.T) {
+ tmp := t.TempDir()
+ t.Setenv("HOME", tmp)
+ if err := os.WriteFile(filepath.Join(tmp, ".claude.json"), []byte("{ not-json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if got := ResolveForVendor("claude-code"); got != "" {
+ t.Fatalf("malformed json must yield empty, got %q", got)
+ }
+}
+
+func TestResolveForVendor_CodexExtractsEmailFromJWT(t *testing.T) {
+ tmp := t.TempDir()
+ t.Setenv("HOME", tmp)
+ if err := os.MkdirAll(filepath.Join(tmp, ".codex"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ // Pre-built JWT with payload {"email":"[email protected]","sub":"x"}. The
+ // header + signature segments are arbitrary; we never verify them.
+ const jwt = "eyJhbGciOiJIUzI1NiJ9." +
+ "eyJlbWFpbCI6Imp3dEBleGFtcGxlLmNvbSIsInN1YiI6IngifQ." +
+ "sig"
+ body := `{"tokens":{"id_token":"` + jwt + `"}}`
+ if err := os.WriteFile(filepath.Join(tmp, ".codex", "auth.json"), []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if got := ResolveForVendor("codex"); got != "[email protected]" {
+ t.Fatalf("codex jwt email mismatch: got %q", got)
+ }
+}
+
+func TestResolveForVendor_UnknownVendorReturnsEmpty(t *testing.T) {
+ if got := ResolveForVendor("rovo"); got != "" {
+ t.Fatalf("unknown vendor must yield empty, got %q", got)
+ }
+ if got := ResolveForVendor(""); got != "" {
+ t.Fatalf("empty vendor must yield empty, got %q", got)
+ }
+}
diff --git a/cli/internal/coding/install/install.go b/cli/internal/coding/install/install.go
new file mode 100644
index 00000000..0d0490e7
--- /dev/null
+++ b/cli/internal/coding/install/install.go
@@ -0,0 +1,114 @@
+// Package install implements `openlit coding install --vendor=...`.
+//
+// Writes per-vendor host plugin manifests to the user's home directory
+// so the agent (Claude Code, Cursor, Codex) finds them on next
+// launch. The manifest payloads themselves live under cli/internal/coding/install/marketplace/
+// (mirrored from the repo-root `.claude-plugin/` + `plugins/` by
+// `cli/scripts/sync-plugins.sh`) and are embedded into the binary at
+// build time, so a single statically-linked CLI carries everything.
+package install
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/spf13/cobra"
+)
+
+// NewCmd returns the cobra command for `openlit coding install`.
+func NewCmd() *cobra.Command {
+ var (
+ vendor string
+ dryRun bool
+ )
+
+ cmd := &cobra.Command{
+ Use: "install",
+ Short: "Install per-vendor coding-agent host plugin manifests",
+ Long: `Install per-vendor host plugin manifests so coding agents pipe
+telemetry through 'openlit coding hook'.
+
+Vendors:
+ claude-code Plugin under ~/.claude/plugins/openlit-cc/ + 'claude plugin install'
+ cursor Hook entries merged into ~/.cursor/hooks.json (user scope)
+ codex Marketplace + 'codex plugin add openlit@openlit'
+ all shorthand for all three
+
+The 'openlit' binary itself must be on PATH. Install via Homebrew, the
+prebuilt binaries on GitHub Releases, the curl|sh installer, or
+'go install github.com/openlit/openlit/cli/cmd/openlit@latest'.`,
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ return run(cmd, vendor, dryRun)
+ },
+ }
+
+ cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor (claude-code | cursor | codex | all)")
+ cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print what would be written without modifying any files")
+ _ = cmd.MarkFlagRequired("vendor")
+
+ return cmd
+}
+
+func run(cmd *cobra.Command, vendor string, dryRun bool) error {
+ vendor = strings.ToLower(strings.TrimSpace(vendor))
+ if vendor == "" {
+ return errors.New("--vendor is required")
+ }
+
+ targets, err := vendorsFromArg(vendor)
+ if err != nil {
+ return err
+ }
+
+ for _, v := range targets {
+ written, err := installVendor(v, dryRun)
+ if err != nil {
+ return fmt.Errorf("install %s: %w", v, err)
+ }
+ if dryRun {
+ fmt.Fprintf(cmd.OutOrStdout(), "[dry-run] would write %d file(s) for %s\n", len(written), v)
+ } else {
+ fmt.Fprintf(cmd.OutOrStdout(), "openlit: installed %s plugin (%d file(s))\n", v, len(written))
+ }
+ for _, p := range written {
+ fmt.Fprintf(cmd.OutOrStdout(), " - %s\n", p)
+ }
+ if !dryRun {
+ // Post-install hint: Codex is the only vendor whose
+ // hooks require explicit user trust on first run. Per
+ // Codex's security model the user has to open `/hooks`
+ // inside the TUI and review each plugin's hook entries
+ // once — otherwise the registered hooks stay listed
+ // but inactive, and nothing reaches OpenLit. Surfacing
+ // this here is the difference between "I installed and
+ // see no data" (bad) and a clean first session.
+ if v == "codex" {
+ fmt.Fprintln(cmd.OutOrStdout(), "")
+ fmt.Fprintln(cmd.OutOrStdout(), "Next steps for Codex:")
+ fmt.Fprintln(cmd.OutOrStdout(), " 1. Restart Codex (or run `codex` in a new shell).")
+ fmt.Fprintln(cmd.OutOrStdout(), " 2. Inside Codex, run `/hooks` and trust each `openlit@openlit` entry.")
+ fmt.Fprintln(cmd.OutOrStdout(), " 3. Start a session — your turns will appear in OpenLit's Coding Agents tab.")
+ }
+ }
+ }
+ return nil
+}
+
+// vendorsFromArg expands the --vendor argument into a slice of vendor IDs.
+func vendorsFromArg(arg string) ([]string, error) {
+ switch arg {
+ case "all":
+ return []string{"claude-code", "cursor", "codex"}, nil
+ case "claude-code", "cc":
+ return []string{"claude-code"}, nil
+ case "cursor":
+ return []string{"cursor"}, nil
+ case "codex":
+ return []string{"codex"}, nil
+ default:
+ return nil, fmt.Errorf("unknown --vendor %q", arg)
+ }
+}
diff --git a/cli/internal/coding/install/install_cursor.go b/cli/internal/coding/install/install_cursor.go
new file mode 100644
index 00000000..9388727e
--- /dev/null
+++ b/cli/internal/coding/install/install_cursor.go
@@ -0,0 +1,262 @@
+// Cursor-specific install path: merge OpenLit's hook entries into the
+// user-scope ~/.cursor/hooks.json file instead of dropping a separate
+// plugin tree under ~/.cursor/plugins/openlit/.
+//
+// Why user-scope hooks.json and not the plugin dir?
+//
+// Cursor evaluates hooks from four scopes (Enterprise, User, Project,
+// Project Claude). The plugin loader IS supposed to surface plugin
+// manifests under ~/.cursor/plugins/<name>/hooks/hooks.json, but in
+// practice that path requires the user to register the plugin via the
+// in-app `/add-plugin` flow — silently dropping files there does NOT
+// make Cursor pick them up. We confirmed this on real machines (Cursor's
+// own debug log lists the four scope paths but never the plugins dir).
+//
+// User-scope is the documented, supported way to install agent-wide
+// hooks that apply to every workspace the user opens, and it works
+// without any in-app step. That's exactly what we want from
+// `openlit coding install --vendor=cursor`.
+//
+// Multiple-owner safety:
+//
+// ~/.cursor/hooks.json is a shared resource — a user may already have
+// hooks installed by another tool (or hand-written ones). We MUST NOT
+// blow those away. Install merges per-event:
+//
+// 1. Read existing hooks.json (or start fresh if missing).
+// 2. For each event in our embedded hooks.json, drop any prior entry
+// whose `command` we own (substring `openlit coding hook
+// --vendor=cursor`) — keeps re-install idempotent.
+// 3. Append our patched entry to the event array.
+// 4. Preserve all unrelated events and top-level keys.
+//
+// On uninstall we do the inverse strip; see uninstall_cursor.go.
+
+package install
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// cursorOwnedCommandMarker identifies hook entries this CLI authored.
+// We match on a substring of the `command` string so the marker
+// survives whatever absolute path patchManifestBytes inlined.
+const cursorOwnedCommandMarker = "openlit coding hook --vendor=cursor"
+
+// installCursorHooks merges our hook entries into ~/.cursor/hooks.json.
+// Returns the absolute path of the file it touched (or would touch in
+// dry-run) so the install command can print it to the user.
+func installCursorHooks(dryRun bool) ([]string, error) {
+ openlitBin, err := resolveOpenlitBin()
+ if err != nil {
+ return nil, fmt.Errorf("locate openlit binary: %w (install openlit and ensure it is on PATH)", err)
+ }
+
+ hooksPath, err := userCursorHooksPath()
+ if err != nil {
+ return nil, err
+ }
+
+ // Load our hook template from the embedded plugin tree. We
+ // rewrite the bare `openlit ...` commands to use the absolute
+ // path of the running binary so GUI launches of Cursor (which
+ // don't inherit the shell's PATH) still find it.
+ tmplBytes, err := marketplaceFS.ReadFile("marketplace/plugins/cursor/hooks/hooks.json")
+ if err != nil {
+ return nil, fmt.Errorf("read embedded cursor hooks template: %w", err)
+ }
+ tmplBytes = patchManifestBytes("hooks/hooks.json", tmplBytes, openlitBin)
+ var template cursorHooksFile
+ if err := json.Unmarshal(tmplBytes, &template); err != nil {
+ return nil, fmt.Errorf("parse embedded cursor hooks template: %w", err)
+ }
+
+ existing, err := readCursorHooksFile(hooksPath)
+ if err != nil {
+ return nil, fmt.Errorf("read existing %s: %w", hooksPath, err)
+ }
+
+ merged := mergeCursorHooks(existing, template)
+
+ if dryRun {
+ return []string{hooksPath}, nil
+ }
+
+ if err := writeCursorHooksFile(hooksPath, merged); err != nil {
+ return nil, err
+ }
+ return []string{hooksPath}, nil
+}
+
+// cursorHooksFile mirrors the shape of ~/.cursor/hooks.json. We use
+// json.RawMessage for hook-entry values so we round-trip any extra
+// fields (e.g. `timeout`, future fields Cursor may add) without
+// silently dropping them.
+type cursorHooksFile struct {
+ Version int `json:"version,omitempty"`
+ Hooks map[string][]json.RawMessage `json:"hooks,omitempty"`
+ // Extra captures any unrecognized top-level keys so we don't
+ // drop them when we re-marshal the file. encoding/json gives us
+ // this only via a custom unmarshal — see below.
+ Extra map[string]json.RawMessage `json:"-"`
+}
+
+func (f *cursorHooksFile) UnmarshalJSON(data []byte) error {
+ raw := map[string]json.RawMessage{}
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return err
+ }
+ if v, ok := raw["version"]; ok {
+ _ = json.Unmarshal(v, &f.Version)
+ delete(raw, "version")
+ }
+ if h, ok := raw["hooks"]; ok {
+ if err := json.Unmarshal(h, &f.Hooks); err != nil {
+ return fmt.Errorf("hooks: %w", err)
+ }
+ delete(raw, "hooks")
+ }
+ if len(raw) > 0 {
+ f.Extra = raw
+ }
+ return nil
+}
+
+func (f cursorHooksFile) MarshalJSON() ([]byte, error) {
+ out := map[string]json.RawMessage{}
+ for k, v := range f.Extra {
+ out[k] = v
+ }
+ if f.Version != 0 {
+ v, err := json.Marshal(f.Version)
+ if err != nil {
+ return nil, err
+ }
+ out["version"] = v
+ }
+ if f.Hooks != nil {
+ h, err := json.Marshal(f.Hooks)
+ if err != nil {
+ return nil, err
+ }
+ out["hooks"] = h
+ }
+ return json.Marshal(out)
+}
+
+// mergeCursorHooks returns a new cursorHooksFile with our template's
+// entries merged into existing. The rules are documented at the top of
+// this file. The receiver is not mutated.
+func mergeCursorHooks(existing, template cursorHooksFile) cursorHooksFile {
+ merged := cursorHooksFile{
+ Version: existing.Version,
+ Hooks: map[string][]json.RawMessage{},
+ Extra: existing.Extra,
+ }
+ // Bump version to the template's if existing had none — keeps
+ // fresh installs writing version:1 rather than version:0.
+ if merged.Version == 0 {
+ merged.Version = template.Version
+ }
+ for event, entries := range existing.Hooks {
+ filtered := make([]json.RawMessage, 0, len(entries))
+ for _, e := range entries {
+ if !isOpenLitEntry(e) {
+ filtered = append(filtered, e)
+ }
+ }
+ if len(filtered) > 0 {
+ merged.Hooks[event] = filtered
+ }
+ }
+ for event, entries := range template.Hooks {
+ merged.Hooks[event] = append(merged.Hooks[event], entries...)
+ }
+ return merged
+}
+
+// isOpenLitEntry reports whether a hook entry was authored by us. It
+// runs on the raw bytes to avoid a strict struct that might choke on
+// extra fields. We don't substring-match the full RawMessage because
+// the marker could appear inside an unrelated string field; instead we
+// shallow-decode to read `command` specifically.
+func isOpenLitEntry(raw json.RawMessage) bool {
+ var entry struct {
+ Command string `json:"command"`
+ }
+ if err := json.Unmarshal(raw, &entry); err != nil {
+ return false
+ }
+ return entry.Command != "" && strings.Contains(entry.Command, cursorOwnedCommandMarker)
+}
+
+// readCursorHooksFile returns the file's parsed contents, or an empty
+// shell if the file does not exist. A malformed existing file is an
+// error — we refuse to silently overwrite a user-broken JSON file.
+func readCursorHooksFile(path string) (cursorHooksFile, error) {
+ body, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return cursorHooksFile{}, nil
+ }
+ return cursorHooksFile{}, err
+ }
+ if len(body) == 0 {
+ return cursorHooksFile{}, nil
+ }
+ var f cursorHooksFile
+ if err := json.Unmarshal(body, &f); err != nil {
+ return cursorHooksFile{}, fmt.Errorf("parse %s: %w (refusing to overwrite a malformed hooks file)", path, err)
+ }
+ return f, nil
+}
+
+// writeCursorHooksFile serializes f and atomically replaces the
+// destination. We write to a tempfile alongside the target so a
+// half-written file never becomes the active hooks config.
+func writeCursorHooksFile(path string, f cursorHooksFile) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ body, err := json.MarshalIndent(f, "", " ")
+ if err != nil {
+ return fmt.Errorf("encode cursor hooks: %w", err)
+ }
+ body = append(body, '\n')
+
+ tmp, err := os.CreateTemp(filepath.Dir(path), ".hooks.json.*")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ if _, err := tmp.Write(body); err != nil {
+ _ = tmp.Close()
+ _ = os.Remove(tmpName)
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ _ = os.Remove(tmpName)
+ return err
+ }
+ if err := os.Chmod(tmpName, 0o644); err != nil {
+ _ = os.Remove(tmpName)
+ return err
+ }
+ return os.Rename(tmpName, path)
+}
+
+// userCursorHooksPath returns the absolute path to ~/.cursor/hooks.json.
+// Per Cursor's docs the file lives under the user's home dir on every
+// supported platform (macOS, Linux, Windows), keyed off the standard
+// home-dir resolver.
+func userCursorHooksPath() (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("could not resolve home directory: %w", err)
+ }
+ return filepath.Join(home, ".cursor", "hooks.json"), nil
+}
diff --git a/cli/internal/coding/install/install_cursor_test.go b/cli/internal/coding/install/install_cursor_test.go
new file mode 100644
index 00000000..117f70d4
--- /dev/null
+++ b/cli/internal/coding/install/install_cursor_test.go
@@ -0,0 +1,170 @@
+package install
+
+import (
+ "encoding/json"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+)
+
+// TestMergeCursorHooks_FreshInstall: starting from an empty user file
+// (no hooks.json on disk yet), our template should land verbatim.
+func TestMergeCursorHooks_FreshInstall(t *testing.T) {
+ template := mustParseHooks(t, `{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [{"command": "openlit coding hook --vendor=cursor --event=sessionStart", "timeout": 5000}]
+ }
+ }`)
+
+ merged := mergeCursorHooks(cursorHooksFile{}, template)
+
+ if merged.Version != 1 {
+ t.Fatalf("expected version 1, got %d", merged.Version)
+ }
+ if got := len(merged.Hooks["sessionStart"]); got != 1 {
+ t.Fatalf("expected 1 sessionStart entry, got %d", got)
+ }
+}
+
+// TestMergeCursorHooks_PreservesUnrelatedEntries: another tool already
+// wrote a sessionStart hook; our install must merge alongside it.
+func TestMergeCursorHooks_PreservesUnrelatedEntries(t *testing.T) {
+ existing := mustParseHooks(t, `{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [{"command": "other-tool", "timeout": 1000}],
+ "customEvent": [{"command": "user-script", "timeout": 1}]
+ }
+ }`)
+ template := mustParseHooks(t, `{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [{"command": "openlit coding hook --vendor=cursor --event=sessionStart"}]
+ }
+ }`)
+
+ merged := mergeCursorHooks(existing, template)
+
+ if got := len(merged.Hooks["sessionStart"]); got != 2 {
+ t.Fatalf("expected 2 sessionStart entries (other + ours), got %d", got)
+ }
+ if got := len(merged.Hooks["customEvent"]); got != 1 {
+ t.Fatalf("expected customEvent preserved, got %d", got)
+ }
+ // "other-tool" entry must come first (we append).
+ cmds := commandsFor(t, merged.Hooks["sessionStart"])
+ if cmds[0] != "other-tool" {
+ t.Fatalf("existing entry should come first; got order %v", cmds)
+ }
+ if !strings.Contains(cmds[1], "openlit coding hook") {
+ t.Fatalf("our entry should come second; got %q", cmds[1])
+ }
+}
+
+// TestMergeCursorHooks_Idempotent: running install twice should NOT
+// double-register our hooks. The marker-based strip in mergeCursorHooks
+// drops the prior openlit entry before re-appending.
+func TestMergeCursorHooks_Idempotent(t *testing.T) {
+ template := mustParseHooks(t, `{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [{"command": "openlit coding hook --vendor=cursor --event=sessionStart"}]
+ }
+ }`)
+
+ first := mergeCursorHooks(cursorHooksFile{}, template)
+ second := mergeCursorHooks(first, template)
+
+ if got := len(second.Hooks["sessionStart"]); got != 1 {
+ t.Fatalf("re-install must stay at 1 entry, got %d", got)
+ }
+}
+
+// TestMergeCursorHooks_PreservesExtraTopLevelKeys: a user with custom
+// top-level fields in their hooks.json must keep them after merge.
+func TestMergeCursorHooks_PreservesExtraTopLevelKeys(t *testing.T) {
+ existing := mustParseHooks(t, `{
+ "version": 1,
+ "hooks": {},
+ "customConfig": {"foo": "bar"}
+ }`)
+ template := mustParseHooks(t, `{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [{"command": "openlit coding hook --vendor=cursor --event=sessionStart"}]
+ }
+ }`)
+
+ merged := mergeCursorHooks(existing, template)
+
+ out, err := json.Marshal(merged)
+ if err != nil {
+ t.Fatalf("marshal merged: %v", err)
+ }
+ var roundTrip map[string]json.RawMessage
+ if err := json.Unmarshal(out, &roundTrip); err != nil {
+ t.Fatalf("unmarshal merged: %v", err)
+ }
+ if _, ok := roundTrip["customConfig"]; !ok {
+ t.Fatalf("customConfig was dropped; got keys %v", keys(roundTrip))
+ }
+}
+
+func TestIsOpenLitEntry(t *testing.T) {
+ cases := []struct {
+ body string
+ want bool
+ }{
+ {`{"command": "openlit coding hook --vendor=cursor --event=sessionStart"}`, true},
+ {`{"command": "/Users/me/.openlit/bin/openlit coding hook --vendor=cursor --event=sessionEnd", "timeout": 5000}`, true},
+ {`{"command": "/usr/local/bin/openlit coding hook --vendor=claude-code --event=sessionStart"}`, false},
+ {`{"command": "other-tool"}`, false},
+ {`{}`, false},
+ {`"raw string entry"`, false},
+ }
+ for _, tc := range cases {
+ got := isOpenLitEntry(json.RawMessage(tc.body))
+ if got != tc.want {
+ t.Errorf("isOpenLitEntry(%s) = %v, want %v", tc.body, got, tc.want)
+ }
+ }
+}
+
+func mustParseHooks(t *testing.T, body string) cursorHooksFile {
+ t.Helper()
+ var f cursorHooksFile
+ if err := json.Unmarshal([]byte(body), &f); err != nil {
+ t.Fatalf("parse fixture: %v\n%s", err, body)
+ }
+ return f
+}
+
+func commandsFor(t *testing.T, entries []json.RawMessage) []string {
+ t.Helper()
+ out := make([]string, 0, len(entries))
+ for _, e := range entries {
+ var v struct {
+ Command string `json:"command"`
+ }
+ if err := json.Unmarshal(e, &v); err != nil {
+ t.Fatalf("decode entry: %v", err)
+ }
+ out = append(out, v.Command)
+ }
+ return out
+}
+
+func keys(m map[string]json.RawMessage) []string {
+ out := make([]string, 0, len(m))
+ for k := range m {
+ out = append(out, k)
+ }
+ sort.Strings(out)
+ return out
+}
+
+// Compile-time guard that the round-trip path produces structurally
+// equivalent data when there is nothing to merge.
+var _ = reflect.DeepEqual
diff --git a/cli/internal/coding/install/install_patch.go b/cli/internal/coding/install/install_patch.go
new file mode 100644
index 00000000..e0141dbf
--- /dev/null
+++ b/cli/internal/coding/install/install_patch.go
@@ -0,0 +1,226 @@
+package install
+
+import (
+ "fmt"
+ "io/fs"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+// patchManifestBytes rewrites hook manifests so they do not depend on the
+// caller's PATH. GUI apps (VS Code, Cursor) often launch hook subprocesses
+// with a minimal PATH that omits ~/.local/bin. Replacing the bare
+// `openlit` command with the absolute path of the binary that ran
+// `openlit coding install` removes that whole class of "hooks fire but
+// don't find the CLI" failures.
+func patchManifestBytes(_ string, body []byte, openlitBin string) []byte {
+ s := string(body)
+ if strings.Contains(s, "__OPENLIT_BIN__") {
+ s = strings.ReplaceAll(s, "__OPENLIT_BIN__", openlitBin)
+ }
+ if strings.Contains(s, "openlit coding hook") {
+ quoted := shellQuote(openlitBin)
+ s = strings.ReplaceAll(s, "openlit coding hook", quoted+" coding hook")
+ }
+ return []byte(s)
+}
+
+func resolveOpenlitBin() (string, error) {
+ if exe, err := os.Executable(); err == nil {
+ if filepath.Base(exe) == "openlit" {
+ return exe, nil
+ }
+ }
+ return exec.LookPath("openlit")
+}
+
+func shellQuote(s string) string {
+ if s == "" {
+ return "''"
+ }
+ if !strings.ContainsAny(s, " \t\n'\"\\$`") {
+ return s
+ }
+ return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"
+}
+
+// enableClaudeCodePlugin registers the bundled marketplace and installs
+// openlit-cc for the user. Best-effort when `claude` is missing.
+//
+// Skipping silently is only correct for "claude isn't installed on this
+// machine" — everything else (missing embedded template, can't resolve
+// our own binary) is a real failure that the caller surfaces via stderr.
+// Swallowing those would leave the on-disk plugin orphaned because Claude
+// Code only loads plugins it knows about via a marketplace, which is
+// the entire point of materializing one here.
+func enableClaudeCodePlugin() error {
+ claudeBin, err := exec.LookPath("claude")
+ if err != nil {
+ return nil
+ }
+
+ openlitBin, err := resolveOpenlitBin()
+ if err != nil {
+ return fmt.Errorf("resolve openlit binary: %w", err)
+ }
+ marketplaceRoot, err := materializeClaudeMarketplace(openlitBin)
+ if err != nil {
+ return fmt.Errorf("materialize claude marketplace: %w", err)
+ }
+
+ add := exec.Command(claudeBin, "plugin", "marketplace", "add", marketplaceRoot) //nolint:gosec
+ if out, err := add.CombinedOutput(); err != nil {
+ msg := strings.TrimSpace(string(out))
+ if msg != "" && !strings.Contains(strings.ToLower(msg), "already") {
+ fmt.Fprintf(os.Stderr, "openlit install: claude marketplace add: %s\n", msg)
+ }
+ }
+
+ inst := exec.Command(claudeBin, "plugin", "install", "openlit-cc@openlit", "--scope", "user") //nolint:gosec
+ if out, err := inst.CombinedOutput(); err != nil {
+ msg := strings.TrimSpace(string(out))
+ if strings.Contains(strings.ToLower(msg), "already") {
+ return nil
+ }
+ return fmt.Errorf("%s", msg)
+ }
+ return nil
+}
+
+// materializeClaudeMarketplace writes the embedded Claude Code
+// marketplace tree to ~/.local/share/openlit/claude-marketplace so
+// `claude plugin marketplace add` has a stable directory path. The
+// destination layout matches the repo-root layout exactly:
+//
+// ~/.local/share/openlit/claude-marketplace/
+// .claude-plugin/marketplace.json
+// plugins/claude-code/
+// plugins/cursor/ (carried for completeness; only claude-code is
+// plugins/codex/ registered via `claude plugin install` below)
+//
+// Keeping the layout identical to repo-root means the marketplace.json's
+// `source: "./plugins/claude-code"` resolves correctly for both flows
+// (Claude fetching the marketplace from GitHub or from this local dir).
+func materializeClaudeMarketplace(openlitBin string) (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ root := filepath.Join(home, ".local", "share", "openlit", "claude-marketplace")
+ // Wipe a stale tree so removals in the embed (e.g. a vendor dir
+ // being dropped) propagate. The marketplace dir is owned wholly
+ // by us; no user data lives here.
+ if err := os.RemoveAll(root); err != nil {
+ return "", fmt.Errorf("clean %s: %w", root, err)
+ }
+ if err := extractEmbeddedDir("marketplace", root, openlitBin); err != nil {
+ return "", err
+ }
+ return root, nil
+}
+
+// enableCodexPlugin registers the freshly written OpenLit marketplace
+// with Codex and installs the `openlit@openlit` plugin so the hooks
+// configured in plugin.json actually fire. Best-effort: if the `codex`
+// CLI is missing we fall through with a helpful stderr note and
+// expect the user to register the marketplace manually.
+//
+// Codex requires this two-step dance because its plugin loader does NOT
+// auto-discover plugin directories — it only scans configured
+// marketplaces (`codex plugin marketplace list`) and installed plugins
+// (`codex plugin list`). The path `~/.codex/plugins/<name>/` is a
+// red herring: nothing in Codex reads it, even if `plugin.json` and
+// `hooks.json` are present there.
+//
+// After this call returns successfully the plugin's hooks are wired
+// but Codex still requires a one-time `/hooks` review inside the TUI
+// (a security measure) — we surface that requirement in the install
+// command's stdout summary.
+func enableCodexPlugin(marketplaceRoot string) error {
+ codexBin, err := resolveCodexBin()
+ if err != nil {
+ return err
+ }
+
+ // 1. Register (or refresh) the marketplace. Re-running this is
+ // idempotent in newer Codex builds — older builds error with a
+ // "marketplace already exists" message that we swallow.
+ add := exec.Command(codexBin, "plugin", "marketplace", "add", marketplaceRoot) //nolint:gosec
+ if out, err := add.CombinedOutput(); err != nil {
+ msg := strings.TrimSpace(string(out))
+ lower := strings.ToLower(msg)
+ // "already" → idempotent add, not a real error.
+ // "remote_plugin" / "feature flag" → newer builds gate the
+ // git/remote source flow, which we don't need (we pass a
+ // local path), so any other failure mode is what we want
+ // to surface.
+ if msg != "" && !strings.Contains(lower, "already") {
+ return fmt.Errorf("codex plugin marketplace add: %s", msg)
+ }
+ }
+
+ // 2. Install the plugin from the just-added marketplace. The slug
+ // is `<plugin_name>@<marketplace_name>`, both of which come
+ // from the JSON we shipped (`name: "openlit"` in
+ // `.codex-plugin/plugin.json` and `.agents/plugins/marketplace.json`).
+ inst := exec.Command(codexBin, "plugin", "add", "openlit@openlit") //nolint:gosec
+ if out, err := inst.CombinedOutput(); err != nil {
+ msg := strings.TrimSpace(string(out))
+ if strings.Contains(strings.ToLower(msg), "already") {
+ return nil
+ }
+ return fmt.Errorf("codex plugin add openlit@openlit: %s", msg)
+ }
+ return nil
+}
+
+// resolveCodexBin finds the codex binary in $PATH, then falls back to
+// the Codex.app default install location used by the macOS GUI app.
+// Codex on macOS doesn't symlink itself into /usr/local/bin out of the
+// box, which is why an `openlit coding install --vendor=codex` from a
+// shell where `codex` isn't on $PATH would silently no-op without
+// this fallback.
+func resolveCodexBin() (string, error) {
+ if path, err := exec.LookPath("codex"); err == nil {
+ return path, nil
+ }
+ fallbacks := []string{
+ "/Applications/Codex.app/Contents/Resources/codex",
+ }
+ if home, err := os.UserHomeDir(); err == nil {
+ fallbacks = append(fallbacks,
+ filepath.Join(home, "Applications", "Codex.app", "Contents", "Resources", "codex"),
+ filepath.Join(home, ".codex", "bin", "codex"),
+ )
+ }
+ for _, p := range fallbacks {
+ if info, err := os.Stat(p); err == nil && !info.IsDir() {
+ return p, nil
+ }
+ }
+ return "", fmt.Errorf("codex binary not found on PATH or at the standard Codex.app location")
+}
+
+func extractEmbeddedDir(src, dest, openlitBin string) error {
+ return fs.WalkDir(marketplaceFS, src, func(p string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ return nil
+ }
+ rel := strings.TrimPrefix(p, src+"/")
+ target := filepath.Join(dest, rel)
+ body, readErr := marketplaceFS.ReadFile(p)
+ if readErr != nil {
+ return readErr
+ }
+ body = patchManifestBytes(rel, body, openlitBin)
+ if mkErr := os.MkdirAll(filepath.Dir(target), 0o755); mkErr != nil {
+ return mkErr
+ }
+ return os.WriteFile(target, body, 0o644)
+ })
+}
diff --git a/cli/internal/coding/install/install_vendors.go b/cli/internal/coding/install/install_vendors.go
new file mode 100644
index 00000000..40712cdd
--- /dev/null
+++ b/cli/internal/coding/install/install_vendors.go
@@ -0,0 +1,147 @@
+// Per-vendor manifest writers. The actual manifest contents live under
+// .claude-plugin/ + plugins/ at the repo root and are embedded into the
+// binary via go:embed as a single assembled tree under marketplace/.
+// installVendor writes the appropriate subset to the user's home directory
+// for each vendor.
+
+package install
+
+import (
+ "embed"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// marketplaceFS holds the embedded Claude Code marketplace tree. The
+// contents are assembled by `cli/scripts/sync-plugins.sh` from the
+// two repo-root sources (`.claude-plugin/marketplace.json` and
+// `plugins/<vendor>/`) into a single in-tree mirror so the CLI binary
+// is self-contained — users don't need to clone the repo to run
+// `openlit coding install`.
+//
+// Layout inside the embed root matches the repo-root
+// layout exactly:
+//
+// marketplace/
+// .claude-plugin/marketplace.json
+// plugins/claude-code/
+// plugins/cursor/
+// plugins/codex/
+//
+// Keeping the layouts identical means the single marketplace.json
+// `source: "./plugins/claude-code"` resolves correctly whether Claude
+// fetches the marketplace from GitHub or from the local materialized
+// directory.
+//
+// `all:` prefix is required so go:embed descends into dot-prefixed
+// subdirectories (Claude Code's `.claude-plugin/`, Cursor's
+// `.cursor-plugin/`, Codex's `.codex-plugin/`).
+//
+//go:embed all:marketplace
+var marketplaceFS embed.FS
+
+// installVendor writes the manifest set for one vendor to the user's
+// home directory. Returns the absolute paths it touched.
+func installVendor(vendor string, dryRun bool) ([]string, error) {
+ // Cursor is special: its supported way to install agent-wide
+ // hooks is to merge into ~/.cursor/hooks.json (user scope), not
+ // to drop a plugin tree. See install_cursor.go for the why.
+ if vendor == "cursor" {
+ return installCursorHooks(dryRun)
+ }
+
+ dest, err := vendorDestRoot(vendor)
+ if err != nil {
+ return nil, err
+ }
+ srcDir := "marketplace/plugins/" + vendor
+
+ openlitBin, binErr := resolveOpenlitBin()
+ if binErr != nil {
+ return nil, fmt.Errorf("locate openlit binary: %w (install openlit and ensure it is on PATH)", binErr)
+ }
+
+ var written []string
+ walkErr := fs.WalkDir(marketplaceFS, srcDir, func(p string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ return nil
+ }
+ rel := strings.TrimPrefix(p, srcDir+"/")
+ target := filepath.Join(dest, rel)
+ written = append(written, target)
+ if dryRun {
+ return nil
+ }
+ body, readErr := marketplaceFS.ReadFile(p)
+ if readErr != nil {
+ return readErr
+ }
+ body = patchManifestBytes(rel, body, openlitBin)
+ if mkErr := os.MkdirAll(filepath.Dir(target), 0o755); mkErr != nil {
+ return mkErr
+ }
+ return os.WriteFile(target, body, 0o644)
+ })
+ if walkErr != nil {
+ // fs.ErrNotExist means we haven't authored manifests for this
+ // vendor yet — surface it as an explicit not-implemented rather
+ // than a confusing path error.
+ if os.IsNotExist(walkErr) {
+ return nil, fmt.Errorf("manifest set not bundled for vendor %q (please file an issue)", vendor)
+ }
+ return nil, walkErr
+ }
+
+ if !dryRun && vendor == "claude-code" {
+ if err := enableClaudeCodePlugin(); err != nil {
+ fmt.Fprintf(os.Stderr, "openlit install: could not register Claude Code plugin via `claude` CLI: %v\n", err)
+ fmt.Fprintf(os.Stderr, "openlit install: hooks were still written to %s — in Claude Code run: /plugin marketplace add <openlit-repo>/plugins then /plugin install openlit-cc@openlit\n", dest)
+ }
+ }
+ if !dryRun && vendor == "codex" {
+ if err := enableCodexPlugin(dest); err != nil {
+ fmt.Fprintf(os.Stderr, "openlit install: could not register Codex plugin via `codex` CLI: %v\n", err)
+ fmt.Fprintf(os.Stderr, "openlit install: marketplace was written to %s — in Codex run: codex plugin marketplace add %s then codex plugin add openlit@openlit, then open /hooks inside Codex and trust each hook\n", dest, dest)
+ }
+ }
+ return written, nil
+}
+
+// vendorDestRoot returns the directory under $HOME where this vendor's
+// manifests must land. We honor each vendor's own conventions:
+//
+// Claude Code → ~/.claude/plugins/openlit-cc/
+// Codex → ~/.local/share/openlit/codex-marketplace/ (a local
+// marketplace registered via `codex plugin marketplace add`)
+//
+// Cursor is intentionally absent: it installs by merging into
+// ~/.cursor/hooks.json (user scope), not by writing a plugin tree.
+// See install_cursor.go for the rationale.
+//
+// For Codex specifically: dropping files under `~/.codex/plugins/<name>/`
+// is NOT how Codex's plugin loader discovers plugins. The loader scans
+// configured marketplaces (`codex plugin marketplace list`) and only
+// installs plugins by name via `codex plugin add <plugin>@<marketplace>`.
+// We therefore materialize a self-contained marketplace tree at a
+// stable location and register it via the `codex` CLI in
+// enableCodexPlugin() (see install_patch.go).
+func vendorDestRoot(vendor string) (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("could not resolve home directory: %w", err)
+ }
+ switch vendor {
+ case "claude-code":
+ return filepath.Join(home, ".claude", "plugins", "openlit-cc"), nil
+ case "codex":
+ return filepath.Join(home, ".local", "share", "openlit", "codex-marketplace"), nil
+ default:
+ return "", fmt.Errorf("unknown vendor %q", vendor)
+ }
+}
diff --git a/cli/internal/coding/install/marketplace/.claude-plugin/marketplace.json b/cli/internal/coding/install/marketplace/.claude-plugin/marketplace.json
new file mode 100644
index 00000000..3d8a124f
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/.claude-plugin/marketplace.json
@@ -0,0 +1,17 @@
+{
+ "name": "openlit",
+ "owner": {
+ "name": "OpenLit",
+ "email": "[email protected]"
+ },
+ "plugins": [
+ {
+ "name": "openlit-cc",
+ "description": "OpenTelemetry-native session, tool, and edit-decision capture for Claude Code.",
+ "author": {
+ "name": "OpenLit"
+ },
+ "source": "./plugins/claude-code"
+ }
+ ]
+}
diff --git a/cli/internal/coding/install/marketplace/plugins/claude-code/.claude-plugin/plugin.json b/cli/internal/coding/install/marketplace/plugins/claude-code/.claude-plugin/plugin.json
new file mode 100644
index 00000000..b2165aeb
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/plugins/claude-code/.claude-plugin/plugin.json
@@ -0,0 +1,11 @@
+{
+ "name": "openlit-cc",
+ "version": "0.1.0",
+ "description": "OpenLit telemetry for Claude Code: sessions, tool calls, edit decisions, and cost rollups.",
+ "author": {
+ "name": "OpenLit",
+ "url": "https://openlit.io"
+ },
+ "repository": "https://github.com/openlit/openlit",
+ "homepage": "https://openlit.io"
+}
diff --git a/cli/internal/coding/install/marketplace/plugins/claude-code/hooks/hooks.json b/cli/internal/coding/install/marketplace/plugins/claude-code/hooks/hooks.json
new file mode 100644
index 00000000..c00dfabe
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/plugins/claude-code/hooks/hooks.json
@@ -0,0 +1,83 @@
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=SessionStart",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=UserPromptSubmit",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=PreToolUse",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=PostToolUse",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=Stop",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "SubagentStop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=SubagentStop",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "SessionEnd": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=SessionEnd",
+ "timeout": 5
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/cli/internal/coding/install/marketplace/plugins/codex/.agents/plugins/marketplace.json b/cli/internal/coding/install/marketplace/plugins/codex/.agents/plugins/marketplace.json
new file mode 100644
index 00000000..ab786b53
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/plugins/codex/.agents/plugins/marketplace.json
@@ -0,0 +1,23 @@
+{
+ "name": "openlit",
+ "interface": {
+ "displayName": "OpenLit",
+ "shortDescription": "OpenTelemetry-native session, tool, and turn capture for Codex.",
+ "developerName": "OpenLit",
+ "websiteURL": "https://openlit.io"
+ },
+ "plugins": [
+ {
+ "name": "openlit",
+ "source": {
+ "source": "local",
+ "path": "./plugins/openlit"
+ },
+ "policy": {
+ "installation": "AVAILABLE",
+ "authentication": "ON_INSTALL"
+ },
+ "category": "Engineering"
+ }
+ ]
+}
diff --git a/cli/internal/coding/install/marketplace/plugins/codex/plugins/openlit/.codex-plugin/plugin.json b/cli/internal/coding/install/marketplace/plugins/codex/plugins/openlit/.codex-plugin/plugin.json
new file mode 100644
index 00000000..4c6152ee
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/plugins/codex/plugins/openlit/.codex-plugin/plugin.json
@@ -0,0 +1,22 @@
+{
+ "name": "openlit",
+ "displayName": "OpenLit",
+ "version": "0.1.0",
+ "description": "OpenLit telemetry for Codex: sessions, tool calls, LLM turns with token usage, and cost rollups.",
+ "author": {
+ "name": "OpenLit",
+ "url": "https://openlit.io"
+ },
+ "repository": "https://github.com/openlit/openlit",
+ "homepage": "https://openlit.io",
+ "license": "Apache-2.0",
+ "keywords": ["telemetry", "observability", "openlit", "codex"],
+ "hooks": "./hooks/hooks.json",
+ "interface": {
+ "displayName": "OpenLit for Codex",
+ "shortDescription": "OpenTelemetry-native session, tool, and turn capture",
+ "developerName": "OpenLit",
+ "category": "Engineering",
+ "capabilities": ["Read", "Write"]
+ }
+}
diff --git a/cli/internal/coding/install/marketplace/plugins/codex/plugins/openlit/hooks/hooks.json b/cli/internal/coding/install/marketplace/plugins/codex/plugins/openlit/hooks/hooks.json
new file mode 100644
index 00000000..94e96ac2
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/plugins/codex/plugins/openlit/hooks/hooks.json
@@ -0,0 +1,62 @@
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "matcher": "startup|resume|clear",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=SessionStart",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=UserPromptSubmit",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=PreToolUse",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=PostToolUse",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=Stop",
+ "timeout": 30
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/cli/internal/coding/install/marketplace/plugins/cursor/.cursor-plugin/plugin.json b/cli/internal/coding/install/marketplace/plugins/cursor/.cursor-plugin/plugin.json
new file mode 100644
index 00000000..4a274d5b
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/plugins/cursor/.cursor-plugin/plugin.json
@@ -0,0 +1,12 @@
+{
+ "name": "openlit",
+ "displayName": "OpenLit",
+ "version": "0.1.0",
+ "description": "OpenLit telemetry for Cursor: sessions, tool calls, edit decisions, and cost rollups.",
+ "author": {
+ "name": "OpenLit",
+ "url": "https://openlit.io"
+ },
+ "repository": "https://github.com/openlit/openlit",
+ "homepage": "https://openlit.io"
+}
diff --git a/cli/internal/coding/install/marketplace/plugins/cursor/hooks/hooks.json b/cli/internal/coding/install/marketplace/plugins/cursor/hooks/hooks.json
new file mode 100644
index 00000000..4fa4e420
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/plugins/cursor/hooks/hooks.json
@@ -0,0 +1,113 @@
+{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=sessionStart",
+ "timeout": 5000
+ }
+ ],
+ "sessionEnd": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=sessionEnd",
+ "timeout": 5000
+ }
+ ],
+ "beforeSubmitPrompt": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=beforeSubmitPrompt",
+ "timeout": 5000
+ }
+ ],
+ "afterAgentResponse": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterAgentResponse",
+ "timeout": 5000
+ }
+ ],
+ "afterAgentThought": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterAgentThought",
+ "timeout": 5000
+ }
+ ],
+ "preToolUse": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=preToolUse",
+ "timeout": 5000
+ }
+ ],
+ "postToolUse": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=postToolUse",
+ "timeout": 5000
+ }
+ ],
+ "postToolUseFailure": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=postToolUseFailure",
+ "timeout": 5000
+ }
+ ],
+ "subagentStart": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=subagentStart",
+ "timeout": 5000
+ }
+ ],
+ "subagentStop": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=subagentStop",
+ "timeout": 5000
+ }
+ ],
+ "beforeShellExecution": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=beforeShellExecution",
+ "timeout": 5000
+ }
+ ],
+ "afterShellExecution": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterShellExecution",
+ "timeout": 5000
+ }
+ ],
+ "beforeMCPExecution": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=beforeMCPExecution",
+ "timeout": 5000
+ }
+ ],
+ "afterMCPExecution": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterMCPExecution",
+ "timeout": 5000
+ }
+ ],
+ "beforeReadFile": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=beforeReadFile",
+ "timeout": 5000
+ }
+ ],
+ "afterFileEdit": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterFileEdit",
+ "timeout": 5000
+ }
+ ],
+ "preCompact": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=preCompact",
+ "timeout": 5000
+ }
+ ],
+ "stop": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=stop",
+ "timeout": 5000
+ }
+ ]
+ }
+}
diff --git a/cli/internal/coding/launch/exec_unix.go b/cli/internal/coding/launch/exec_unix.go
new file mode 100644
index 00000000..97373d64
--- /dev/null
+++ b/cli/internal/coding/launch/exec_unix.go
@@ -0,0 +1,15 @@
+//go:build !windows
+
+package launch
+
+import (
+ "os"
+ "syscall"
+)
+
+// defaultExecReplace replaces the current process with the agent's. On
+// Unix this is a real exec(2): the user's TTY connects directly to the
+// agent and our process is gone.
+func defaultExecReplace(path string, args []string) error {
+ return syscall.Exec(path, args, os.Environ()) //nolint:gosec // intentional self-replacing exec
+}
diff --git a/cli/internal/coding/launch/exec_windows.go b/cli/internal/coding/launch/exec_windows.go
new file mode 100644
index 00000000..17b1618c
--- /dev/null
+++ b/cli/internal/coding/launch/exec_windows.go
@@ -0,0 +1,26 @@
+//go:build windows
+
+package launch
+
+import (
+ "os"
+ "os/exec"
+)
+
+// defaultExecReplace fakes exec(2) on Windows by spawning a child and
+// exiting with its status. Stdio is wired straight through so it behaves
+// like a real exec from the user's perspective.
+func defaultExecReplace(path string, args []string) error {
+ c := exec.Command(path, args[1:]...)
+ c.Stdin = os.Stdin
+ c.Stdout = os.Stdout
+ c.Stderr = os.Stderr
+ if err := c.Run(); err != nil {
+ if exitErr, ok := err.(*exec.ExitError); ok {
+ os.Exit(exitErr.ExitCode())
+ }
+ return err
+ }
+ os.Exit(0)
+ return nil
+}
diff --git a/cli/internal/coding/launch/launch.go b/cli/internal/coding/launch/launch.go
new file mode 100644
index 00000000..60b51c25
--- /dev/null
+++ b/cli/internal/coding/launch/launch.go
@@ -0,0 +1,124 @@
+// Package launch implements `openlit coding launch <agent>`.
+//
+// Behavior: ensure the per-vendor manifest is installed (auto-runs the
+// install logic if it isn't), then exec the agent's own CLI with whatever
+// args followed.
+package launch
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+
+ "github.com/spf13/cobra"
+)
+
+// NewCmd returns the `openlit coding launch` cobra command.
+func NewCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "launch <agent> [-- agent-args...]",
+ Short: "Bootstrap the openlit plugin for an agent and exec it",
+ Long: `Bootstrap the openlit host plugin manifest for the chosen agent, then
+exec the agent's own CLI.
+
+Example:
+
+ openlit coding launch claude
+ openlit coding launch cursor -- --debug
+ openlit coding launch codex
+
+The agent's binary must be on PATH. The plugin manifest is installed
+idempotently — running 'launch' twice is a no-op the second time.`,
+ Args: cobra.MinimumNArgs(1),
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return run(cmd, args)
+ },
+ }
+ return cmd
+}
+
+func run(cmd *cobra.Command, args []string) error {
+ agent := strings.ToLower(strings.TrimSpace(args[0]))
+ if agent == "" {
+ return errors.New("agent name is required")
+ }
+
+ bin, err := agentBinary(agent)
+ if err != nil {
+ return err
+ }
+
+ // Resolve the agent's binary first so we can fail fast if it's not
+ // on PATH; no point installing a manifest for a missing CLI.
+ resolved, lookErr := exec.LookPath(bin)
+ if lookErr != nil {
+ return fmt.Errorf("could not find %q on PATH: %w", bin, lookErr)
+ }
+
+ if err := ensureInstalled(cmd, agent); err != nil {
+ // Don't block launch on manifest install failure — the agent
+ // can still run, just without our hook. Print the error so the
+ // user knows.
+ fmt.Fprintf(cmd.ErrOrStderr(), "openlit launch: warning: install %s manifest failed: %v\n", agent, err)
+ }
+
+ // exec replaces the current process — this is intentional so the
+ // user's terminal hooks back up to the agent's stdio without us in
+ // the middle.
+ rest := args[1:]
+ // Strip an optional `--` separator inserted by cobra so it doesn't
+ // reach the agent.
+ if len(rest) > 0 && rest[0] == "--" {
+ rest = rest[1:]
+ }
+ return execReplace(resolved, append([]string{bin}, rest...))
+}
+
+// agentBinary maps the user-friendly agent argument to the binary name
+// we expect on PATH.
+func agentBinary(agent string) (string, error) {
+ switch agent {
+ case "claude", "claude-code", "cc":
+ return "claude", nil
+ case "cursor":
+ return "cursor", nil
+ case "codex":
+ return "codex", nil
+ default:
+ return "", fmt.Errorf("unknown agent %q (allowed: claude, cursor, codex)", agent)
+ }
+}
+
+// ensureInstalled runs the install logic for one vendor. We don't import
+// the install package directly to avoid a circular dependency potential;
+// instead, we re-spawn ourselves with `coding install --vendor=...`.
+// On the recommended install paths the binary is on PATH already.
+func ensureInstalled(cmd *cobra.Command, agent string) error {
+ vendor := vendorOf(agent)
+ exe, err := os.Executable()
+ if err != nil {
+ return fmt.Errorf("locate self: %w", err)
+ }
+ c := exec.Command(exe, "coding", "install", "--vendor", vendor) //nolint:gosec // self-exec
+ c.Stdout = cmd.OutOrStdout()
+ c.Stderr = cmd.ErrOrStderr()
+ return c.Run()
+}
+
+func vendorOf(agent string) string {
+ switch agent {
+ case "claude", "cc":
+ return "claude-code"
+ default:
+ return agent
+ }
+}
+
+// execReplace is the exec(2) syscall on POSIX; Windows fakes it via a
+// child process + os.Exit. The cli/internal/coding/launch/exec_*.go
+// files implement the platform-specific bits.
+var execReplace = defaultExecReplace
diff --git a/cli/internal/coding/normalize/normalize.go b/cli/internal/coding/normalize/normalize.go
new file mode 100644
index 00000000..65208c6e
--- /dev/null
+++ b/cli/internal/coding/normalize/normalize.go
@@ -0,0 +1,402 @@
+// Package normalize defines the contract every per-vendor hook adapter
+// implements, plus the canonical Span/Event types they emit.
+//
+// The split is deliberate: per-vendor adapters under hook/<vendor>/ deal
+// with the vendor's quirks (Claude Code stdin JSON, Cursor 8-event-list,
+// Codex rollout JSONL); the normalize.* types here are what every adapter
+// produces, and what the OTLP emitter consumes. One canonical schema = one
+// dashboard regardless of the vendor it came from.
+package normalize
+
+import (
+ "context"
+ "time"
+)
+
+// Adapter is the interface a per-vendor hook implementation satisfies.
+type Adapter interface {
+ // Vendor returns the vendor identifier as it appears in
+ // gen_ai.agent.name / coding_agent.client (e.g. "claude-code").
+ Vendor() string
+
+ // Handle processes one hook invocation. It is invoked synchronously
+ // by the hook subcommand; implementations must respect the context
+ // deadline and return promptly. Errors returned from Handle are
+ // logged to stderr; the hook subcommand always exits 0.
+ Handle(ctx context.Context, in Input) error
+}
+
+// Input is the per-invocation payload an adapter receives from the hook
+// subcommand. Adapters MAY ignore Event when the vendor does not
+// communicate event names through the hook flag.
+type Input struct {
+ // Vendor is the resolved vendor identifier (matches Adapter.Vendor()).
+ Vendor string
+
+ // Event is the vendor-specific event name (e.g. "SessionStart",
+ // "PreToolUse", "Stop"). Empty when the vendor omits it.
+ Event string
+
+ // Payload is the entire stdin body from the host plugin.
+ Payload []byte
+
+ // ContentCapture is one of "minimal" | "metadata_only" | "full".
+ // Adapters MUST honor this when constructing event/span
+ // attributes that would otherwise contain prompt or tool-arg
+ // bodies. See Phase C of the coding-agents plan for the full
+ // per-mode attribute matrix.
+ ContentCapture string
+
+ // Emit is the OTLP-bound emitter the adapter writes to.
+ Emit Emitter
+}
+
+// Emitter is the surface adapters use to produce OTel spans/events. The
+// concrete implementation lives in internal/otlp; we keep this interface
+// in normalize/ so adapters don't import the otlp package and we can
+// swap exporters in tests without churn.
+type Emitter interface {
+ // EmitSession emits a single coding-agent session span.
+ EmitSession(Session) error
+ // EmitToolCall emits a coding-agent tool-call span.
+ EmitToolCall(ToolCall) error
+ // EmitEditDecision emits an edit-decision span (or event, depending
+ // on the implementation; the adapter doesn't care).
+ EmitEditDecision(EditDecision) error
+ // EmitLLMTurn emits a coding-agent LLM-turn span — one per
+ // model-generation pair (prompt → response). Captures the prompt
+ // and (optional) response text plus token usage when available.
+ // This is the "generation" concept from OTel GenAI.
+ EmitLLMTurn(LLMTurn) error
+ // EmitSubagent emits a coding-agent subagent span representing one
+ // child agent's lifecycle. Carries the subagent type, parent linkage,
+ // status, and modified-files set so the parent session's tree view
+ // can drill into the child.
+ EmitSubagent(Subagent) error
+ // EmitEvent emits a free-form span event under the provided session
+ // or tool span name. Used for high-cardinality moments where a
+ // dedicated span would be overkill (e.g. loop detected).
+ EmitEvent(EventEmission) error
+ // EmitGitCommit emits a single `coding_agent.git.commit` span
+ // representing one agent-attributed git commit. The emitter is
+ // expected to also bump the `coding_agent.commit.count` metric
+ // counter.
+ EmitGitCommit(GitCommit) error
+ // EmitGitPullRequest emits a single `coding_agent.git.pull_request`
+ // span representing one agent-attributed PR / MR create or push.
+ // The emitter is expected to also bump the
+ // `coding_agent.pull_request.count` metric counter.
+ EmitGitPullRequest(GitPullRequest) error
+}
+
+// Session is the canonical "this agent ran" span. Adapters populate as
+// many fields as the vendor's payload supports; missing fields are
+// allowed and dashboard widgets handle nulls.
+type Session struct {
+ SessionID string
+ ConversationID string
+
+ Vendor string
+ ClientVersion string
+ Model string
+ Provider string
+
+ StartedAt time.Time
+ EndedAt time.Time
+ Duration time.Duration
+
+ Outcome string // see semconv.CodingAgentSessionOutcome*
+ ToolCallCount int
+ SubagentCount int
+ CostUSD float64
+ InputTokens int64
+ OutputTokens int64
+ TotalTokens int64
+
+ // Code-change rollups stamped on the session-root span at
+ // SessionEnd (or as the session progresses for vendors like Codex
+ // that have no SessionEnd hook). All four line counts are absolute
+ // totals across the session, not deltas. Accept / reject counters
+ // reflect explicit user decisions where the vendor exposes them
+ // (Claude Code Pre+Post pair), and the auto-applied policy
+ // decisions on Cursor / Codex (both bump accept).
+ LinesAdded int
+ LinesRemoved int
+ LinesAccepted int
+ LinesRejected int
+ EditAcceptCount int
+ EditRejectCount int
+ // Agent-attributed git activity. Detected via the agent's
+ // Bash / shell tool invocations only — a developer manually
+ // running `git commit` outside the agent's tool does NOT count.
+ CommitCount int
+ PRCount int
+
+ // VCS fields, populated by cli/internal/coding/git/.
+ RepoURL string
+ HeadSHA string
+ BranchName string
+ VCSDirty bool
+
+ // Identity / classification.
+ UserID string
+ UserClassification string // "personal" | "work" | "disputed" | "unknown"
+ ClassificationReason string
+
+ // Permission posture.
+ PermissionMode string
+
+ // CWD is the working directory the agent is operating in
+ // (Cursor's `cwd` / `workspace_roots[0]`). Surfaced on the
+ // session span so the trace-detail header can show "Working
+ // folder" alongside the repo URL.
+ CWD string
+
+ // Free-form vendor extras for the future. Adapters use this for
+ // vendor-specific signals we don't (yet) want in the canonical
+ // schema. Keys MUST already be namespaced (e.g.
+ // "claude_code.transcript_path").
+ Extras map[string]string
+}
+
+// ToolCall is the canonical tool-call span.
+type ToolCall struct {
+ SessionID string
+ AgentID string
+ ToolName string
+ ToolUseID string
+ GroupID string
+ GroupType string
+ Iteration int
+
+ StartedAt time.Time
+ EndedAt time.Time
+ Duration time.Duration
+
+ // Errored is true if the tool returned a non-zero / failure.
+ Errored bool
+ ErrorMsg string
+ FailureType string // "error" | "timeout" | "permission_denied" (Cursor)
+ IsInterrupt bool
+
+ // MCP attribution (if this tool came from an MCP server).
+ MCPServerName string
+ MCPScope string
+ MCPTransport string
+ MCPSource string
+
+ // Triggering LLM request.
+ TriggeringLLMRequestID string
+ Model string
+
+ // Sandboxed is true when the tool ran in a sandboxed environment
+ // (Cursor's `sandbox` flag for shell execution).
+ Sandboxed bool
+
+ WorkingDir string
+ Command string
+
+ Vendor string
+ // Argument body — only populated when ContentCapture == "full".
+ Args string
+ // Result body — only populated when ContentCapture == "full".
+ Result string
+
+ // AgentMessage is the assistant's running narration when the
+ // agent calls a tool (Cursor's `agent_message`). Useful for
+ // drilling into "why did the agent run this tool" — only
+ // populated under full capture.
+ AgentMessage string
+}
+
+// EditDecision captures one user/agent edit outcome. Vendors that emit a
+// PostEdit hook (Claude Code, Codex) call EmitEditDecision once
+// per modified file.
+type EditDecision struct {
+ SessionID string
+ AgentID string
+ Decision string // accept | reject | modify | auto_accepted
+ Source string // user_interactive | user_permanent_rule | hook | config | policy
+ Tool string
+ Language string
+ LinesAdded int
+ LinesRemoved int
+ FilePath string
+
+ Vendor string
+
+ At time.Time
+}
+
+// LLMTurn captures one user-prompt / assistant-response cycle (also
+// known as a "generation"). Vendors map their hooks onto this:
+//
+// - Cursor: beforeSubmitPrompt → StartedAt + Prompt
+// afterAgentResponse → EndedAt + Response
+// afterAgentThought → ThoughtText
+// - Claude Code: derived from transcript JSONL turns at SessionEnd
+// - Codex: derived from rollout JSONL on Stop
+//
+// When an emitter receives an LLMTurn that has only StartedAt/Prompt
+// (the "begin" half), it should emit a short-lived span at that time so
+// the prompt is preserved even if the matching afterAgentResponse never
+// fires (e.g. session aborted mid-generation).
+type LLMTurn struct {
+ SessionID string
+ ConversationID string
+ GenerationID string
+ Vendor string
+ Model string
+
+ StartedAt time.Time
+ EndedAt time.Time
+
+ // Prompt and Response are captured ONLY when ContentCapture == "full".
+ // Both arrive truncated to a sane upper bound at the otlp layer.
+ // They hold the user's verbatim prompt and the assistant's text
+ // reply respectively. The emitter wraps them into OTel-canonical
+ // `gen_ai.{input,output}.messages` envelopes
+ // (https://github.com/open-telemetry/semantic-conventions-genai
+ // → docs/gen-ai/gen-ai-spans.md) at attribute-emission time, so
+ // adapters never deal with the JSON shape directly.
+ //
+ // Tool calls and tool results that bracket this turn are NOT
+ // stamped onto the LLM-turn span. They live on dedicated
+ // `coding_agent.tool.call` spans (with
+ // `gen_ai.tool.call.arguments` / `gen_ai.tool.call.result`); the
+ // chat view interleaves those spans with LLM turns by timestamp,
+ // so the conversation reconstructs from per-turn LLM spans +
+ // per-tool tool.call spans without duplicative narration. The
+ // previous design folded the tool bodies into each turn's
+ // messages JSON, which routinely exceeded the 16 KB span-
+ // attribute cap and broke the chat view's parser.
+ Prompt string
+ Response string
+ // ThoughtText is the assistant's reasoning/thinking block, when
+ // the vendor exposes it (e.g. Cursor afterAgentThought, Claude
+ // Code extended-thinking blocks). Captured separately so
+ // dashboards can hide it by default.
+ ThoughtText string
+ ThoughtMs int64
+
+ // Attachments lists the prompt attachments the user supplied (file
+ // paths, rule files). High-signal, low-cardinality, so always
+ // captured regardless of ContentCapture.
+ AttachmentPaths []string
+
+ InputTokens int64
+ OutputTokens int64
+ TotalTokens int64
+ CostUSD float64
+ // CacheReadTokens / CacheCreationTokens are the OTel-standard
+ // gen_ai cache fields. Anthropic exposes them on every response;
+ // OpenAI doesn't yet. Zero means "vendor didn't tell us" — never
+ // "actually zero".
+ CacheReadTokens int64
+ CacheCreationTokens int64
+
+ // FinishReasons holds the OTel-standard
+ // `gen_ai.response.finish_reasons` array. We accept multiple
+ // because some vendors send `["tool_use","stop"]` when a tool
+ // call followed by stop happens in the same turn.
+ FinishReasons []string
+
+ // AssistantMessageOnly is true when the LLM turn is only the
+ // "after" half (afterAgentResponse) without a paired prompt — the
+ // dashboard renders these as continuation turns rather than full
+ // generations.
+ AssistantMessageOnly bool
+
+ // PermissionMode + UserEmail / UserID from the hook payload.
+ UserEmail string
+
+ // Extras carries per-turn high-signal tags that don't have a
+ // dedicated normalized field yet. Common keys cover generation
+ // metadata (`git.branch`, `cwd`, `claude_code.entrypoint`,
+ // `claude_code.subagent`). Stamped as `string` span attributes by
+ // the emitter — adapters MUST namespace their keys.
+ Extras map[string]string
+}
+
+// Subagent captures one subagent (Task tool) lifecycle. start and stop
+// arrive on different hook invocations; we emit one span per stop with
+// the linkage attributes set, plus a low-cost event on start so the
+// dashboard can show in-flight subagents.
+type Subagent struct {
+ SessionID string
+ ParentConversationID string
+ SubagentID string
+ SubagentType string
+ Task string
+ Description string
+ Summary string
+ Vendor string
+ Model string
+ GitBranch string
+ IsParallelWorker bool
+
+ StartedAt time.Time
+ EndedAt time.Time
+ DurationMs int64
+ MessageCount int
+ ToolCallCount int
+ LoopCount int
+
+ // Status is one of: started | completed | error | aborted.
+ Status string
+ // ModifiedFiles is the file list the subagent touched, when reported.
+ ModifiedFiles []string
+ // ToolCallID is the parent tool-call that spawned this subagent;
+ // useful when joining tool-call spans → subagent spans.
+ ToolCallID string
+}
+
+// EventEmission is the catch-all for span events the dedicated structs
+// above don't cover.
+type EventEmission struct {
+ SessionID string
+ Name string
+ At time.Time
+ Attrs map[string]any
+}
+
+// GitCommit captures one agent-attributed git commit, detected by the
+// vendor adapter parsing a `git commit` invocation in the agent's
+// Bash / shell tool stream. Vendors that surface the resulting SHA
+// (via the tool's stdout) fill SHA; vendors that don't leave it empty
+// and the emitter falls back to the at-emit time.
+//
+// Message is captured only under `full` content capture.
+type GitCommit struct {
+ SessionID string
+ Vendor string
+ UserID string
+ Tool string // "Bash" | "shell" | "local_shell"
+
+ SHA string
+ Message string
+
+ WorkingDir string
+ At time.Time
+}
+
+// GitPullRequest captures one agent-attributed PR / MR creation,
+// detected by the vendor adapter parsing a `gh pr create`, GitLab
+// equivalent, or push-with-PR-URL invocation in the agent's
+// Bash / shell tool stream.
+//
+// Number / Title are best-effort — only populated when the underlying
+// tool stdout carried them. URL is the canonical join key.
+type GitPullRequest struct {
+ SessionID string
+ Vendor string
+ UserID string
+ Tool string
+
+ URL string
+ Number int
+ Title string
+
+ WorkingDir string
+ At time.Time
+}
diff --git a/cli/internal/coding/pricing/pricing.go b/cli/internal/coding/pricing/pricing.go
new file mode 100644
index 00000000..efbc8f34
--- /dev/null
+++ b/cli/internal/coding/pricing/pricing.go
@@ -0,0 +1,381 @@
+// Package pricing returns realized USD cost from token counts using a
+// small static table of public list prices.
+//
+// The CLI is short-lived and offline-safe; we do not fetch live pricing.
+// Rates here are last-known public list prices (2026-05) and are kept
+// deliberately conservative — we'd rather under-bill than over-bill the
+// dashboard. The server can replace these with org-specific contract
+// rates at materialization time.
+//
+// All rates are USD per 1,000,000 tokens.
+package pricing
+
+import "strings"
+
+// Rate captures input + output rates for a model family.
+//
+// Anthropic prompt caching has *two* rates that differ by ~12x:
+// - cache reads (re-using a previously cached prefix) cost ~0.10x input
+// - cache writes (creating / refreshing a cache entry) cost ~1.25x input
+//
+// We model them as separate fields. OpenAI's caching is implicit and
+// only surfaces a "cached tokens" count (no separate write rate), so
+// for OpenAI models we leave CacheCreationPer1M at zero and use
+// CachedReadPer1M for the cached portion.
+type Rate struct {
+ InputPer1M float64
+ OutputPer1M float64
+ // CachedReadPer1M is the cache-read rate (Anthropic) or the implicit
+ // cached-input rate (OpenAI). When zero, Cost treats cache reads as
+ // full input rate.
+ CachedReadPer1M float64
+ // CacheCreationPer1M is the cache-write rate (Anthropic prompt
+ // caching writes, ~1.25x input). Zero for vendors without a
+ // separate cache-write price — see Cost for the fallback rule.
+ CacheCreationPer1M float64
+}
+
+// Cost returns the realized USD cost for the supplied token counts.
+//
+// - `cacheRead` is the subset of `input` that came from a previously
+// cached prefix (Anthropic `cache_read_input_tokens`, OpenAI
+// `cached_tokens`).
+// - `cacheCreation` is the subset of `input` that wrote a new cache
+// entry (Anthropic `cache_creation_input_tokens`). Zero for vendors
+// without an explicit cache-write signal.
+//
+// Both `cacheRead` and `cacheCreation` are subtracted from `input`
+// before billing — `input` is the *total* input token count, not the
+// fresh-only count.
+func (r Rate) Cost(input, output, cacheRead, cacheCreation int64) float64 {
+ if r.InputPer1M == 0 && r.OutputPer1M == 0 {
+ return 0
+ }
+ cacheReadRate := r.CachedReadPer1M
+ if cacheReadRate == 0 {
+ cacheReadRate = r.InputPer1M
+ }
+ // Safety fallback: if a model entry forgets to set
+ // CacheCreationPer1M but the request actually has cache_creation
+ // tokens, bill them at the input rate rather than $0. This
+ // guarantees missing-rate bugs **under**-bill by a small margin
+ // (Anthropic's actual cache-write premium is 1.25x input) instead
+ // of silently dropping to free.
+ cacheCreationRate := r.CacheCreationPer1M
+ if cacheCreationRate == 0 && cacheCreation > 0 {
+ cacheCreationRate = r.InputPer1M
+ }
+ freshInput := input - cacheRead - cacheCreation
+ if freshInput < 0 {
+ freshInput = 0
+ }
+ return (float64(freshInput)*r.InputPer1M +
+ float64(cacheRead)*cacheReadRate +
+ float64(cacheCreation)*cacheCreationRate +
+ float64(output)*r.OutputPer1M) / 1_000_000.0
+}
+
+// Lookup returns the best-effort rate for a given model id. Matching is
+// substring-based (case-insensitive) so we don't have to enumerate every
+// minor revision (e.g. claude-sonnet-4-5-20251022 still matches "claude-sonnet-4").
+//
+// Returns the zero Rate (which produces $0) when nothing matches; the
+// caller should fall through to "no cost data" rather than guessing.
+func Lookup(model string) Rate {
+ low := strings.ToLower(model)
+ for _, e := range table {
+ for _, pat := range e.match {
+ if strings.Contains(low, pat) {
+ return e.rate
+ }
+ }
+ }
+ return Rate{}
+}
+
+type entry struct {
+ match []string
+ rate Rate
+}
+
+// table is intentionally small. Each entry covers a model family; the
+// patterns are substrings so we tolerate vendor revisions without code
+// edits. Order matters — first-match wins, so put more-specific
+// patterns ahead of broader ones.
+//
+// References (verified May 2026):
+// - Anthropic: https://www.anthropic.com/pricing#anthropic-api
+// - OpenAI / Codex: https://openai.com/api/pricing/ +
+// https://developers.openai.com/codex/pricing
+// - Google Gemini: https://ai.google.dev/pricing
+// - xAI Grok: https://docs.x.ai/docs/models
+// - Cursor (Composer + routed models):
+// https://cursor.com/docs/models-and-pricing
+// - Moonshot Kimi: https://platform.moonshot.ai/docs/pricing
+//
+// IMPORTANT: the order below is load-bearing. We've been bitten more
+// than once by a generic `claude-opus-4` pattern eating the new $5/$25
+// Opus 4.5+ pricing. ALWAYS list versioned variants before the family
+// prefix.
+//
+// CacheCreationPer1M (Anthropic only) is set to 1.25x InputPer1M per
+// Anthropic's prompt caching docs. CachedReadPer1M is ~10% of input.
+// OpenAI / Google / xAI / Cursor / Moonshot leave CacheCreationPer1M
+// at 0 — their APIs don't surface a separate cache-write count.
+var table = []entry{
+ // --- Anthropic Claude family -----------------------------------
+ // Opus 4.5+ dropped to $5/$25 in 2025-10 (down from the original
+ // Opus 4 / 4.1 launch price of $15/$75). We special-case the
+ // later versions so Cursor's `claude-opus-4-7-thinking-*` SKUs and
+ // the bare `claude-opus-4-5` / `4-6` / `4-7` / `4-8` ids price
+ // correctly. Note the "-fast" variants (Anthropic priority tier,
+ // also exposed via Cursor) carry a ~6x premium.
+ {
+ match: []string{"claude-opus-4-8-fast", "claude-opus-4-7-fast", "claude-opus-4-6-fast", "claude-opus-4-5-fast"},
+ rate: Rate{InputPer1M: 30.00, OutputPer1M: 150.00, CachedReadPer1M: 3.00, CacheCreationPer1M: 37.50},
+ },
+ {
+ match: []string{"claude-opus-4-8", "claude-opus-4-7", "claude-opus-4-6", "claude-opus-4-5"},
+ rate: Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25},
+ },
+ {
+ // Legacy Opus 4 / 4.1: still on the $15/$75 list price.
+ match: []string{"claude-opus-4-0", "claude-opus-4-1", "claude-4-opus"},
+ rate: Rate{InputPer1M: 15.00, OutputPer1M: 75.00, CachedReadPer1M: 1.50, CacheCreationPer1M: 18.75},
+ },
+ {
+ // Generic "claude-opus-4" / "claude-4-opus" with no version
+ // suffix. We bias toward the modern rate because new SDKs and
+ // Cursor builds default to the latest Opus, and undercharging is
+ // preferable to a 3x overcharge.
+ match: []string{"claude-opus-4"},
+ rate: Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25},
+ },
+ {
+ match: []string{"claude-sonnet-4", "claude-4-sonnet", "claude-4.5-sonnet", "claude-4.6-sonnet", "claude-4.7-sonnet"},
+ rate: Rate{InputPer1M: 3.00, OutputPer1M: 15.00, CachedReadPer1M: 0.30, CacheCreationPer1M: 3.75},
+ },
+ {
+ match: []string{"claude-haiku-4", "claude-4-haiku", "claude-4.5-haiku"},
+ rate: Rate{InputPer1M: 1.00, OutputPer1M: 5.00, CachedReadPer1M: 0.10, CacheCreationPer1M: 1.25},
+ },
+ {
+ match: []string{"claude-3-7-sonnet", "claude-3.7-sonnet"},
+ rate: Rate{InputPer1M: 3.00, OutputPer1M: 15.00, CachedReadPer1M: 0.30, CacheCreationPer1M: 3.75},
+ },
+ {
+ match: []string{"claude-3-5-haiku", "claude-3.5-haiku"},
+ rate: Rate{InputPer1M: 0.80, OutputPer1M: 4.00, CachedReadPer1M: 0.08, CacheCreationPer1M: 1.00},
+ },
+ {
+ match: []string{"claude-3-5-sonnet", "claude-3.5-sonnet"},
+ rate: Rate{InputPer1M: 3.00, OutputPer1M: 15.00, CachedReadPer1M: 0.30, CacheCreationPer1M: 3.75},
+ },
+ {
+ match: []string{"claude-3-haiku"},
+ rate: Rate{InputPer1M: 0.25, OutputPer1M: 1.25, CachedReadPer1M: 0.03, CacheCreationPer1M: 0.30},
+ },
+ {
+ match: []string{"claude-3-sonnet"},
+ rate: Rate{InputPer1M: 3.00, OutputPer1M: 15.00, CachedReadPer1M: 0.30, CacheCreationPer1M: 3.75},
+ },
+ {
+ match: []string{"claude-3-opus", "claude-3.0-opus"},
+ rate: Rate{InputPer1M: 15.00, OutputPer1M: 75.00, CachedReadPer1M: 1.50, CacheCreationPer1M: 18.75},
+ },
+ // --- OpenAI ----------------------------------------------------
+ // GPT-5.x ladder. Versions matter: 5.0 / 5.1 share $1.25/$10, 5.2 /
+ // 5.3 jump to $1.75/$14, 5.4 base sits at $2.50/$15 (the surprise
+ // price hike), 5.5 jumps again to $5/$30. Mini and nano variants
+ // price separately, so they go first.
+ {
+ match: []string{"gpt-5.5-pro", "gpt-5-5-pro"},
+ rate: Rate{InputPer1M: 30.00, OutputPer1M: 180.00},
+ },
+ {
+ match: []string{"gpt-5.5", "gpt-5-5"},
+ rate: Rate{InputPer1M: 5.00, OutputPer1M: 30.00, CachedReadPer1M: 0.50},
+ },
+ {
+ match: []string{"gpt-5.4-pro", "gpt-5-4-pro"},
+ rate: Rate{InputPer1M: 30.00, OutputPer1M: 180.00},
+ },
+ {
+ match: []string{"gpt-5.4-nano", "gpt-5-4-nano"},
+ rate: Rate{InputPer1M: 0.20, OutputPer1M: 1.25, CachedReadPer1M: 0.02},
+ },
+ {
+ match: []string{"gpt-5.4-mini", "gpt-5-4-mini"},
+ rate: Rate{InputPer1M: 0.75, OutputPer1M: 4.50, CachedReadPer1M: 0.075},
+ },
+ {
+ match: []string{"gpt-5.4", "gpt-5-4"},
+ rate: Rate{InputPer1M: 2.50, OutputPer1M: 15.00, CachedReadPer1M: 0.25},
+ },
+ {
+ match: []string{"gpt-5.3-codex", "codex-5.3", "gpt-5-3-codex"},
+ rate: Rate{InputPer1M: 1.75, OutputPer1M: 14.00, CachedReadPer1M: 0.175},
+ },
+ {
+ match: []string{"gpt-5.2-codex", "gpt-5-2-codex"},
+ rate: Rate{InputPer1M: 1.75, OutputPer1M: 14.00, CachedReadPer1M: 0.175},
+ },
+ {
+ match: []string{"gpt-5.2", "gpt-5-2"},
+ rate: Rate{InputPer1M: 1.75, OutputPer1M: 14.00, CachedReadPer1M: 0.175},
+ },
+ {
+ match: []string{"gpt-5.1-codex-max", "gpt-5-1-codex-max"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125},
+ },
+ {
+ match: []string{"gpt-5.1-codex-mini", "gpt-5-1-codex-mini"},
+ rate: Rate{InputPer1M: 0.25, OutputPer1M: 2.00, CachedReadPer1M: 0.025},
+ },
+ {
+ match: []string{"gpt-5.1-codex", "gpt-5-1-codex"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125},
+ },
+ {
+ match: []string{"gpt-5.1", "gpt-5-1"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125},
+ },
+ {
+ match: []string{"gpt-5-pro"},
+ rate: Rate{InputPer1M: 15.00, OutputPer1M: 120.00},
+ },
+ {
+ match: []string{"gpt-5-nano"},
+ rate: Rate{InputPer1M: 0.05, OutputPer1M: 0.40, CachedReadPer1M: 0.005},
+ },
+ {
+ match: []string{"gpt-5-mini"},
+ rate: Rate{InputPer1M: 0.25, OutputPer1M: 2.00, CachedReadPer1M: 0.025},
+ },
+ {
+ match: []string{"gpt-5-codex"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125},
+ },
+ {
+ match: []string{"gpt-5-fast"},
+ rate: Rate{InputPer1M: 2.50, OutputPer1M: 20.00, CachedReadPer1M: 0.25},
+ },
+ {
+ // Bare "gpt-5" or "gpt-5-..." (after the more-specific patterns
+ // above have already caught the named variants).
+ match: []string{"gpt-5"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125},
+ },
+ {
+ match: []string{"gpt-4o", "gpt-4-o"},
+ rate: Rate{InputPer1M: 2.50, OutputPer1M: 10.00, CachedReadPer1M: 1.25},
+ },
+ {
+ match: []string{"gpt-4-turbo", "gpt-4-1106", "gpt-4-0125"},
+ rate: Rate{InputPer1M: 10.00, OutputPer1M: 30.00},
+ },
+ {
+ match: []string{"o1-mini"},
+ rate: Rate{InputPer1M: 3.00, OutputPer1M: 12.00},
+ },
+ {
+ match: []string{"o1-preview", "o1-pro"},
+ rate: Rate{InputPer1M: 15.00, OutputPer1M: 60.00},
+ },
+ {
+ match: []string{"o3-mini"},
+ rate: Rate{InputPer1M: 1.10, OutputPer1M: 4.40},
+ },
+ {
+ match: []string{"o3"},
+ rate: Rate{InputPer1M: 2.00, OutputPer1M: 8.00},
+ },
+ {
+ match: []string{"o4-mini"},
+ rate: Rate{InputPer1M: 1.10, OutputPer1M: 4.40},
+ },
+ // --- Google Gemini ---------------------------------------------
+ {
+ match: []string{"gemini-3.1-pro", "gemini-3-1-pro"},
+ rate: Rate{InputPer1M: 2.00, OutputPer1M: 12.00},
+ },
+ {
+ match: []string{"gemini-3.1-flash-lite", "gemini-3-1-flash-lite"},
+ rate: Rate{InputPer1M: 0.25, OutputPer1M: 1.50},
+ },
+ {
+ match: []string{"gemini-3.5-flash", "gemini-3-5-flash"},
+ rate: Rate{InputPer1M: 1.50, OutputPer1M: 9.00},
+ },
+ {
+ match: []string{"gemini-3-pro-image-preview", "gemini-3-pro"},
+ rate: Rate{InputPer1M: 2.00, OutputPer1M: 12.00},
+ },
+ {
+ match: []string{"gemini-3-flash"},
+ rate: Rate{InputPer1M: 0.50, OutputPer1M: 3.00},
+ },
+ {
+ match: []string{"gemini-2.5-pro", "gemini-2-5-pro"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 10.00},
+ },
+ {
+ match: []string{"gemini-2.5-flash-lite", "gemini-2-5-flash-lite"},
+ rate: Rate{InputPer1M: 0.10, OutputPer1M: 0.40},
+ },
+ {
+ match: []string{"gemini-2.5-flash", "gemini-2-5-flash"},
+ rate: Rate{InputPer1M: 0.30, OutputPer1M: 2.50},
+ },
+ {
+ match: []string{"gemini-2.0-flash", "gemini-2-0-flash"},
+ rate: Rate{InputPer1M: 0.10, OutputPer1M: 0.40},
+ },
+ {
+ match: []string{"gemini-1.5-pro", "gemini-1-5-pro"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 5.00},
+ },
+ {
+ match: []string{"gemini-1.5-flash", "gemini-1-5-flash"},
+ rate: Rate{InputPer1M: 0.075, OutputPer1M: 0.30},
+ },
+ // --- xAI Grok --------------------------------------------------
+ // Grok 4.x ladder per Cursor + xAI docs. No explicit cache rates;
+ // xAI does not expose cached_tokens.
+ {
+ match: []string{"grok-4-20", "grok-4.20"},
+ rate: Rate{InputPer1M: 2.00, OutputPer1M: 6.00, CachedReadPer1M: 0.20},
+ },
+ {
+ match: []string{"grok-4-3", "grok-4.3"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 2.50, CachedReadPer1M: 0.20},
+ },
+ {
+ match: []string{"grok-build-0-1", "grok-build-0.1", "grok-build"},
+ rate: Rate{InputPer1M: 1.00, OutputPer1M: 2.00, CachedReadPer1M: 0.20},
+ },
+ // --- Cursor Composer ------------------------------------------
+ // Cursor's own models per https://cursor.com/docs/models-and-pricing
+ // (no separate cache write; cache reads are flat).
+ {
+ match: []string{"composer-2-5", "composer-2.5", "composer-2"},
+ rate: Rate{InputPer1M: 0.50, OutputPer1M: 2.50, CachedReadPer1M: 0.20},
+ },
+ {
+ match: []string{"composer-1-5", "composer-1.5"},
+ rate: Rate{InputPer1M: 3.50, OutputPer1M: 17.50, CachedReadPer1M: 0.35},
+ },
+ {
+ match: []string{"composer-1", "composer"},
+ rate: Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125},
+ },
+ // --- Moonshot Kimi --------------------------------------------
+ {
+ match: []string{"kimi-k2-5", "kimi-k2.5", "kimi-2-5"},
+ rate: Rate{InputPer1M: 0.60, OutputPer1M: 3.00, CachedReadPer1M: 0.10},
+ },
+ {
+ match: []string{"kimi-k2", "kimi-2"},
+ rate: Rate{InputPer1M: 0.60, OutputPer1M: 3.00, CachedReadPer1M: 0.10},
+ },
+}
diff --git a/cli/internal/coding/pricing/pricing_test.go b/cli/internal/coding/pricing/pricing_test.go
new file mode 100644
index 00000000..2c198d49
--- /dev/null
+++ b/cli/internal/coding/pricing/pricing_test.go
@@ -0,0 +1,202 @@
+package pricing
+
+import (
+ "math"
+ "testing"
+)
+
+func TestLookupAnthropic(t *testing.T) {
+ tests := []struct {
+ model string
+ want Rate
+ }{
+ // Sonnet 4.x / 3.5: $3/$15 across all minor revisions.
+ {"claude-sonnet-4-5-20251022", Rate{InputPer1M: 3.00, OutputPer1M: 15.00, CachedReadPer1M: 0.30, CacheCreationPer1M: 3.75}},
+ {"claude-3-5-sonnet-20241022", Rate{InputPer1M: 3.00, OutputPer1M: 15.00, CachedReadPer1M: 0.30, CacheCreationPer1M: 3.75}},
+ // Opus 4.5+ dropped to $5/$25 in 2025-10. Cursor's Cmd-K hook
+ // stamps `claude-opus-4-7-thinking-xhigh` so we exercise the
+ // versioned-with-suffix pattern explicitly: regressing this
+ // inflates dashboard cost ~3x (back to the legacy Opus rate).
+ {"claude-opus-4-8", Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25}},
+ {"claude-opus-4-7", Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25}},
+ {"claude-opus-4-7-thinking-xhigh", Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25}},
+ {"claude-opus-4-6", Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25}},
+ {"claude-opus-4-5", Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25}},
+ // Anthropic priority-tier "-fast" variants carry a 6x markup
+ // (and roughly 6x cache-write rate); Cursor exposes these.
+ {"claude-opus-4-8-fast", Rate{InputPer1M: 30.00, OutputPer1M: 150.00, CachedReadPer1M: 3.00, CacheCreationPer1M: 37.50}},
+ // Legacy Opus 4.0 / 4.1 are still on the original $15/$75 list.
+ {"claude-opus-4-0", Rate{InputPer1M: 15.00, OutputPer1M: 75.00, CachedReadPer1M: 1.50, CacheCreationPer1M: 18.75}},
+ {"claude-opus-4-1", Rate{InputPer1M: 15.00, OutputPer1M: 75.00, CachedReadPer1M: 1.50, CacheCreationPer1M: 18.75}},
+ // Haiku 4.x: $1/$5.
+ {"claude-haiku-4-5-20251001", Rate{InputPer1M: 1.00, OutputPer1M: 5.00, CachedReadPer1M: 0.10, CacheCreationPer1M: 1.25}},
+ // Bare "claude-opus-4" with no version falls into the modern
+ // bucket — we'd rather undercharge than 3x-overcharge a new SKU
+ // before the table catches up.
+ {"claude-opus-4", Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25}},
+ }
+ for _, tt := range tests {
+ got := Lookup(tt.model)
+ if got != tt.want {
+ t.Errorf("Lookup(%q) = %+v, want %+v", tt.model, got, tt.want)
+ }
+ }
+}
+
+func TestLookupOpenAI(t *testing.T) {
+ tests := []struct {
+ model string
+ want Rate
+ }{
+ // GPT-5 base: $1.25/$10. Cursor and Codex stamp this directly.
+ {"gpt-5", Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125}},
+ {"gpt-5-codex", Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125}},
+ {"gpt-5-mini", Rate{InputPer1M: 0.25, OutputPer1M: 2.00, CachedReadPer1M: 0.025}},
+ {"gpt-5-nano", Rate{InputPer1M: 0.05, OutputPer1M: 0.40, CachedReadPer1M: 0.005}},
+ {"gpt-5-fast", Rate{InputPer1M: 2.50, OutputPer1M: 20.00, CachedReadPer1M: 0.25}},
+ // GPT-5.1 codex variants.
+ {"gpt-5.1-codex-mini", Rate{InputPer1M: 0.25, OutputPer1M: 2.00, CachedReadPer1M: 0.025}},
+ {"gpt-5.1-codex-max", Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125}},
+ // GPT-5.4 jumped to $2.50/$15 — used by Codex CLI in our test data.
+ {"gpt-5.4", Rate{InputPer1M: 2.50, OutputPer1M: 15.00, CachedReadPer1M: 0.25}},
+ {"gpt-5.4-mini", Rate{InputPer1M: 0.75, OutputPer1M: 4.50, CachedReadPer1M: 0.075}},
+ // GPT-5.5 frontier tier.
+ {"gpt-5.5", Rate{InputPer1M: 5.00, OutputPer1M: 30.00, CachedReadPer1M: 0.50}},
+ // o-series — confirm o3 isn't being eaten by the gpt-5 family.
+ {"o3", Rate{InputPer1M: 2.00, OutputPer1M: 8.00}},
+ {"o4-mini", Rate{InputPer1M: 1.10, OutputPer1M: 4.40}},
+ }
+ for _, tt := range tests {
+ got := Lookup(tt.model)
+ if got != tt.want {
+ t.Errorf("Lookup(%q) = %+v, want %+v", tt.model, got, tt.want)
+ }
+ }
+}
+
+func TestLookupGoogle(t *testing.T) {
+ tests := []struct {
+ model string
+ want Rate
+ }{
+ {"gemini-2.5-pro", Rate{InputPer1M: 1.25, OutputPer1M: 10.00}},
+ {"gemini-2.5-flash", Rate{InputPer1M: 0.30, OutputPer1M: 2.50}},
+ {"gemini-2.5-flash-lite", Rate{InputPer1M: 0.10, OutputPer1M: 0.40}},
+ {"gemini-3-flash", Rate{InputPer1M: 0.50, OutputPer1M: 3.00}},
+ {"gemini-3-pro", Rate{InputPer1M: 2.00, OutputPer1M: 12.00}},
+ {"gemini-3.5-flash", Rate{InputPer1M: 1.50, OutputPer1M: 9.00}},
+ {"gemini-3.1-pro", Rate{InputPer1M: 2.00, OutputPer1M: 12.00}},
+ }
+ for _, tt := range tests {
+ got := Lookup(tt.model)
+ if got != tt.want {
+ t.Errorf("Lookup(%q) = %+v, want %+v", tt.model, got, tt.want)
+ }
+ }
+}
+
+func TestLookupXAIAndCursorAndMoonshot(t *testing.T) {
+ tests := []struct {
+ model string
+ want Rate
+ }{
+ // xAI Grok ladder.
+ {"grok-4-20", Rate{InputPer1M: 2.00, OutputPer1M: 6.00, CachedReadPer1M: 0.20}},
+ {"grok-4-3", Rate{InputPer1M: 1.25, OutputPer1M: 2.50, CachedReadPer1M: 0.20}},
+ {"grok-build-0-1", Rate{InputPer1M: 1.00, OutputPer1M: 2.00, CachedReadPer1M: 0.20}},
+ // Cursor Composer.
+ {"composer-2-5", Rate{InputPer1M: 0.50, OutputPer1M: 2.50, CachedReadPer1M: 0.20}},
+ {"composer-1-5", Rate{InputPer1M: 3.50, OutputPer1M: 17.50, CachedReadPer1M: 0.35}},
+ {"composer-1", Rate{InputPer1M: 1.25, OutputPer1M: 10.00, CachedReadPer1M: 0.125}},
+ // Moonshot.
+ {"kimi-k2-5", Rate{InputPer1M: 0.60, OutputPer1M: 3.00, CachedReadPer1M: 0.10}},
+ }
+ for _, tt := range tests {
+ got := Lookup(tt.model)
+ if got != tt.want {
+ t.Errorf("Lookup(%q) = %+v, want %+v", tt.model, got, tt.want)
+ }
+ }
+}
+
+func TestLookupUnknown(t *testing.T) {
+ got := Lookup("totally-made-up-model-9000")
+ if got.InputPer1M != 0 || got.OutputPer1M != 0 {
+ t.Errorf("expected zero rate for unknown, got %+v", got)
+ }
+}
+
+func TestCostBasic(t *testing.T) {
+ r := Rate{InputPer1M: 3.00, OutputPer1M: 15.00, CachedReadPer1M: 0.30, CacheCreationPer1M: 3.75}
+ got := r.Cost(10_000, 2_000, 0, 0)
+ want := 0.06 // 10k*3/1M + 2k*15/1M = 0.03 + 0.03
+ if math.Abs(got-want) > 1e-9 {
+ t.Errorf("Cost(10k,2k,0,0) = %v, want %v", got, want)
+ }
+}
+
+func TestCostWithCacheRead(t *testing.T) {
+ r := Rate{InputPer1M: 3.00, OutputPer1M: 15.00, CachedReadPer1M: 0.30, CacheCreationPer1M: 3.75}
+ // 8000 cache reads + 2000 fresh = 10000 input tokens; 2000 output;
+ // no cache creation.
+ got := r.Cost(10_000, 2_000, 8_000, 0)
+ // Fresh: 2000 * 3/1M = 0.006
+ // Cache read: 8000 * 0.30/1M = 0.0024
+ // Output: 2000 * 15/1M = 0.030
+ want := 0.0384
+ if math.Abs(got-want) > 1e-9 {
+ t.Errorf("cache-read cost = %v, want %v", got, want)
+ }
+}
+
+// TestCostCacheCreationPremium is the regression net for the
+// Claude Code under-billing bug: before the cache_creation split,
+// cache_creation tokens were billed at the cache_read rate (~10% of
+// input) instead of the cache_write rate (~125% of input), a ~12x
+// gap on the cache-write portion. This test pins the new behaviour.
+func TestCostCacheCreationPremium(t *testing.T) {
+ r := Rate{InputPer1M: 5.00, OutputPer1M: 25.00, CachedReadPer1M: 0.50, CacheCreationPer1M: 6.25}
+ // 2000 fresh + 6000 cache-read + 2000 cache-create = 10000 input;
+ // 2000 output. This mirrors a realistic Claude Opus 4.x turn.
+ got := r.Cost(10_000, 2_000, 6_000, 2_000)
+ // Fresh: 2000 * 5/1M = 0.010
+ // Cache read: 6000 * 0.50/1M = 0.003
+ // Cache create: 2000 * 6.25/1M = 0.0125
+ // Output: 2000 * 25/1M = 0.050
+ // Total = 0.0755
+ want := 0.0755
+ if math.Abs(got-want) > 1e-9 {
+ t.Errorf("cache-creation cost = %v, want %v", got, want)
+ }
+
+ // Bundling the cache_creation tokens under cache_read (the pre-fix
+ // behaviour) would have yielded a far smaller bill — verify the
+ // new path is strictly higher to guard against silent regression.
+ bundledUnderRead := r.Cost(10_000, 2_000, 8_000, 0)
+ if got <= bundledUnderRead {
+ t.Errorf("cache_creation premium must be billed: split=%v, bundled-as-read=%v", got, bundledUnderRead)
+ }
+}
+
+// TestCostCacheCreationFallback documents the safety fallback: when
+// a Rate entry forgets to set CacheCreationPer1M but the call has
+// cache_creation tokens, we fall back to InputPer1M instead of $0.
+// This guarantees missing-rate bugs under-bill by a small margin
+// rather than silently dropping cache-write tokens to free.
+func TestCostCacheCreationFallback(t *testing.T) {
+ r := Rate{InputPer1M: 4.00, OutputPer1M: 16.00, CachedReadPer1M: 0.40 /* no CacheCreationPer1M */}
+ // 0 fresh + 0 cache_read + 1000 cache_creation; 0 output.
+ got := r.Cost(1_000, 0, 0, 1_000)
+ // Fallback bills cache_creation at InputPer1M: 1000 * 4/1M = 0.004
+ want := 0.004
+ if math.Abs(got-want) > 1e-9 {
+ t.Errorf("cache_creation fallback cost = %v, want %v", got, want)
+ }
+}
+
+func TestCostZeroRate(t *testing.T) {
+ r := Rate{}
+ if got := r.Cost(1_000, 1_000, 0, 0); got != 0 {
+ t.Errorf("zero rate must return 0, got %v", got)
+ }
+}
diff --git a/cli/internal/coding/pricing/tokens.go b/cli/internal/coding/pricing/tokens.go
new file mode 100644
index 00000000..20180193
--- /dev/null
+++ b/cli/internal/coding/pricing/tokens.go
@@ -0,0 +1,40 @@
+package pricing
+
+import "strings"
+
+// EstimateTokens returns an approximate token count for a UTF-8 string
+// using the canonical "4 chars ≈ 1 token" heuristic, with a whitespace-
+// aware floor (so we never under-bill multi-word prompts).
+//
+// This is a fallback for vendors that don't expose token counts on
+// their hooks (Cursor's beforeSubmitPrompt / afterAgentResponse give us
+// only the text). When the vendor does report usage (Claude Code's
+// transcript JSONL, Codex rollout JSONL), prefer that authoritative
+// number — this estimator is intentionally conservative so we never
+// silently inflate cost.
+//
+// Heuristic chosen to match what Anthropic's tokenizer roughly produces
+// on English/code prompts (their actual ratio runs 3.5–4.5 chars/tok
+// depending on content; we land at the middle).
+func EstimateTokens(text string) int64 {
+ if text == "" {
+ return 0
+ }
+ // Char-based estimate dominates for code-heavy prompts.
+ chars := int64(len(text))
+ charEstimate := chars / 4
+ if chars%4 != 0 {
+ charEstimate++
+ }
+
+ // Word-based floor for natural-language prompts where chars/4
+ // under-counts (lots of short words = more tokens than the char
+ // ratio implies).
+ words := int64(len(strings.Fields(text)))
+ wordFloor := (words * 4) / 3 // ~0.75 word/token
+
+ if wordFloor > charEstimate {
+ return wordFloor
+ }
+ return charEstimate
+}
diff --git a/cli/internal/coding/pricing/tokens_test.go b/cli/internal/coding/pricing/tokens_test.go
new file mode 100644
index 00000000..25dd19f6
--- /dev/null
+++ b/cli/internal/coding/pricing/tokens_test.go
@@ -0,0 +1,26 @@
+package pricing
+
+import "testing"
+
+func TestEstimateTokensEmpty(t *testing.T) {
+ if got := EstimateTokens(""); got != 0 {
+ t.Errorf("expected 0 for empty, got %d", got)
+ }
+}
+
+func TestEstimateTokensShort(t *testing.T) {
+ got := EstimateTokens("hello world")
+ if got <= 0 {
+ t.Errorf("expected >0, got %d", got)
+ }
+}
+
+func TestEstimateTokensWordFloor(t *testing.T) {
+ // "a b c d e f g h" = 8 single-char words, 15 chars
+ // charEstimate = 4, wordFloor = 8*4/3 = 10
+ // → returns 10 (word floor wins for short word-dense text)
+ got := EstimateTokens("a b c d e f g h")
+ if got < 10 {
+ t.Errorf("expected word floor to win (>=10), got %d", got)
+ }
+}
diff --git a/cli/internal/coding/sessionstate/flock_unix.go b/cli/internal/coding/sessionstate/flock_unix.go
new file mode 100644
index 00000000..86cc7db0
--- /dev/null
+++ b/cli/internal/coding/sessionstate/flock_unix.go
@@ -0,0 +1,33 @@
+//go:build darwin || linux || freebsd || netbsd || openbsd
+
+package sessionstate
+
+import (
+ "os"
+ "path/filepath"
+ "syscall"
+)
+
+// withFileLock — Unix implementation. See the godoc comment in
+// sessionstate.go for the contract. Uses BSD flock so the lock is
+// advisory and process-scoped; sufficient for the openlit hook
+// pattern (one hook subprocess per agent event, never overlapping
+// inside the same process).
+func withFileLock(lockPath string, fn func()) {
+ if err := os.MkdirAll(filepath.Dir(lockPath), 0o700); err != nil {
+ fn()
+ return
+ }
+ f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ fn()
+ return
+ }
+ defer f.Close()
+ if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
+ fn()
+ return
+ }
+ defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
+ fn()
+}
diff --git a/cli/internal/coding/sessionstate/flock_windows.go b/cli/internal/coding/sessionstate/flock_windows.go
new file mode 100644
index 00000000..0e78b451
--- /dev/null
+++ b/cli/internal/coding/sessionstate/flock_windows.go
@@ -0,0 +1,47 @@
+//go:build windows
+
+package sessionstate
+
+import (
+ "os"
+ "path/filepath"
+
+ "golang.org/x/sys/windows"
+)
+
+// withFileLock — Windows implementation. See the godoc comment in
+// sessionstate.go for the contract. Uses LockFileEx with LOCKFILE_EXCLUSIVE_LOCK
+// (no LOCKFILE_FAIL_IMMEDIATELY) so the call blocks until the lock is acquired,
+// matching the Unix flock behaviour. The lock is process-scoped and released
+// either explicitly via UnlockFileEx or implicitly when the handle is closed —
+// either way, a crashed hook cannot orphan the lock.
+//
+// On any setup failure (mkdir, open, lock acquisition) we fall back to running
+// fn unlocked rather than dropping the event entirely: telemetry must never
+// fail closed on an OS-level hiccup. The worst case is a single last-write-wins
+// collision on the session-state file, which the in-process diskMu still
+// guards against within a single process.
+func withFileLock(lockPath string, fn func()) {
+ if err := os.MkdirAll(filepath.Dir(lockPath), 0o700); err != nil {
+ fn()
+ return
+ }
+ f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ fn()
+ return
+ }
+ defer f.Close()
+
+ // LockFileEx locks a byte range; pass a max range so we cover the
+ // whole (currently-empty) lock file regardless of any future writes.
+ // An overlapped structure with zeroed offsets locks from byte 0.
+ var ol windows.Overlapped
+ const exclusive = windows.LOCKFILE_EXCLUSIVE_LOCK
+ if err := windows.LockFileEx(windows.Handle(f.Fd()), exclusive, 0, 0xFFFFFFFF, 0xFFFFFFFF, &ol); err != nil {
+ fn()
+ return
+ }
+ defer windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 0xFFFFFFFF, 0xFFFFFFFF, &ol)
+ fn()
+}
diff --git a/cli/internal/coding/sessionstate/sessionstate.go b/cli/internal/coding/sessionstate/sessionstate.go
new file mode 100644
index 00000000..b55652b0
--- /dev/null
+++ b/cli/internal/coding/sessionstate/sessionstate.go
@@ -0,0 +1,604 @@
+// Package sessionstate persists tiny per-session facts that the CLI
+// needs to remember across hook invocations.
+//
+// Each hook invocation is a fresh process, so any state the host plugin
+// doesn't replay on every event has to be cached on disk. We use this
+// for two things today:
+//
+// 1. **User identity** (Cursor's `user_email`, etc.) — vendors only
+// emit it on a subset of events, so we cache it after the first
+// event and replay it as a resource attribute on every subsequent
+// hook invocation in the same session.
+// 2. **Last-seen mode + model** — Cursor's composer_mode (agent / ask
+// / plan) and request model can change mid-session. We cache the
+// most recent value and let the per-vendor adapter compare it
+// against the new payload to emit a `coding_agent.permission_mode.changed`
+// event when the user toggles modes.
+//
+// The cache lives under $XDG_CACHE_HOME/openlit/sessions/<sid>.json.
+// Files are bounded in size (a few hundred bytes each), are written
+// 0600, and are best-effort: a corrupt or missing file falls through to
+// the empty state and the hook proceeds without it.
+package sessionstate
+
+import (
+ "encoding/json"
+ "math/rand"
+ "os"
+ "path/filepath"
+ "regexp"
+ "sync"
+ "time"
+)
+
+// gcMaxAge is the on-disk retention for a session cache entry.
+// Entries older than this are reaped by GC() on a probabilistic
+// schedule. Bumped well above any plausible chat thread length so
+// resuming an idle conversation still finds its cached identity.
+const gcMaxAge = 7 * 24 * time.Hour
+
+// gcEvery controls the GC sampling probability. We run GC on roughly
+// 1 in N hook invocations rather than every call (most hooks run in
+// <50 ms; an unconditional readdir per hook would noticeably slow the
+// hot path on machines with thousands of session files).
+const gcEvery = 1000
+
+// State holds the per-session facts we currently track. Add fields
+// here when a vendor adds another sticky attribute we want to compare
+// against on later hook events.
+type State struct {
+ // User is the identity to stamp on resource attrs when the
+ // vendor's payload doesn't carry one.
+ User string `json:"user,omitempty"`
+
+ // PermissionMode is Cursor's composer_mode / Claude Code's
+ // permission mode. Values: "agent" | "ask" | "plan" |
+ // "acceptEdits" | "bypassPermissions" | "default" | "auto".
+ PermissionMode string `json:"permission_mode,omitempty"`
+
+ // Model is the most recently-seen model id (e.g.
+ // "claude-opus-4-7-thinking-xhigh"). Cursor reports this on
+ // every prompt-bearing event; tracking it lets us emit a
+ // model-changed event mid-session.
+ Model string `json:"model,omitempty"`
+
+ // CWD is the working folder the agent runs in for this session.
+ // Cached so spans emitted by hook events that lack a cwd in
+ // their payload (e.g. afterAgentResponse / stop) still carry the
+ // session's working folder as a resource attribute.
+ CWD string `json:"cwd,omitempty"`
+
+ // RepoURL / Branch are the VCS snapshot taken at session start.
+ // Re-snapshotting on every hook event would mean a `git remote
+ // -v` + `git rev-parse` per event; caching the first snapshot is
+ // fine because branch changes mid-session are rare and the next
+ // cold-start hook event re-runs git anyway.
+ RepoURL string `json:"repo_url,omitempty"`
+ Branch string `json:"branch,omitempty"`
+
+ // ConversationID is Cursor's `conversation_id` (or equivalent on
+ // other vendors). Cached separately from SessionID because they
+ // may differ when a subagent is running: the subagent's own
+ // session_id is fresh but it inherits the parent's
+ // conversation_id, which is what we want to roll up in the UI.
+ ConversationID string `json:"conversation_id,omitempty"`
+
+ // ParentConversationID points at the spawning agent's chat
+ // thread, when this session is a subagent of another. Stamped
+ // from Cursor's `parent_conversation_id` field — present on
+ // subagentStart and (we hope) on subagent's own hook events.
+ // The UI uses this to fold subagent rows under their parent
+ // chat instead of listing them as standalone sessions.
+ ParentConversationID string `json:"parent_conversation_id,omitempty"`
+
+ // IsBackgroundAgent is true when Cursor's payload flags the
+ // session as a background / parallel-worker agent. UI hides
+ // these from the default Sessions list and shows them inside
+ // the parent chat's trace detail instead.
+ IsBackgroundAgent bool `json:"is_background_agent,omitempty"`
+
+ // SessionRolledUp counters that Phase C's minimal mode emits on
+ // sessionEnd in lieu of per-event spans. Always safe to populate;
+ // only consumed when the active capture mode is "minimal".
+ ToolCallCount int `json:"tool_call_count,omitempty"`
+ SubagentCount int `json:"subagent_count,omitempty"`
+ InputTokens int64 `json:"input_tokens,omitempty"`
+ OutputTokens int64 `json:"output_tokens,omitempty"`
+ CostUSD float64 `json:"cost_usd,omitempty"`
+
+ // Per-session code-change rollups accumulated across hook
+ // invocations and stamped on the session-root span at
+ // SessionEnd. All four line totals are absolute (not deltas).
+ // Adapters bump these via the shared bumpCounters helper
+ // regardless of content-capture mode — line counts are not
+ // considered user content and are always safe to record.
+ LinesAdded int `json:"lines_added,omitempty"`
+ LinesRemoved int `json:"lines_removed,omitempty"`
+ LinesAccepted int `json:"lines_accepted,omitempty"`
+ LinesRejected int `json:"lines_rejected,omitempty"`
+ EditAcceptCount int `json:"edit_accept_count,omitempty"`
+ EditRejectCount int `json:"edit_reject_count,omitempty"`
+ CommitCount int `json:"commit_count,omitempty"`
+ PRCount int `json:"pr_count,omitempty"`
+
+ // PendingEdits is the rejection-heuristic backing store for
+ // vendors that emit a Pre+Post pair around their edit tool
+ // (Claude Code's PreToolUse / PostToolUse for Edit / Write /
+ // MultiEdit). Keyed by the vendor's tool-use id, value is the
+ // proposed change we'd attribute as rejected if the Post never
+ // fires for this turn. UserPromptSubmit / SessionEnd drain
+ // leftover entries as rejections; PostToolUse resolves them as
+ // accepts and removes the entry. Bounded to ~32 entries per
+ // session so a runaway agent can't grow the cache unbounded.
+ PendingEdits map[string]*PendingEdit `json:"pending_edits,omitempty"`
+
+ // TerminalType is the resolved IDE/terminal hosting the agent
+ // (e.g. `vscode`, `cursor`, `iterm`). Sourced from Claude Code's
+ // transcript `entrypoint` (most reliable) or env / process-tree
+ // detection (fallback). Cached so the session-root span and every
+ // follow-up span agree on the value.
+ TerminalType string `json:"terminal_type,omitempty"`
+
+ // TranscriptPath is the absolute path to the vendor's transcript
+ // JSONL (Claude Code's `transcript_path`). Cached so non-lifecycle
+ // hook events (Stop / PostToolUse) can resume reading without the
+ // payload re-shipping it.
+ TranscriptPath string `json:"transcript_path,omitempty"`
+
+ // TranscriptOffset is the byte position the transcript reader
+ // last advanced to. Subsequent hook events resume reading from
+ // here; only new assistant turns produce new LLM-turn spans.
+ TranscriptOffset int64 `json:"transcript_offset,omitempty"`
+
+ // EmittedAssistantTurnIDs records assistant `requestId`s we've
+ // already emitted as LLM-turn spans. Defensive de-dup so a
+ // retried hook event or a transcript rewrite (Claude Code's
+ // streaming fragments) doesn't double-count tokens or chat
+ // content. Bounded to the most recent ~256 ids.
+ EmittedAssistantTurnIDs []string `json:"emitted_assistant_turn_ids,omitempty"`
+
+ // CodexTurns holds per-turn fragments for the Codex adapter,
+ // keyed by Codex's `turn_id`. Codex's hook protocol scopes
+ // every event to a turn (UserPromptSubmit, PreToolUse,
+ // PostToolUse, Stop all carry `turn_id`), and only `Stop`
+ // gives us the assistant's final text + token totals. Adapters
+ // accumulate the prompt and per-tool records on intermediate
+ // events and drain the fragment into one `coding_agent.llm.turn`
+ // span on Stop. Bounded to the most recent ~16 turn fragments
+ // so a long session doesn't grow this map unbounded.
+ CodexTurns map[string]*CodexTurnFragment `json:"codex_turns,omitempty"`
+
+ // CodexSubagent caches the parent-session linkage we extracted
+ // from Codex's transcript `session_meta` block at SessionStart.
+ // Stamped on every subsequent span this session emits so the UI
+ // can fold subagent runs under their spawning chat.
+ CodexSubagent *CodexSubagentLink `json:"codex_subagent,omitempty"`
+
+ // ActiveTaskToolUseID is the `tool_use_id` of the most recent
+ // Claude Code Task tool invocation. Claude Code's subagents don't
+ // fire intermediate hooks — only PreToolUse(Task) at spawn time
+ // and SubagentStop at completion. Caching the spawning tool-use
+ // id here lets us echo it onto the SubagentStop span as
+ // `gen_ai.tool.call.id`, which the chat view uses to group the
+ // Task tool call + subagent block into one collapsible item.
+ // Cleared on SubagentStop.
+ ActiveTaskToolUseID string `json:"active_task_tool_use_id,omitempty"`
+
+ // SessionStartedAt is the wall-clock at which we first saw a
+ // `SessionStart` (or equivalent) lifecycle event for this
+ // (sessionID, vendor) pair. Cached so SessionEnd / sessionEnd can
+ // compute a real duration without depending on the vendor to
+ // re-ship the start time. Previously Claude Code rolled this in
+ // as `StartedAt = time.Now()` at *both* events, producing ~0ms
+ // session durations across the board.
+ SessionStartedAt time.Time `json:"session_started_at,omitempty"`
+
+ // LastSessionRootEmitAt is the wall-clock of the most recent
+ // `coding_agent.session` span emission. Used by Codex (which has
+ // no SessionEnd hook and would otherwise re-emit the session-
+ // root span on EVERY Stop event) to throttle re-emits to once
+ // every ~60s. Deterministic SpanIDs ensure all re-emits collapse
+ // onto a single `otel_traces` row in ClickHouse, but throttling
+ // still saves the OTLP serialise + send cost on long sessions
+ // with dozens of turns.
+ LastSessionRootEmitAt time.Time `json:"last_session_root_emit_at,omitempty"`
+}
+
+// CodexTurnFragment is the per-turn state Codex's adapter accumulates
+// between intermediate hook events (UserPromptSubmit, PostToolUse) and
+// the closing Stop event. One Stop emits one `coding_agent.llm.turn`
+// span built from this fragment.
+type CodexTurnFragment struct {
+ // TurnID is Codex's `turn_id`. Cached so list iteration keeps a
+ // stable key even when callers don't pass the id through.
+ TurnID string `json:"turn_id,omitempty"`
+ // Prompt is the user's verbatim prompt (UserPromptSubmit). Only
+ // populated under `full` capture mode.
+ Prompt string `json:"prompt,omitempty"`
+ // LastAssistantMessage is Codex's plain-text assistant reply on
+ // Stop. Only populated under `full` capture mode.
+ LastAssistantMessage string `json:"last_assistant_message,omitempty"`
+ // Tools accumulates one entry per PostToolUse event so the
+ // closing `coding_agent.llm.turn` can render `tool_call_response`
+ // parts. Body fields (Input / Response) only land under `full`.
+ Tools []CodexToolRecord `json:"tools,omitempty"`
+ // StartedAt is when we first saw this turn (UserPromptSubmit or
+ // SessionStart fallback). Used as the LLM-turn span StartedAt
+ // on Stop so dashboards get a real duration.
+ StartedAt time.Time `json:"started_at,omitempty"`
+ // Model + Source come from the SessionStart/UserPromptSubmit
+ // payload. Cached because the Stop event itself often omits
+ // them on subagent invocations.
+ Model string `json:"model,omitempty"`
+ Source string `json:"source,omitempty"`
+ // StopHookActive is Codex's signal that the hook fired
+ // pre-emptively (a previous turn hadn't fully stopped). Surfaced
+ // as a tag so dashboards can quarantine these rows.
+ StopHookActive bool `json:"stop_hook_active,omitempty"`
+}
+
+// CodexToolRecord is one tool invocation observed inside a Codex turn,
+// accumulated by `PostToolUse`. The fields mirror Codex's hook payload
+// (tool_name, tool_use_id, tool_input, tool_response, tool_duration_ms,
+// status, error) plus the resolved decision (Status). Body fields are
+// gated on `full` content capture by the adapter before we ever write
+// here so the on-disk cache cannot carry tool args/results in
+// metadata_only mode.
+type CodexToolRecord struct {
+ ToolName string `json:"tool_name,omitempty"`
+ ToolUseID string `json:"tool_use_id,omitempty"`
+ ToolInput string `json:"tool_input,omitempty"`
+ ToolResponse string `json:"tool_response,omitempty"`
+ Status string `json:"status,omitempty"`
+ ErrorMessage string `json:"error_message,omitempty"`
+ Cwd string `json:"cwd,omitempty"`
+ DurationMs int64 `json:"duration_ms,omitempty"`
+ CompletedAt string `json:"completed_at,omitempty"`
+}
+
+// CodexSubagentLink captures Codex's parent → child thread relationship
+// when the current session is a subagent of another. Sourced from the
+// transcript's `session_meta` record at SessionStart, then stamped on
+// every span via resource attributes.
+type CodexSubagentLink struct {
+ ParentSessionID string `json:"parent_session_id,omitempty"`
+ AgentRole string `json:"agent_role,omitempty"`
+ AgentNickname string `json:"agent_nickname,omitempty"`
+ AgentDepth int `json:"agent_depth,omitempty"`
+}
+
+// PendingEdit is one row in the rejection-heuristic backing store —
+// see `State.PendingEdits`. Adapters stash a PendingEdit on the
+// vendor's pre-edit hook (Claude Code's PreToolUse) and either
+// resolve+remove it on the matching post-edit hook (PostToolUse,
+// accept path) or drain it as rejected when the next UserPromptSubmit
+// arrives without a paired PostToolUse (reject path).
+//
+// LinesAdded / LinesRemoved are inferred from the proposed change at
+// pre-time (Claude Code's `new_string` / `old_string` for Edit;
+// `content` for Write). Counts inevitably under-count when the
+// vendor's tool ultimately wrote a different range, but they're
+// directionally honest and the dominant pattern is "pre and post
+// agree on the change".
+type PendingEdit struct {
+ ToolUseID string `json:"tool_use_id,omitempty"`
+ ToolName string `json:"tool_name,omitempty"`
+ FilePath string `json:"file_path,omitempty"`
+ LinesAdded int `json:"lines_added,omitempty"`
+ LinesRemoved int `json:"lines_removed,omitempty"`
+ Language string `json:"language,omitempty"`
+ At int64 `json:"at,omitempty"` // unix epoch ms
+}
+
+var safeFilenameRe = regexp.MustCompile(`[^A-Za-z0-9_.-]`)
+
+// path returns the cache file for `sessionID` and `vendor`.
+//
+// We deliberately partition the cache by vendor as well as session id
+// because Claude Code launched inside Cursor inherits Cursor's
+// CURSOR_SESSION_ID (and similar env-leakage cases on Codex).
+// Without per-vendor partitioning, the first hook to write the cache
+// poisons every other vendor's reads — symptoms include:
+//
+// - Claude Code spans inheriting Cursor's `composer_mode` value
+// ("agent" / "plan" / "ask"), even though Claude Code never reports
+// those values.
+// - Identical `terminal.type` on both vendors' spans.
+// - User identity flapping between OAuth email (Claude Code) and OS
+// username (Cursor's fallback) within a single chat.
+//
+// Returns "" when the session id is empty, the vendor is empty, or
+// the cache root can't be derived. Every adapter passes its canonical
+// vendor; an empty vendor here is a programming error and we refuse
+// to write into a shared file that would re-introduce the cross-vendor
+// poisoning the partitioning was designed to prevent.
+func path(sessionID, vendor string) string {
+ if sessionID == "" || vendor == "" {
+ return ""
+ }
+ root, err := os.UserCacheDir()
+ if err != nil || root == "" {
+ return ""
+ }
+ safeSID := safeFilenameRe.ReplaceAllString(sessionID, "_")
+ safeVendor := safeFilenameRe.ReplaceAllString(vendor, "_")
+ if safeSID == "" || safeVendor == "" {
+ return ""
+ }
+ return filepath.Join(root, "openlit", "sessions", safeSID+"__"+safeVendor+".json")
+}
+
+// diskMu serialises Load / Save inside a single process. Cross-process
+// safety is handled by per-file flock acquired inside withFileLock.
+var diskMu sync.Mutex
+
+// withFileLock acquires an exclusive advisory lock on the file at
+// `lockPath` and runs fn while holding it. The lock file is created
+// next to the cache entry (suffixed `.lock`) so concurrent hook
+// processes for the same session serialise on the same descriptor.
+//
+// On Unix, the real implementation in `flock_unix.go` uses
+// `syscall.Flock` for true cross-process serialisation. On Windows
+// the stub in `flock_windows.go` falls through to the in-process
+// `diskMu` mutex — that's correct for the common single-host case
+// and avoids the cgo dance of LockFileEx for what is, today, a Unix-
+// first dev tool. Both implementations always invoke `fn` exactly
+// once, regardless of whether the lock attempt succeeded — the
+// underlying contract is "best-effort serialisation; never block
+// the hook".
+//
+// The platform-specific definitions live in the build-tagged sibling
+// files in this package.
+
+// Load returns the cached state for the (sessionID, vendor) pair.
+// Always returns a non-nil State even when the cache file is missing
+// or unreadable — callers fall through to the empty state and emit
+// fresh. See `path` for the rationale on per-vendor partitioning.
+func Load(sessionID, vendor string) *State {
+ p := path(sessionID, vendor)
+ if p == "" {
+ return &State{}
+ }
+ maybeGC()
+ out := &State{}
+ withFileLock(p+".lock", func() {
+ diskMu.Lock()
+ defer diskMu.Unlock()
+ b, err := os.ReadFile(p)
+ if err != nil {
+ return
+ }
+ var s State
+ if err := json.Unmarshal(b, &s); err != nil {
+ return
+ }
+ // Touch mtime so frequently-resumed sessions don't get GC'd
+ // out from under a long-running chat.
+ _ = os.Chtimes(p, time.Now(), time.Now())
+ out = &s
+ })
+ return out
+}
+
+// pendingEditCap bounds how many in-flight pending edits a single
+// session can hold. Vendors that emit Pre+Post pairs (Claude Code's
+// Edit / Write / MultiEdit) typically have <=1 in-flight at a time;
+// the cap exists to defend against the pathological case where a hung
+// session never drains its pre-edits and the cache grows unbounded.
+const pendingEditCap = 32
+
+// AddPendingEdit stashes the proposed edit body under the vendor's
+// tool-use id. The function is best-effort and silently drops new
+// entries when the cap is hit so the cache cannot grow unbounded.
+// Counts as a no-op when the session id or tool-use id is empty.
+func AddPendingEdit(sessionID, vendor, toolUseID string, edit *PendingEdit) {
+ if sessionID == "" || vendor == "" || toolUseID == "" || edit == nil {
+ return
+ }
+ st := Load(sessionID, vendor)
+ if st == nil {
+ st = &State{}
+ }
+ if st.PendingEdits == nil {
+ st.PendingEdits = make(map[string]*PendingEdit, 4)
+ }
+ if _, exists := st.PendingEdits[toolUseID]; !exists && len(st.PendingEdits) >= pendingEditCap {
+ // Drop oldest by simple scan; the cap is only hit in the
+ // pathological case where Post never fires, so a linear
+ // scan is fine.
+ var oldestKey string
+ var oldestAt int64
+ for k, v := range st.PendingEdits {
+ if v == nil {
+ continue
+ }
+ if oldestKey == "" || v.At < oldestAt {
+ oldestKey = k
+ oldestAt = v.At
+ }
+ }
+ if oldestKey != "" {
+ delete(st.PendingEdits, oldestKey)
+ }
+ }
+ edit.ToolUseID = toolUseID
+ if edit.At == 0 {
+ edit.At = time.Now().UnixMilli()
+ }
+ st.PendingEdits[toolUseID] = edit
+ Save(sessionID, vendor, st)
+}
+
+// TakePendingEdit removes and returns the pending edit by tool-use id.
+// Returns nil when no entry exists. The caller is responsible for
+// emitting the resolved EditDecision span / bumping counters; this
+// function only owns the cache write.
+func TakePendingEdit(sessionID, vendor, toolUseID string) *PendingEdit {
+ if sessionID == "" || vendor == "" || toolUseID == "" {
+ return nil
+ }
+ st := Load(sessionID, vendor)
+ if st == nil || st.PendingEdits == nil {
+ return nil
+ }
+ got, ok := st.PendingEdits[toolUseID]
+ if !ok {
+ return nil
+ }
+ delete(st.PendingEdits, toolUseID)
+ Save(sessionID, vendor, st)
+ return got
+}
+
+// DrainPendingEdits removes and returns all currently-pending edits.
+// Called on UserPromptSubmit / SessionEnd to attribute lingering
+// Pre-without-Post entries as user rejections.
+func DrainPendingEdits(sessionID, vendor string) []*PendingEdit {
+ if sessionID == "" || vendor == "" {
+ return nil
+ }
+ st := Load(sessionID, vendor)
+ if st == nil || len(st.PendingEdits) == 0 {
+ return nil
+ }
+ out := make([]*PendingEdit, 0, len(st.PendingEdits))
+ for _, v := range st.PendingEdits {
+ if v != nil {
+ out = append(out, v)
+ }
+ }
+ st.PendingEdits = nil
+ Save(sessionID, vendor, st)
+ return out
+}
+
+// BumpCodeCounters accumulates code-change totals onto the cached
+// session state. Adapters call this from edit-tool hook handlers;
+// the otlp emitter reads the totals on sessionEnd and stamps them on
+// the session-root span. The function is a no-op when no deltas are
+// supplied so callers don't need to gate the call site.
+func BumpCodeCounters(sessionID, vendor string, linesAdded, linesRemoved, linesAccepted, linesRejected, editAccepts, editRejects int) {
+ if sessionID == "" || vendor == "" {
+ return
+ }
+ if linesAdded == 0 && linesRemoved == 0 && linesAccepted == 0 && linesRejected == 0 && editAccepts == 0 && editRejects == 0 {
+ return
+ }
+ st := Load(sessionID, vendor)
+ if st == nil {
+ st = &State{}
+ }
+ st.LinesAdded += linesAdded
+ st.LinesRemoved += linesRemoved
+ st.LinesAccepted += linesAccepted
+ st.LinesRejected += linesRejected
+ st.EditAcceptCount += editAccepts
+ st.EditRejectCount += editRejects
+ Save(sessionID, vendor, st)
+}
+
+// BumpCommitCount bumps the per-session commit counter. Called once
+// per agent-attributed `git commit` invocation detected by the
+// vendor adapter.
+func BumpCommitCount(sessionID, vendor string) {
+ if sessionID == "" || vendor == "" {
+ return
+ }
+ st := Load(sessionID, vendor)
+ if st == nil {
+ st = &State{}
+ }
+ st.CommitCount++
+ Save(sessionID, vendor, st)
+}
+
+// BumpPRCount bumps the per-session pull-request counter. Called once
+// per agent-attributed PR / MR creation detected by the vendor
+// adapter.
+func BumpPRCount(sessionID, vendor string) {
+ if sessionID == "" || vendor == "" {
+ return
+ }
+ st := Load(sessionID, vendor)
+ if st == nil {
+ st = &State{}
+ }
+ st.PRCount++
+ Save(sessionID, vendor, st)
+}
+
+// Save writes `s` to the cache file for the (sessionID, vendor) pair.
+// Best-effort — errors are silent because the hook contract is "never
+// fail on telemetry". Uses temp-file + rename to avoid leaving
+// half-written JSON behind if another hook process raced us or the OS
+// killed us mid-write.
+func Save(sessionID, vendor string, s *State) {
+ p := path(sessionID, vendor)
+ if p == "" || s == nil {
+ return
+ }
+ withFileLock(p+".lock", func() {
+ diskMu.Lock()
+ defer diskMu.Unlock()
+ if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
+ return
+ }
+ b, err := json.Marshal(s)
+ if err != nil {
+ return
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(p), filepath.Base(p)+".*")
+ if err != nil {
+ return
+ }
+ tmpPath := tmp.Name()
+ _, werr := tmp.Write(b)
+ cerr := tmp.Close()
+ if werr != nil || cerr != nil {
+ _ = os.Remove(tmpPath)
+ return
+ }
+ _ = os.Chmod(tmpPath, 0o600)
+ if err := os.Rename(tmpPath, p); err != nil {
+ _ = os.Remove(tmpPath)
+ }
+ })
+}
+
+// maybeGC runs the on-disk reaper on roughly 1 / gcEvery Load calls so
+// the hot path stays cheap. Tests can stub this by zeroing gcEvery.
+func maybeGC() {
+ if gcEvery <= 0 || rand.Intn(gcEvery) != 0 {
+ return
+ }
+ go GC(gcMaxAge)
+}
+
+// GC walks the on-disk cache and removes files (and their .lock
+// siblings) whose mtime is older than `maxAge`. Best-effort — errors
+// are silent so a partial sweep can't fail the hook process. Exported
+// so tests + an optional CLI subcommand can drive it explicitly.
+func GC(maxAge time.Duration) {
+ root, err := os.UserCacheDir()
+ if err != nil || root == "" {
+ return
+ }
+ dir := filepath.Join(root, "openlit", "sessions")
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return
+ }
+ cutoff := time.Now().Add(-maxAge)
+ for _, e := range entries {
+ if e.IsDir() {
+ continue
+ }
+ info, err := e.Info()
+ if err != nil {
+ continue
+ }
+ if info.ModTime().Before(cutoff) {
+ _ = os.Remove(filepath.Join(dir, e.Name()))
+ }
+ }
+}
diff --git a/cli/internal/coding/tailfile/tailfile.go b/cli/internal/coding/tailfile/tailfile.go
new file mode 100644
index 00000000..80030c28
--- /dev/null
+++ b/cli/internal/coding/tailfile/tailfile.go
@@ -0,0 +1,94 @@
+// Package tailfile reads the last N bytes of a file as a slice of
+// JSONL lines, dropping a partial first line.
+//
+// We use it for cost-rollup paths that need to scan transcripts at
+// hook end-of-session. Reading the whole file is unsafe — long
+// sessions can produce multi-MB or larger files and the hook process
+// is on a tight latency budget (< 1s p99). Bounding the read keeps
+// the worst case predictable at the cost of undercounting tokens for
+// sessions that span more than `cap` bytes of transcript.
+//
+// F3: Phase F task in the coding-agents plan. The cap default is
+// chosen to comfortably cover a few hours of dense usage while still
+// fitting in memory on small CI runners.
+package tailfile
+
+import (
+ "bufio"
+ "bytes"
+ "io"
+ "os"
+)
+
+// DefaultCap is the byte budget for a tail-read. 4 MiB lets a
+// Claude/Codex session of ~30k turns be read entirely; only outlier
+// marathon sessions get truncated. Tunable per-call via Tail's cap
+// parameter, but exported because adapters share this value as
+// their canonical default.
+const DefaultCap int64 = 4 * 1024 * 1024
+
+// LineCap caps the maximum line length the scanner will accept.
+// JSONL records that exceed this are skipped (not fatal). 1 MiB
+// is comfortably larger than any Anthropic/OpenAI usage line.
+const LineCap = 1 * 1024 * 1024
+
+// Tail returns up to `cap` bytes from the end of `path` split into
+// lines, with the first (possibly partial) line discarded. Returns
+// an empty slice if the file is missing/unreadable so callers can
+// treat the result as "best effort, nothing to roll up".
+func Tail(path string, cap int64) [][]byte {
+ if path == "" {
+ return nil
+ }
+ if cap <= 0 {
+ cap = DefaultCap
+ }
+ f, err := os.Open(path) //nolint:gosec // path comes from the agent's own payload
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+
+ info, err := f.Stat()
+ if err != nil {
+ return nil
+ }
+ size := info.Size()
+ start := int64(0)
+ truncated := false
+ if size > cap {
+ start = size - cap
+ truncated = true
+ }
+ if _, err := f.Seek(start, io.SeekStart); err != nil {
+ return nil
+ }
+
+ // We use Scanner with a custom buffer because the default 64 KiB
+ // is below realistic usage-record line size on long Claude turns.
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 64*1024), LineCap)
+
+ var out [][]byte
+ first := true
+ for scanner.Scan() {
+ line := bytes.TrimSpace(scanner.Bytes())
+ // When we seeked into the middle of the file, the first
+ // "line" is almost certainly truncated JSON — discard it
+ // so we don't pollute the caller with garbage records.
+ if first {
+ first = false
+ if truncated {
+ continue
+ }
+ }
+ if len(line) == 0 {
+ continue
+ }
+ // Copy because Scanner reuses the underlying buffer.
+ buf := make([]byte, len(line))
+ copy(buf, line)
+ out = append(out, buf)
+ }
+ return out
+}
diff --git a/cli/internal/coding/uninstall/uninstall.go b/cli/internal/coding/uninstall/uninstall.go
new file mode 100644
index 00000000..4aa454b3
--- /dev/null
+++ b/cli/internal/coding/uninstall/uninstall.go
@@ -0,0 +1,133 @@
+// Package uninstall implements `openlit coding uninstall --vendor=...`.
+//
+// Inverse of `openlit coding install`: removes the per-vendor host
+// plugin manifests that install writes, optionally deregisters the
+// plugin from the vendor's own CLI (Claude Code's `claude plugin
+// uninstall`, Codex's `codex plugin remove`), and with `--purge` also
+// drops the shared OpenLit config and session-state cache.
+//
+// We separate `--vendor` cleanup from `--purge` so the common
+// "I want to stop Cursor from being tracked but keep my Claude Code
+// telemetry" case is a single command and doesn't blow away the
+// shared API key + endpoint config.
+package uninstall
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/spf13/cobra"
+)
+
+// NewCmd returns the cobra command for `openlit coding uninstall`.
+func NewCmd() *cobra.Command {
+ var (
+ vendor string
+ purge bool
+ dryRun bool
+ )
+
+ cmd := &cobra.Command{
+ Use: "uninstall",
+ Short: "Remove per-vendor coding-agent host plugin manifests",
+ Long: `Remove host plugin manifests previously written by 'openlit coding install'.
+
+Vendors:
+ claude-code ~/.claude/plugins/openlit-cc/ + 'claude plugin uninstall'
+ cursor strips openlit entries from ~/.cursor/hooks.json (preserves other tools')
+ codex ~/.local/share/openlit/codex-marketplace/ + 'codex plugin remove'
+ all shorthand for all three
+
+Use --purge to also remove the shared OpenLit config (~/.config/openlit)
+and the session-state cache. Leave it off if you plan to re-install
+later and want to keep your API key + endpoint.
+
+The 'openlit' binary itself is NOT removed by this command. Uninstall
+it via the same channel you installed it through (Homebrew, the curl|sh
+installer, or 'go install').`,
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ return run(cmd, vendor, purge, dryRun)
+ },
+ }
+
+ cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor (claude-code | cursor | codex | all)")
+ cmd.Flags().BoolVar(&purge, "purge", false, "Also remove ~/.config/openlit and the session-state cache")
+ cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print what would be removed without modifying any files")
+ _ = cmd.MarkFlagRequired("vendor")
+
+ return cmd
+}
+
+func run(cmd *cobra.Command, vendor string, purge, dryRun bool) error {
+ vendor = strings.ToLower(strings.TrimSpace(vendor))
+ if vendor == "" {
+ return errors.New("--vendor is required")
+ }
+
+ targets, err := vendorsFromArg(vendor)
+ if err != nil {
+ return err
+ }
+
+ out := cmd.OutOrStdout()
+ for _, v := range targets {
+ removed, vendErrs := uninstallVendor(v, dryRun)
+ if dryRun {
+ fmt.Fprintf(out, "[dry-run] would remove %d path(s) for %s\n", len(removed), v)
+ } else {
+ fmt.Fprintf(out, "openlit: removed %s plugin (%d path(s))\n", v, len(removed))
+ }
+ for _, p := range removed {
+ fmt.Fprintf(out, " - %s\n", p)
+ }
+ for _, e := range vendErrs {
+ fmt.Fprintf(cmd.ErrOrStderr(), "openlit uninstall %s: %s\n", v, e)
+ }
+ }
+
+ if purge {
+ removed, purgeErrs := purgeShared(dryRun)
+ if dryRun {
+ fmt.Fprintf(out, "[dry-run] --purge would remove %d shared path(s)\n", len(removed))
+ } else {
+ fmt.Fprintf(out, "openlit: purged %d shared path(s)\n", len(removed))
+ }
+ for _, p := range removed {
+ fmt.Fprintf(out, " - %s\n", p)
+ }
+ for _, e := range purgeErrs {
+ fmt.Fprintf(cmd.ErrOrStderr(), "openlit uninstall --purge: %s\n", e)
+ }
+ }
+
+ if !dryRun {
+ fmt.Fprintln(out, "")
+ fmt.Fprintln(out, "Hooks will stop firing on the agent's next session.")
+ if !purge {
+ fmt.Fprintln(out, "Tip: pass --purge to also drop ~/.config/openlit and the session-state cache.")
+ }
+ }
+ return nil
+}
+
+// vendorsFromArg mirrors the install package's accepted vendor IDs so
+// the two commands stay in lock-step. We intentionally duplicate the
+// switch rather than import install/ to keep uninstall buildable on
+// its own (and the surface is small).
+func vendorsFromArg(arg string) ([]string, error) {
+ switch arg {
+ case "all":
+ return []string{"claude-code", "cursor", "codex"}, nil
+ case "claude-code", "cc":
+ return []string{"claude-code"}, nil
+ case "cursor":
+ return []string{"cursor"}, nil
+ case "codex":
+ return []string{"codex"}, nil
+ default:
+ return nil, fmt.Errorf("unknown --vendor %q", arg)
+ }
+}
diff --git a/cli/internal/coding/uninstall/uninstall_cursor.go b/cli/internal/coding/uninstall/uninstall_cursor.go
new file mode 100644
index 00000000..1d3c8c5d
--- /dev/null
+++ b/cli/internal/coding/uninstall/uninstall_cursor.go
@@ -0,0 +1,190 @@
+// Cursor-specific uninstall path: the symmetric inverse of
+// install_cursor.go.
+//
+// Strips every hook entry whose `command` we own out of
+// ~/.cursor/hooks.json. We MUST NOT touch entries authored by other
+// tools (or the user themselves), so we operate per-event and
+// per-entry rather than overwriting the file. If our strip empties
+// the entire `hooks` block AND nothing else of substance remains
+// (a bare `version` field doesn't count), we delete the file
+// outright so the user is left with a clean home directory.
+//
+// Idempotent: running uninstall against a machine that was never
+// installed is a no-op and reports zero paths touched.
+
+package uninstall
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// cursorOwnedCommandMarker mirrors install/install_cursor.go. Kept in
+// sync by code review: both packages must agree on what "ours" means.
+const cursorOwnedCommandMarker = "openlit coding hook --vendor=cursor"
+
+// uninstallCursorHooks performs the two cleanup steps. Returns the
+// absolute paths it removed or rewrote, plus any non-fatal errors.
+func uninstallCursorHooks(dryRun bool) (removed []string, errs []string) {
+ hooksPath, err := userCursorHooksPath()
+ if err != nil {
+ return nil, []string{err.Error()}
+ }
+
+ switch path, e := stripCursorHooks(hooksPath, dryRun); {
+ case e != nil:
+ errs = append(errs, e.Error())
+ case path != "":
+ removed = append(removed, path)
+ }
+ return removed, errs
+}
+
+// stripCursorHooks rewrites hooksPath in place to drop our entries.
+// Returns the path that was modified (empty if no change was needed).
+// Missing file = nothing to do, not an error.
+func stripCursorHooks(hooksPath string, dryRun bool) (string, error) {
+ body, err := os.ReadFile(hooksPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return "", nil
+ }
+ return "", err
+ }
+ if len(body) == 0 {
+ return "", nil
+ }
+
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal(body, &raw); err != nil {
+ return "", fmt.Errorf("parse %s: %w (leaving the file untouched)", hooksPath, err)
+ }
+
+ hooksRaw, ok := raw["hooks"]
+ if !ok {
+ // No hooks block at all — nothing for us to strip.
+ return "", nil
+ }
+ var hooks map[string][]json.RawMessage
+ if err := json.Unmarshal(hooksRaw, &hooks); err != nil {
+ return "", fmt.Errorf("parse hooks in %s: %w (leaving the file untouched)", hooksPath, err)
+ }
+
+ changed := false
+ for event, entries := range hooks {
+ kept := make([]json.RawMessage, 0, len(entries))
+ for _, e := range entries {
+ if isOpenLitEntry(e) {
+ changed = true
+ continue
+ }
+ kept = append(kept, e)
+ }
+ if len(kept) == 0 {
+ delete(hooks, event)
+ } else {
+ hooks[event] = kept
+ }
+ }
+
+ if !changed {
+ return "", nil
+ }
+
+ // If our strip emptied the hooks block AND nothing else of
+ // substance remains, drop the file. Otherwise re-serialize the
+ // trimmed structure. We treat a lone `version` field as
+ // "of no substance" — keeping the file just for that is noise.
+ if len(hooks) == 0 {
+ nonTrivial := false
+ for k := range raw {
+ if k != "hooks" && k != "version" {
+ nonTrivial = true
+ break
+ }
+ }
+ if !nonTrivial {
+ if dryRun {
+ return hooksPath, nil
+ }
+ if err := os.Remove(hooksPath); err != nil {
+ return hooksPath, err
+ }
+ return hooksPath, nil
+ }
+ }
+
+ updatedHooks, err := json.Marshal(hooks)
+ if err != nil {
+ return "", fmt.Errorf("encode trimmed hooks: %w", err)
+ }
+ if len(hooks) == 0 {
+ delete(raw, "hooks")
+ } else {
+ raw["hooks"] = updatedHooks
+ }
+
+ out, err := json.MarshalIndent(raw, "", " ")
+ if err != nil {
+ return "", fmt.Errorf("encode trimmed hooks file: %w", err)
+ }
+ out = append(out, '\n')
+
+ if dryRun {
+ return hooksPath, nil
+ }
+ if err := writeFileAtomic(hooksPath, out, 0o644); err != nil {
+ return hooksPath, err
+ }
+ return hooksPath, nil
+}
+
+// isOpenLitEntry reports whether a hook entry was authored by us.
+// Mirrors install/install_cursor.go's helper of the same name.
+func isOpenLitEntry(raw json.RawMessage) bool {
+ var entry struct {
+ Command string `json:"command"`
+ }
+ if err := json.Unmarshal(raw, &entry); err != nil {
+ return false
+ }
+ return entry.Command != "" && strings.Contains(entry.Command, cursorOwnedCommandMarker)
+}
+
+func userCursorHooksPath() (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("could not resolve home directory: %w", err)
+ }
+ return filepath.Join(home, ".cursor", "hooks.json"), nil
+}
+
+// writeFileAtomic writes body to path via a tempfile + rename so a
+// crash mid-write can't leave a half-written hooks file in place.
+func writeFileAtomic(path string, body []byte, mode os.FileMode) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(path), ".hooks.json.*")
+ if err != nil {
+ return err
+ }
+ name := tmp.Name()
+ if _, err := tmp.Write(body); err != nil {
+ _ = tmp.Close()
+ _ = os.Remove(name)
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ _ = os.Remove(name)
+ return err
+ }
+ if err := os.Chmod(name, mode); err != nil {
+ _ = os.Remove(name)
+ return err
+ }
+ return os.Rename(name, path)
+}
diff --git a/cli/internal/coding/uninstall/uninstall_cursor_test.go b/cli/internal/coding/uninstall/uninstall_cursor_test.go
new file mode 100644
index 00000000..23ed77a5
--- /dev/null
+++ b/cli/internal/coding/uninstall/uninstall_cursor_test.go
@@ -0,0 +1,152 @@
+package uninstall
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestStripCursorHooks_RemovesOnlyOurs(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "hooks.json")
+ body := `{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [
+ {"command": "other-tool"},
+ {"command": "/Users/me/.openlit/bin/openlit coding hook --vendor=cursor --event=sessionStart", "timeout": 5000}
+ ],
+ "customEvent": [{"command": "user-script"}]
+ }
+ }`
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ removed, err := stripCursorHooks(path, false)
+ if err != nil {
+ t.Fatalf("strip: %v", err)
+ }
+ if removed != path {
+ t.Fatalf("removed = %q want %q", removed, path)
+ }
+
+ out, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var parsed struct {
+ Hooks map[string][]map[string]any `json:"hooks"`
+ }
+ if err := json.Unmarshal(out, &parsed); err != nil {
+ t.Fatalf("parse rewrite: %v\n%s", err, out)
+ }
+ if got := len(parsed.Hooks["sessionStart"]); got != 1 {
+ t.Fatalf("expected 1 sessionStart left (other-tool); got %d (%v)", got, parsed.Hooks["sessionStart"])
+ }
+ if parsed.Hooks["sessionStart"][0]["command"] != "other-tool" {
+ t.Fatalf("wrong entry survived: %v", parsed.Hooks["sessionStart"][0])
+ }
+ if got := len(parsed.Hooks["customEvent"]); got != 1 {
+ t.Fatalf("customEvent should be intact; got %d", got)
+ }
+}
+
+func TestStripCursorHooks_DeletesFileWhenOnlyOursAndVersion(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "hooks.json")
+ body := `{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [
+ {"command": "openlit coding hook --vendor=cursor --event=sessionStart"}
+ ]
+ }
+ }`
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := stripCursorHooks(path, false); err != nil {
+ t.Fatalf("strip: %v", err)
+ }
+
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("hooks.json should be deleted, but Stat returned err=%v", err)
+ }
+}
+
+func TestStripCursorHooks_KeepsFileWhenOtherTopLevelKeysExist(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "hooks.json")
+ body := `{
+ "version": 1,
+ "hooks": {"sessionStart": [{"command": "openlit coding hook --vendor=cursor --event=sessionStart"}]},
+ "someCustomThing": {"foo": "bar"}
+ }`
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := stripCursorHooks(path, false); err != nil {
+ t.Fatalf("strip: %v", err)
+ }
+
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("file should still exist (someCustomThing present): %v", err)
+ }
+ out, _ := os.ReadFile(path)
+ var raw map[string]any
+ if err := json.Unmarshal(out, &raw); err != nil {
+ t.Fatalf("parse: %v\n%s", err, out)
+ }
+ if _, ok := raw["someCustomThing"]; !ok {
+ t.Fatalf("someCustomThing must be preserved; got %v", raw)
+ }
+}
+
+func TestStripCursorHooks_MissingFileIsNoOp(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "hooks.json")
+ removed, err := stripCursorHooks(path, false)
+ if err != nil {
+ t.Fatalf("strip: %v", err)
+ }
+ if removed != "" {
+ t.Fatalf("removed = %q want empty", removed)
+ }
+}
+
+func TestStripCursorHooks_NoOpWhenNothingOurs(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "hooks.json")
+ body := `{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [{"command": "other-tool"}]
+ }
+ }`
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ mtimeBefore, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ removed, err := stripCursorHooks(path, false)
+ if err != nil {
+ t.Fatalf("strip: %v", err)
+ }
+ if removed != "" {
+ t.Fatalf("nothing of ours present, but strip reported %q", removed)
+ }
+ mtimeAfter, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !mtimeBefore.ModTime().Equal(mtimeAfter.ModTime()) {
+ t.Fatalf("file should not have been touched")
+ }
+}
diff --git a/cli/internal/coding/uninstall/uninstall_test.go b/cli/internal/coding/uninstall/uninstall_test.go
new file mode 100644
index 00000000..0aabb9aa
--- /dev/null
+++ b/cli/internal/coding/uninstall/uninstall_test.go
@@ -0,0 +1,114 @@
+package uninstall
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// TestRemovePath covers the three states the helper has to handle:
+// missing path (no-op, no error), existing file (removed unless
+// dry-run), existing directory (recursive remove unless dry-run).
+//
+// These are the failure modes that bit us during install: a stale
+// re-run had to be safe, and a missing path on a fresh box couldn't
+// surface as a noisy error.
+func TestRemovePath(t *testing.T) {
+ t.Parallel()
+ tmp := t.TempDir()
+
+ t.Run("missing path is a no-op", func(t *testing.T) {
+ t.Parallel()
+ missing := filepath.Join(t.TempDir(), "does-not-exist")
+ path, err := removePath(missing, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if path != "" {
+ t.Fatalf("expected empty path for missing target, got %q", path)
+ }
+ })
+
+ t.Run("existing directory is removed", func(t *testing.T) {
+ t.Parallel()
+ dir := filepath.Join(tmp, "vendor-dir")
+ nested := filepath.Join(dir, "hooks", "hooks.json")
+ if err := os.MkdirAll(filepath.Dir(nested), 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.WriteFile(nested, []byte("{}"), 0o644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ path, err := removePath(dir, false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if path != dir {
+ t.Fatalf("expected returned path %q, got %q", dir, path)
+ }
+ if _, err := os.Stat(dir); !os.IsNotExist(err) {
+ t.Fatalf("expected directory removed, stat returned %v", err)
+ }
+ })
+
+ t.Run("dry-run leaves disk untouched", func(t *testing.T) {
+ t.Parallel()
+ dir := filepath.Join(tmp, "dry-run-dir")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ path, err := removePath(dir, true)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if path != dir {
+ t.Fatalf("dry-run should report the path that would be removed; got %q", path)
+ }
+ if _, err := os.Stat(dir); err != nil {
+ t.Fatalf("dry-run must not touch disk; stat error: %v", err)
+ }
+ })
+}
+
+// TestVendorsFromArg is a regression guard for the inverse-of-install
+// vendor parser. If install/ ever adds a new vendor, this test should
+// be updated in the same patch so uninstall stays symmetric.
+func TestVendorsFromArg(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ in string
+ want []string
+ }{
+ {"all", []string{"claude-code", "cursor", "codex"}},
+ {"cc", []string{"claude-code"}},
+ {"claude-code", []string{"claude-code"}},
+ {"cursor", []string{"cursor"}},
+ {"codex", []string{"codex"}},
+ }
+ for _, tc := range cases {
+ got, err := vendorsFromArg(tc.in)
+ if err != nil {
+ t.Fatalf("%s: unexpected error: %v", tc.in, err)
+ }
+ if !equalSlice(got, tc.want) {
+ t.Fatalf("%s: got %v, want %v", tc.in, got, tc.want)
+ }
+ }
+
+ if _, err := vendorsFromArg("nope"); err == nil {
+ t.Fatalf("unknown vendor should error")
+ }
+}
+
+func equalSlice(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
diff --git a/cli/internal/coding/uninstall/uninstall_vendors.go b/cli/internal/coding/uninstall/uninstall_vendors.go
new file mode 100644
index 00000000..456d7143
--- /dev/null
+++ b/cli/internal/coding/uninstall/uninstall_vendors.go
@@ -0,0 +1,314 @@
+// Per-vendor uninstall logic. Each vendor's section is the inverse of
+// the corresponding installVendor / enable<Vendor>Plugin pair in
+// internal/coding/install.
+
+package uninstall
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+// uninstallVendor removes the host plugin manifest set for one vendor
+// and, where the vendor exposes a CLI to manage plugins (Claude Code,
+// Codex), best-effort deregisters the plugin so the agent's own state
+// stays consistent.
+//
+// Returns the absolute paths it touched plus a list of non-fatal
+// errors. Side-channel CLI failures (e.g. `claude` not on PATH, codex
+// returning "plugin not installed") are collected and returned rather
+// than propagated as a hard error: directory cleanup is the
+// authoritative state, and we don't want a missing vendor CLI to
+// block the user's "I want this gone" flow.
+func uninstallVendor(vendor string, dryRun bool) (removed []string, errs []string) {
+ // Cursor lives in a shared user-scope file (~/.cursor/hooks.json)
+ // rather than a vendor-owned directory, so it gets its own
+ // path-aware stripper (see uninstall_cursor.go) that preserves
+ // other tools' entries.
+ if vendor == "cursor" {
+ return uninstallCursorHooks(dryRun)
+ }
+
+ dest, err := vendorDestRoot(vendor)
+ if err != nil {
+ return nil, []string{err.Error()}
+ }
+
+ primary, primaryErr := removePath(dest, dryRun)
+ if primary != "" {
+ removed = append(removed, primary)
+ }
+ if primaryErr != nil {
+ errs = append(errs, primaryErr.Error())
+ }
+
+ switch vendor {
+ case "claude-code":
+ // Four side effects beyond the manifest directory:
+ // 1. ~/.local/share/openlit/claude-marketplace/ — written
+ // by materializeClaudeMarketplace so `claude plugin
+ // marketplace add` had a stable path. Removing the
+ // tree here means a future re-install rebuilds it
+ // from the embedded FS, which is cheap.
+ // 2. ~/.claude/plugins/cache/openlit/openlit-cc/ — Claude
+ // Code's own per-version download cache. Without this
+ // sweep, a re-install + version bump leaves the
+ // previous version's binary on disk forever (Claude
+ // Code does not GC stale plugin payloads).
+ // 3. `claude plugin uninstall openlit-cc@openlit` + the
+ // marketplace-remove counterpart — best-effort. If
+ // the user already removed it from inside the Claude
+ // TUI we'll get an "already uninstalled" style error
+ // and continue.
+ // 4. JSON-level fallback: strip the "openlit" entry
+ // from ~/.claude/plugins/known_marketplaces.json.
+ // `claude plugin marketplace remove` does not always
+ // clear this file in practice (observed across
+ // multiple Claude Code builds), and leaving it
+ // behind causes a re-install to silently use the
+ // stale `installLocation` field.
+ mp, mpErr := claudeMarketplaceRoot()
+ if mpErr == nil {
+ p, e := removePath(mp, dryRun)
+ if p != "" {
+ removed = append(removed, p)
+ }
+ if e != nil {
+ errs = append(errs, e.Error())
+ }
+ }
+ if cache, cacheErr := claudePluginCacheRoot(); cacheErr == nil {
+ p, e := removePath(cache, dryRun)
+ if p != "" {
+ removed = append(removed, p)
+ }
+ if e != nil {
+ errs = append(errs, e.Error())
+ }
+ }
+ if !dryRun {
+ if e := disableClaudeCodePlugin(); e != nil {
+ errs = append(errs, e.Error())
+ }
+ }
+ if touched, e := stripClaudeMarketplaceJSON(dryRun); touched != "" {
+ removed = append(removed, touched+" (openlit entry)")
+ if e != nil {
+ errs = append(errs, e.Error())
+ }
+ }
+ case "codex":
+ // Codex stores the marketplace AS the plugin dest dir
+ // (see vendorDestRoot), so the directory removal above
+ // also removes the marketplace tree. We still need to:
+ // 1. Tell Codex to forget about it via the CLI so its
+ // `codex plugin marketplace list` state matches reality.
+ // 2. TOML-level fallback: strip [marketplaces.openlit],
+ // [plugins."openlit@openlit"], and every
+ // [hooks.state."openlit@openlit:*"] section from
+ // ~/.codex/config.toml. Codex's own `plugin remove`
+ // and `plugin marketplace remove` subcommands have
+ // been observed to leave these sections in place
+ // (with `enabled = true` on the plugin block!), so
+ // we go straight to the source of truth on disk.
+ if !dryRun {
+ if e := disableCodexPlugin(); e != nil {
+ errs = append(errs, e.Error())
+ }
+ }
+ if touched, e := stripCodexConfigTOML(dryRun); touched != "" {
+ removed = append(removed, touched+" (openlit sections)")
+ if e != nil {
+ errs = append(errs, e.Error())
+ }
+ }
+ }
+ return removed, errs
+}
+
+// purgeShared removes the cross-vendor OpenLit state. Triggered by
+// `--purge`; left out by default so re-onboarding doesn't require
+// re-entering the API key / endpoint.
+func purgeShared(dryRun bool) (removed []string, errs []string) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return nil, []string{err.Error()}
+ }
+
+ // 1. ~/.config/openlit/ — `openlit configure` output. We
+ // intentionally remove the whole directory rather than just
+ // config.env so any future managed-config side files
+ // (audit logs, key cache, …) are swept up by the same flag.
+ configDir := filepath.Join(home, ".config", "openlit")
+ if p, e := removePath(configDir, dryRun); p != "" {
+ removed = append(removed, p)
+ if e != nil {
+ errs = append(errs, e.Error())
+ }
+ }
+
+ // 2. <UserCacheDir>/openlit/ — session-state cache. Path
+ // resolution matches the sessionstate package so we don't
+ // drift if XDG_CACHE_HOME is set.
+ if cacheRoot, err := os.UserCacheDir(); err == nil && cacheRoot != "" {
+ openlitCache := filepath.Join(cacheRoot, "openlit")
+ if p, e := removePath(openlitCache, dryRun); p != "" {
+ removed = append(removed, p)
+ if e != nil {
+ errs = append(errs, e.Error())
+ }
+ }
+ }
+ return removed, errs
+}
+
+// vendorDestRoot mirrors install.vendorDestRoot for the vendors that
+// own a directory. Cursor is handled separately (it merges into a
+// shared hooks.json) and intentionally does not have an entry here.
+// Kept as a private helper to avoid importing the install package
+// (which would create a circular-import risk if install later grows
+// test helpers that pull uninstall in).
+func vendorDestRoot(vendor string) (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("could not resolve home directory: %w", err)
+ }
+ switch vendor {
+ case "claude-code":
+ return filepath.Join(home, ".claude", "plugins", "openlit-cc"), nil
+ case "codex":
+ return filepath.Join(home, ".local", "share", "openlit", "codex-marketplace"), nil
+ default:
+ return "", fmt.Errorf("unknown vendor %q", vendor)
+ }
+}
+
+func claudeMarketplaceRoot() (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, ".local", "share", "openlit", "claude-marketplace"), nil
+}
+
+// claudePluginCacheRoot is where Claude Code unpacks the actual
+// plugin payload it downloaded from a marketplace. The path is
+// `~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/`, and
+// Claude does not GC stale versions on its own; if we don't sweep
+// this on uninstall, a user who reinstalls with a new version will
+// leave the old payload (and the matching CLAUDE_PLUGIN_ROOT-shaped
+// directory) on disk indefinitely. The marketplace key matches the
+// `id` field of `~/.local/share/openlit/claude-marketplace/.claude-plugin/marketplace.json`.
+func claudePluginCacheRoot() (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, ".claude", "plugins", "cache", "openlit", "openlit-cc"), nil
+}
+
+// removePath removes a file or directory tree at p. Returns the path
+// (only when it existed pre-removal) and any error from the removal
+// itself. A missing path is not an error: a fresh machine has no
+// installation to undo and shouldn't see a spurious "not found".
+func removePath(p string, dryRun bool) (string, error) {
+ if p == "" {
+ return "", nil
+ }
+ if _, err := os.Stat(p); err != nil {
+ if os.IsNotExist(err) {
+ return "", nil
+ }
+ return "", err
+ }
+ if dryRun {
+ return p, nil
+ }
+ if err := os.RemoveAll(p); err != nil {
+ return p, err
+ }
+ return p, nil
+}
+
+// disableClaudeCodePlugin asks the `claude` CLI to drop the openlit-cc
+// plugin AND the openlit marketplace registration. Both are
+// best-effort: a missing CLI or a "nothing to do" outcome is
+// collapsed to nil so we don't block the directory cleanup that
+// already ran. The JSON-level fallback in stripClaudeMarketplaceJSON
+// is what makes uninstall actually reliable when this CLI path is
+// silently incomplete.
+func disableClaudeCodePlugin() error {
+ claudeBin, err := exec.LookPath("claude")
+ if err != nil {
+ return nil
+ }
+ // 1) Plugin uninstall. Arg shape mirrors the install side
+ // (`plugin install openlit-cc@openlit --scope user`),
+ // inverted. If Claude renames the subcommand we swallow
+ // the error rather than fail the directory cleanup.
+ rm := exec.Command(claudeBin, "plugin", "uninstall", "openlit-cc@openlit", "--scope", "user") //nolint:gosec
+ if out, err := rm.CombinedOutput(); err != nil {
+ msg := strings.TrimSpace(string(out))
+ lower := strings.ToLower(msg)
+ if msg != "" &&
+ !strings.Contains(lower, "not installed") &&
+ !strings.Contains(lower, "not found") &&
+ !strings.Contains(lower, "no such plugin") {
+ return fmt.Errorf("claude plugin uninstall: %s", msg)
+ }
+ }
+ // 2) Marketplace remove. The install side ran `claude plugin
+ // marketplace add <path>` to register openlit; this is its
+ // inverse. The bare "openlit" key matches the marketplace
+ // `name` field in our claude-marketplace.json.
+ mp := exec.Command(claudeBin, "plugin", "marketplace", "remove", "openlit") //nolint:gosec
+ if out, err := mp.CombinedOutput(); err != nil {
+ msg := strings.TrimSpace(string(out))
+ lower := strings.ToLower(msg)
+ if msg != "" &&
+ !strings.Contains(lower, "not registered") &&
+ !strings.Contains(lower, "not found") &&
+ !strings.Contains(lower, "no such marketplace") {
+ return fmt.Errorf("claude plugin marketplace remove openlit: %s", msg)
+ }
+ }
+ return nil
+}
+
+// disableCodexPlugin tells the `codex` CLI to remove the openlit plugin
+// and then forget the openlit marketplace registration. Both are
+// best-effort and treat "already gone" as success.
+func disableCodexPlugin() error {
+ codexBin, err := exec.LookPath("codex")
+ if err != nil {
+ return nil
+ }
+
+ rm := exec.Command(codexBin, "plugin", "remove", "openlit@openlit") //nolint:gosec
+ if out, err := rm.CombinedOutput(); err != nil {
+ msg := strings.TrimSpace(string(out))
+ lower := strings.ToLower(msg)
+ if msg != "" &&
+ !strings.Contains(lower, "not installed") &&
+ !strings.Contains(lower, "not found") &&
+ !strings.Contains(lower, "no such plugin") {
+ return fmt.Errorf("codex plugin remove openlit@openlit: %s", msg)
+ }
+ }
+
+ mp := exec.Command(codexBin, "plugin", "marketplace", "remove", "openlit") //nolint:gosec
+ if out, err := mp.CombinedOutput(); err != nil {
+ msg := strings.TrimSpace(string(out))
+ lower := strings.ToLower(msg)
+ if msg != "" &&
+ !strings.Contains(lower, "not registered") &&
+ !strings.Contains(lower, "not found") &&
+ !strings.Contains(lower, "no such marketplace") {
+ return fmt.Errorf("codex plugin marketplace remove openlit: %s", msg)
+ }
+ }
+ return nil
+}
diff --git a/cli/internal/coding/uninstall/vendor_config_scrub.go b/cli/internal/coding/uninstall/vendor_config_scrub.go
new file mode 100644
index 00000000..16339a63
--- /dev/null
+++ b/cli/internal/coding/uninstall/vendor_config_scrub.go
@@ -0,0 +1,181 @@
+// File-level scrubbers that run after the vendor-CLI based uninstall
+// steps. In practice, both the Claude Code and Codex CLIs have been
+// observed to leave residual openlit-owned state in their on-disk
+// config files even after their advertised "uninstall" / "marketplace
+// remove" subcommands run to success. The scrubbers here are
+// defense in depth: surgical edits that delete only the keys / TOML
+// sections openlit owns, preserve everything else, and treat the
+// missing-file case as a no-op.
+//
+// We deliberately do not use a TOML library here — adding one for
+// this single janitorial use case is more risk (line-noise diff,
+// dep churn) than benefit. The stripper is line-based and section-
+// aware; the test in vendor_config_scrub_test.go covers the
+// interesting cases (mixed sections, nested project blocks,
+// inline tables on adjacent lines).
+
+package uninstall
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+// stripClaudeMarketplaceJSON removes the `openlit` entry from
+// `~/.claude/plugins/known_marketplaces.json` when present. Returns
+// the file path it touched (empty string if nothing to do) and any
+// error encountered. Missing file / missing key are not errors.
+//
+// In dry-run mode the file is left unchanged but a present openlit
+// key is still reported as "would touch".
+func stripClaudeMarketplaceJSON(dryRun bool) (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ path := filepath.Join(home, ".claude", "plugins", "known_marketplaces.json")
+ raw, err := os.ReadFile(path) //nolint:gosec // path is derived from $HOME
+ if err != nil {
+ if os.IsNotExist(err) {
+ return "", nil
+ }
+ return "", err
+ }
+ // Unmarshal into a generic map so we don't have to track
+ // Claude's schema. We only need to know "does the openlit
+ // key exist?". The file is small (a few dozen entries at
+ // most) so the round-trip cost is negligible.
+ var data map[string]any
+ if err := json.Unmarshal(raw, &data); err != nil {
+ // If the file is unparseable, leave it alone rather than
+ // blow it away — user may have hand-edited it.
+ return "", fmt.Errorf("parse %s: %w", path, err)
+ }
+ if _, ok := data["openlit"]; !ok {
+ return "", nil
+ }
+ if dryRun {
+ return path, nil
+ }
+ delete(data, "openlit")
+ // Re-marshal with the same indentation Claude itself uses
+ // (two spaces) so the diff in the user's dotfiles repo is
+ // minimal.
+ out, err := json.MarshalIndent(data, "", " ")
+ if err != nil {
+ return path, err
+ }
+ out = append(out, '\n')
+ if err := writeFileAtomic(path, out, 0o600); err != nil {
+ return path, err
+ }
+ return path, nil
+}
+
+// codexOpenlitSectionRe matches every TOML section header that
+// openlit owns. The patterns mirror exactly what
+// `install_patch.go` causes Codex to write — they are NOT a
+// best-effort guess.
+//
+// [marketplaces.openlit] ← from `codex plugin marketplace add`
+// [plugins."openlit@openlit"] ← from `codex plugin add openlit@openlit`
+// [hooks.state."openlit@openlit:hooks/hooks.json:*"] ← codex caches trusted-hash per hook event
+var codexOpenlitSectionRe = regexp.MustCompile(
+ `^\[(?:` +
+ `marketplaces\.openlit` +
+ `|plugins\."openlit@openlit"` +
+ `|hooks\.state\."openlit@openlit:[^"]*"` +
+ `)\]\s*$`,
+)
+
+// codexAnySectionRe matches a bare `[section.name]` line. Used to
+// detect the boundary that ends an openlit section we're stripping.
+var codexAnySectionRe = regexp.MustCompile(`^\[[^\]]+\]\s*$`)
+
+// stripCodexConfigTOML rewrites `~/.codex/config.toml` so that
+// every openlit-owned section is removed. Other sections —
+// including `[projects."/Users/.../openlit"]` (which is a user
+// trust-level entry, not an openlit artifact) — are preserved
+// verbatim.
+//
+// Returns the file path that was touched (empty string when nothing
+// changed) plus any error from the read/write path. Missing file
+// is a no-op.
+func stripCodexConfigTOML(dryRun bool) (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ path := filepath.Join(home, ".codex", "config.toml")
+ raw, err := os.ReadFile(path) //nolint:gosec // path is derived from $HOME
+ if err != nil {
+ if os.IsNotExist(err) {
+ return "", nil
+ }
+ return "", err
+ }
+ rewritten, changed := stripCodexOpenlitSections(string(raw))
+ if !changed {
+ return "", nil
+ }
+ if dryRun {
+ return path, nil
+ }
+ if err := writeFileAtomic(path, []byte(rewritten), 0o600); err != nil {
+ return path, err
+ }
+ return path, nil
+}
+
+// stripCodexOpenlitSections is the pure string transformation that
+// `stripCodexConfigTOML` wraps. Split out for direct table-driven
+// testing without touching the filesystem.
+//
+// Returns (rewritten, changed). `changed` is true iff at least one
+// openlit section was removed.
+func stripCodexOpenlitSections(src string) (string, bool) {
+ // Preserve the original line-ending style by working on raw
+ // bytes via strings.Split. CRLF inputs come through as
+ // trailing \r on each split element — that's fine; we join
+ // with the same separator.
+ sep := "\n"
+ if strings.Contains(src, "\r\n") && !strings.Contains(strings.ReplaceAll(src, "\r\n", ""), "\n") {
+ sep = "\r\n"
+ }
+ lines := strings.Split(src, sep)
+
+ out := make([]string, 0, len(lines))
+ drop := false
+ changed := false
+ for _, line := range lines {
+ trimmed := strings.TrimRight(line, "\r")
+ if codexAnySectionRe.MatchString(trimmed) {
+ if codexOpenlitSectionRe.MatchString(trimmed) {
+ drop = true
+ changed = true
+ continue
+ }
+ drop = false
+ }
+ if drop {
+ continue
+ }
+ out = append(out, line)
+ }
+
+ // Collapse runs of >2 blank lines that the deletions may
+ // have left behind. We do it on the joined string so the
+ // regex sees the actual separator boundaries.
+ joined := strings.Join(out, sep)
+ collapsePattern := regexp.MustCompile(`(?:` + regexp.QuoteMeta(sep) + `){3,}`)
+ joined = collapsePattern.ReplaceAllString(joined, sep+sep)
+ return joined, changed
+}
+
+// writeFileAtomic is shared with uninstall_cursor.go — both
+// callers want the same temp-file-and-rename semantics. Defined
+// there so we don't duplicate the implementation.
diff --git a/cli/internal/coding/uninstall/vendor_config_scrub_test.go b/cli/internal/coding/uninstall/vendor_config_scrub_test.go
new file mode 100644
index 00000000..4c54d938
--- /dev/null
+++ b/cli/internal/coding/uninstall/vendor_config_scrub_test.go
@@ -0,0 +1,277 @@
+package uninstall
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// codexConfigSample is a verbatim slice of a real
+// ~/.codex/config.toml we observed in the wild. Includes every
+// openlit-owned section the install path can write AND non-
+// openlit content that must survive the strip pass — `[features]`,
+// the user-trust `[projects."..."]` entry pointing at the openlit
+// repo (which is NOT an openlit artifact, just a path that happens
+// to contain the substring), unrelated marketplace + plugin
+// entries, an `[mcp_servers.*]` block and its env sub-table, and
+// `[hooks.state]` itself (the bare parent) which Codex regenerates
+// and we must NOT strip.
+const codexConfigSample = `model = "gpt-5.4"
+
+[features]
+multi_agent = true
+
+[projects."/Users/me/private/openlit"]
+trust_level = "trusted"
+
+[marketplaces.openai-bundled]
+last_updated = "2026-05-28T07:58:35Z"
+source_type = "local"
+
+[marketplaces.openlit]
+last_updated = "2026-05-28T12:08:27Z"
+source_type = "local"
+source = "/Users/me/.local/share/openlit/codex-marketplace"
+
+[plugins."documents@openai-primary-runtime"]
+enabled = true
+
+[plugins."openlit@openlit"]
+enabled = true
+
+[desktop]
+ambient-suggestions-enabled = false
+
+[mcp_servers.node_repl]
+args = []
+
+[mcp_servers.node_repl.env]
+CODEX_HOME = "/Users/me/.codex"
+
+[hooks.state]
+
+[hooks.state."openlit@openlit:hooks/hooks.json:post_tool_use:0:0"]
+trusted_hash = "sha256:abc"
+
+[hooks.state."openlit@openlit:hooks/hooks.json:stop:0:0"]
+trusted_hash = "sha256:def"
+`
+
+func TestStripCodexOpenlitSectionsRemovesOnlyOpenlit(t *testing.T) {
+ out, changed := stripCodexOpenlitSections(codexConfigSample)
+ if !changed {
+ t.Fatalf("expected changed=true on a config with openlit sections")
+ }
+
+ mustNotContain := []string{
+ `[marketplaces.openlit]`,
+ `[plugins."openlit@openlit"]`,
+ `[hooks.state."openlit@openlit:hooks/hooks.json:post_tool_use:0:0"]`,
+ `[hooks.state."openlit@openlit:hooks/hooks.json:stop:0:0"]`,
+ `/Users/me/.local/share/openlit/codex-marketplace`,
+ `enabled = true
+[desktop]`, // proxy: the plugin section's body must not survive
+ }
+ for _, needle := range mustNotContain {
+ if strings.Contains(out, needle) {
+ t.Errorf("scrubbed output should not contain %q\n--- output ---\n%s", needle, out)
+ }
+ }
+
+ // Everything else must survive verbatim. Asserting on
+ // specific strings is more useful than a byte-diff because
+ // the test prints which line was lost.
+ mustContain := []string{
+ `model = "gpt-5.4"`,
+ `[features]`,
+ `multi_agent = true`,
+ // User-trust block must NOT be confused with an openlit
+ // section just because the substring "openlit" appears
+ // in the path key.
+ `[projects."/Users/me/private/openlit"]`,
+ `trust_level = "trusted"`,
+ `[marketplaces.openai-bundled]`,
+ `[plugins."documents@openai-primary-runtime"]`,
+ `[mcp_servers.node_repl]`,
+ `[mcp_servers.node_repl.env]`,
+ `CODEX_HOME = "/Users/me/.codex"`,
+ // `[hooks.state]` itself (the parent) is preserved; only
+ // the openlit-keyed children are dropped.
+ `[hooks.state]`,
+ }
+ for _, needle := range mustContain {
+ if !strings.Contains(out, needle) {
+ t.Errorf("scrubbed output should still contain %q\n--- output ---\n%s", needle, out)
+ }
+ }
+}
+
+func TestStripCodexOpenlitSectionsIdempotent(t *testing.T) {
+ // Two passes must yield the same string. Catches a class of
+ // bug where the collapse-blank-lines pass leaves leading or
+ // trailing newlines that the next run would re-collapse.
+ once, _ := stripCodexOpenlitSections(codexConfigSample)
+ twice, changed := stripCodexOpenlitSections(once)
+ if changed {
+ t.Errorf("second pass on already-scrubbed input should report changed=false")
+ }
+ if once != twice {
+ t.Errorf("strip is not idempotent\n--- first ---\n%s\n--- second ---\n%s", once, twice)
+ }
+}
+
+func TestStripCodexOpenlitSectionsNoChange(t *testing.T) {
+ // A config that never had openlit in it must come out byte-
+ // for-byte identical, with changed=false.
+ clean := `model = "gpt-5"
+[features]
+multi_agent = true
+`
+ out, changed := stripCodexOpenlitSections(clean)
+ if changed {
+ t.Errorf("expected changed=false on clean input")
+ }
+ if out != clean {
+ t.Errorf("expected output to equal input verbatim\n--- got ---\n%s", out)
+ }
+}
+
+func TestStripClaudeMarketplaceJSONRemovesOpenlit(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("HOME", dir)
+
+ pluginDir := filepath.Join(dir, ".claude", "plugins")
+ if err := os.MkdirAll(pluginDir, 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ path := filepath.Join(pluginDir, "known_marketplaces.json")
+ initial := map[string]any{
+ "claude-plugins-official": map[string]any{
+ "source": map[string]any{
+ "source": "github",
+ "repo": "anthropics/claude-plugins-official",
+ },
+ "installLocation": "/Users/me/.claude/plugins/marketplaces/claude-plugins-official",
+ "lastUpdated": "2026-05-29T06:53:57.733Z",
+ },
+ "openlit": map[string]any{
+ "source": map[string]any{
+ "source": "directory",
+ "path": "/Users/me/.local/share/openlit/claude-marketplace",
+ },
+ "installLocation": "/Users/me/.local/share/openlit/claude-marketplace",
+ "lastUpdated": "2026-05-28T09:43:10.432Z",
+ },
+ }
+ mustJSONWrite(t, path, initial)
+
+ touched, err := stripClaudeMarketplaceJSON(false)
+ if err != nil {
+ t.Fatalf("strip: %v", err)
+ }
+ if touched != path {
+ t.Errorf("touched = %q, want %q", touched, path)
+ }
+
+ got := mustJSONRead(t, path)
+ if _, ok := got["openlit"]; ok {
+ t.Errorf("openlit entry should have been removed; got %#v", got)
+ }
+ if _, ok := got["claude-plugins-official"]; !ok {
+ t.Errorf("claude-plugins-official entry must survive; got %#v", got)
+ }
+}
+
+func TestStripClaudeMarketplaceJSONNoEntry(t *testing.T) {
+ // File present, no openlit key — must NOT rewrite the file
+ // (and therefore must report touched="").
+ dir := t.TempDir()
+ t.Setenv("HOME", dir)
+ pluginDir := filepath.Join(dir, ".claude", "plugins")
+ if err := os.MkdirAll(pluginDir, 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ path := filepath.Join(pluginDir, "known_marketplaces.json")
+ mustJSONWrite(t, path, map[string]any{
+ "claude-plugins-official": map[string]any{"installLocation": "/x"},
+ })
+ before, _ := os.ReadFile(path)
+
+ touched, err := stripClaudeMarketplaceJSON(false)
+ if err != nil {
+ t.Fatalf("strip: %v", err)
+ }
+ if touched != "" {
+ t.Errorf("touched should be empty when no openlit key; got %q", touched)
+ }
+ after, _ := os.ReadFile(path)
+ if string(before) != string(after) {
+ t.Errorf("file content must be unchanged when no openlit key present")
+ }
+}
+
+func TestStripClaudeMarketplaceJSONMissingFile(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("HOME", dir)
+ touched, err := stripClaudeMarketplaceJSON(false)
+ if err != nil {
+ t.Errorf("missing file should be a no-op, got error: %v", err)
+ }
+ if touched != "" {
+ t.Errorf("touched should be empty for missing file; got %q", touched)
+ }
+}
+
+func TestStripClaudeMarketplaceJSONDryRun(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("HOME", dir)
+ pluginDir := filepath.Join(dir, ".claude", "plugins")
+ if err := os.MkdirAll(pluginDir, 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ path := filepath.Join(pluginDir, "known_marketplaces.json")
+ mustJSONWrite(t, path, map[string]any{
+ "openlit": map[string]any{"installLocation": "/x"},
+ })
+ before, _ := os.ReadFile(path)
+
+ touched, err := stripClaudeMarketplaceJSON(true)
+ if err != nil {
+ t.Fatalf("strip dry-run: %v", err)
+ }
+ if touched != path {
+ t.Errorf("dry-run should still report which file it would touch; got %q", touched)
+ }
+ after, _ := os.ReadFile(path)
+ if string(before) != string(after) {
+ t.Errorf("dry-run must NOT modify the file")
+ }
+}
+
+// --- helpers ----------------------------------------------------
+
+func mustJSONWrite(t *testing.T, path string, v any) {
+ t.Helper()
+ raw, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if err := os.WriteFile(path, append(raw, '\n'), 0o600); err != nil {
+ t.Fatalf("write %s: %v", path, err)
+ }
+}
+
+func mustJSONRead(t *testing.T, path string) map[string]any {
+ t.Helper()
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read %s: %v", path, err)
+ }
+ var out map[string]any
+ if err := json.Unmarshal(raw, &out); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ return out
+}
diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go
new file mode 100644
index 00000000..a1d17bad
--- /dev/null
+++ b/cli/internal/config/config.go
@@ -0,0 +1,522 @@
+// Package config resolves the CLI's runtime configuration from (in order):
+//
+// 1. CLI flags (--otlp-endpoint, --api-key)
+// 2. OPENLIT_* environment variables
+// 3. OTEL_EXPORTER_OTLP_* environment variables (standard OTel fallback)
+// 4. ~/.config/openlit/config.env on Unix, %APPDATA%\openlit\config.env
+// on Windows; honors $XDG_CONFIG_HOME if set. Allow-listed keys; 0600.
+//
+// Keep this dead simple: no eval-style sourcing of arbitrary shell, no
+// secrets in flags' help text. The config file is a flat KEY=VALUE document
+// where only an explicit allow-list of keys is honored.
+package config
+
+import (
+ "bufio"
+ "fmt"
+ "net/url"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+// Resolved holds the effective configuration after all sources are merged.
+type Resolved struct {
+ // OTLPEndpoint is the OTLP/HTTP base URL (e.g. "http://localhost:4318").
+ // Trailing slash and explicit /v1/traces are tolerated; the OTLP
+ // exporter normalizes them.
+ OTLPEndpoint string
+
+ // APIKey, when non-empty, is sent as `Authorization: Bearer <key>`
+ // alongside any OTLPHeaders below.
+ APIKey string
+
+ // OTLPHeaders are extra headers (e.g. parsed from
+ // OTEL_EXPORTER_OTLP_HEADERS=foo=bar,baz=qux). Merged with the
+ // Authorization header derived from APIKey.
+ OTLPHeaders map[string]string
+
+ // Environment / ApplicationName flow into the OTel resource attrs.
+ Environment string
+ ApplicationName string
+
+ // CodingContentCapture is one of "minimal", "metadata_only",
+ // "full". Default is "full" — onboarding feedback was that the
+ // default-on metadata-only mode left users staring at empty
+ // trace detail panes and (correctly) assuming the integration
+ // was broken. The trade-off is that prompt + tool-arg + tool-
+ // result bodies land in your collector verbatim, after tier-1
+ // secret scrubbing. Switch back to "metadata_only" (or
+ // "minimal", which drops per-event spans entirely) when rolling
+ // this out across a team where prompts may carry confidential
+ // material.
+ //
+ // "minimal" emits only session bookends + counters, no
+ // per-event spans; "metadata_only" emits per-event spans
+ // without prompt / tool-arg bodies; "full" includes everything
+ // (still secret-scrubbed).
+ CodingContentCapture string
+
+ // Source records where each value came from for `openlit configure
+ // --show` and debugging.
+ Source map[string]string
+}
+
+// Flags holds the values parsed from CLI flags. Pass an empty struct
+// when invoked from a context that doesn't expose flags.
+type Flags struct {
+ OTLPEndpoint string
+ APIKey string
+}
+
+// Defaults captures hardcoded fallbacks. Kept as a separate struct so
+// tests can replace them without touching env or flags.
+type Defaults struct {
+ OTLPEndpoint string
+ Environment string
+ ApplicationName string
+ CodingContentCapture string
+}
+
+func builtinDefaults() Defaults {
+ return Defaults{
+ OTLPEndpoint: "http://127.0.0.1:4318",
+ Environment: "default",
+ ApplicationName: "openlit-cli",
+ // "full" is the onboarding default: the trace detail view
+ // is unhelpful without prompt + response bodies, and a
+ // missing-content surprise sours first-run UX. Operators
+ // rolling this out at scale can override back to
+ // "metadata_only" via `openlit configure --content-capture`
+ // (or OPENLIT_CODING_CONTENT_CAPTURE). The trace detail UI
+ // also surfaces the toggle inline.
+ CodingContentCapture: "full",
+ }
+}
+
+// Allow-listed keys honored from ~/.config/openlit/config.env. Anything
+// else is silently ignored (we never want this file to be a vector for
+// arbitrary env-injection on the developer's machine).
+var allowedFileKeys = map[string]struct{}{
+ "OPENLIT_OTLP_ENDPOINT": {},
+ "OPENLIT_API_KEY": {},
+ "OPENLIT_ENVIRONMENT": {},
+ "OPENLIT_APPLICATION_NAME": {},
+ "OPENLIT_CODING_CONTENT_CAPTURE": {},
+ "OPENLIT_CODING_REPO_ALLOWLIST": {},
+ "OTEL_EXPORTER_OTLP_ENDPOINT": {},
+ "OTEL_EXPORTER_OTLP_HEADERS": {},
+ "OTEL_RESOURCE_ATTRIBUTES": {},
+}
+
+// PromoteFileToEnv re-exports the config-file values that downstream
+// adapters read directly from os.Getenv (e.g. classifier reading
+// OPENLIT_CODING_REPO_ALLOWLIST). Without this step, values set in
+// ~/.config/openlit/config.env would silently be unavailable to
+// per-vendor adapters that bypass the resolved struct. Existing env
+// vars take precedence so we never override a real shell setting.
+//
+// Secret-shaped keys (currently `OPENLIT_API_KEY`) are deliberately
+// NOT promoted. They live on the Resolved struct and are passed to
+// the OTLP exporter via header injection only. Promoting them to
+// the process env would propagate the key to every grandchild we
+// fork — including the developer's shell when the hook is invoked
+// via `claude code` / `cursor` — which is a needless attack surface
+// and a noisy `env` output for anyone debugging the hook.
+func PromoteFileToEnv() error {
+ vals, err := readConfigFile()
+ if err != nil {
+ return err
+ }
+ for k, v := range vals {
+ if v == "" {
+ continue
+ }
+ if isSecretKey(k) {
+ continue
+ }
+ if _, exists := os.LookupEnv(k); exists {
+ continue
+ }
+ _ = os.Setenv(k, v)
+ }
+ return nil
+}
+
+// isSecretKey reports whether a config key carries secret material
+// that must not be lifted into the process environment. Keep this
+// in sync with the allow-list above (any new sensitive key needs an
+// entry here AND a comment on the consuming side explaining that it
+// stays on the Resolved struct).
+func isSecretKey(k string) bool {
+ switch k {
+ case "OPENLIT_API_KEY":
+ return true
+ }
+ return false
+}
+
+// Load resolves config across all sources.
+//
+// `flags` may be nil when no command-level flags are involved (e.g. the
+// hot-path hook subcommand reads only env + file).
+func Load(flags *Flags) (*Resolved, error) {
+ defaults := builtinDefaults()
+ res := &Resolved{
+ OTLPHeaders: map[string]string{},
+ Source: map[string]string{},
+ }
+
+ // Step 4: file (lowest priority — gets overridden by env and flags).
+ fileVals, err := readConfigFile()
+ if err != nil {
+ return nil, fmt.Errorf("read config file: %w", err)
+ }
+ apply := func(src string, key string, val string) {
+ if val == "" {
+ return
+ }
+ switch key {
+ case "OPENLIT_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_ENDPOINT":
+ res.OTLPEndpoint = val
+ res.Source["otlp_endpoint"] = src
+ case "OPENLIT_API_KEY":
+ res.APIKey = val
+ res.Source["api_key"] = src
+ case "OPENLIT_ENVIRONMENT":
+ res.Environment = val
+ res.Source["environment"] = src
+ case "OPENLIT_APPLICATION_NAME":
+ res.ApplicationName = val
+ res.Source["application_name"] = src
+ case "OPENLIT_CODING_CONTENT_CAPTURE":
+ res.CodingContentCapture = val
+ res.Source["coding_content_capture"] = src
+ case "OTEL_EXPORTER_OTLP_HEADERS":
+ for k, v := range parseOTLPHeaders(val) {
+ res.OTLPHeaders[k] = v
+ }
+ res.Source["otlp_headers"] = src
+ }
+ }
+
+ for k, v := range fileVals {
+ apply("file", k, v)
+ }
+
+ // Step 3: standard OTel env vars.
+ for _, k := range []string{
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
+ "OTEL_EXPORTER_OTLP_HEADERS",
+ } {
+ if v := os.Getenv(k); v != "" {
+ apply("env_otel", k, v)
+ }
+ }
+
+ // Step 2: OPENLIT_* env vars (override OTel ones).
+ for _, k := range []string{
+ "OPENLIT_OTLP_ENDPOINT",
+ "OPENLIT_API_KEY",
+ "OPENLIT_ENVIRONMENT",
+ "OPENLIT_APPLICATION_NAME",
+ "OPENLIT_CODING_CONTENT_CAPTURE",
+ } {
+ if v := os.Getenv(k); v != "" {
+ apply("env_openlit", k, v)
+ }
+ }
+
+ // Step 1: flags (highest priority).
+ if flags != nil {
+ if flags.OTLPEndpoint != "" {
+ res.OTLPEndpoint = flags.OTLPEndpoint
+ res.Source["otlp_endpoint"] = "flag"
+ }
+ if flags.APIKey != "" {
+ res.APIKey = flags.APIKey
+ res.Source["api_key"] = "flag"
+ }
+ }
+
+ // Apply defaults for anything still empty.
+ if res.OTLPEndpoint == "" {
+ res.OTLPEndpoint = defaults.OTLPEndpoint
+ res.Source["otlp_endpoint"] = "default"
+ }
+ if res.Environment == "" {
+ res.Environment = defaults.Environment
+ res.Source["environment"] = "default"
+ }
+ if res.ApplicationName == "" {
+ res.ApplicationName = defaults.ApplicationName
+ res.Source["application_name"] = "default"
+ }
+ if res.CodingContentCapture == "" {
+ res.CodingContentCapture = defaults.CodingContentCapture
+ res.Source["coding_content_capture"] = "default"
+ }
+
+ // Sanity-check the endpoint once so later code doesn't have to.
+ if _, err := url.Parse(res.OTLPEndpoint); err != nil {
+ return nil, fmt.Errorf("invalid OTLP endpoint %q: %w", res.OTLPEndpoint, err)
+ }
+
+ // Quietly upgrade scheme-less or http:// endpoints to https://
+ // when the host is non-loopback. The CLI ships an API key in
+ // the Authorization header on every OTLP request; sending that
+ // in plaintext over a public network is the single highest-impact
+ // security regression we can prevent at config-resolution time.
+ // Loopback / RFC1918 hosts are preserved as-is so local devs and
+ // in-cluster collectors keep working without TLS.
+ res.OTLPEndpoint = upgradeScheme(res.OTLPEndpoint)
+
+ return res, nil
+}
+
+// upgradeScheme rewrites the OTLP endpoint to https:// when the host
+// looks non-local. Inputs without a scheme are interpreted as host
+// strings (e.g. `otel.example.com:4318` -> `https://otel.example.com:4318`).
+// Empty input returns "" unchanged.
+func upgradeScheme(endpoint string) string {
+ if endpoint == "" {
+ return endpoint
+ }
+ raw := endpoint
+ if !strings.Contains(raw, "://") {
+ raw = "//" + raw
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.Host == "" {
+ return endpoint
+ }
+ host := u.Hostname()
+ if isLocalHost(host) {
+ // Default to http for loopback if no scheme; preserve any
+ // explicit scheme the operator passed.
+ if u.Scheme == "" {
+ u.Scheme = "http"
+ return u.String()
+ }
+ return endpoint
+ }
+ switch strings.ToLower(u.Scheme) {
+ case "", "http":
+ u.Scheme = "https"
+ return u.String()
+ default:
+ return endpoint
+ }
+}
+
+// isLocalHost recognises the host strings we treat as trusted-network
+// for the purposes of the https-upgrade rule.
+func isLocalHost(host string) bool {
+ if host == "" {
+ return true
+ }
+ switch strings.ToLower(host) {
+ case "localhost", "127.0.0.1", "::1", "0.0.0.0":
+ return true
+ }
+ // RFC1918 / link-local: treat as local. These are the same prefixes
+ // kube-internal collectors usually live on, so they stay http://.
+ for _, prefix := range []string{
+ "10.",
+ "192.168.",
+ "169.254.",
+ } {
+ if strings.HasPrefix(host, prefix) {
+ return true
+ }
+ }
+ // 172.16.0.0/12 — slightly fiddly; check the second octet range.
+ if strings.HasPrefix(host, "172.") {
+ var oct int
+ _, _ = fmt.Sscanf(host, "172.%d.", &oct)
+ if oct >= 16 && oct <= 31 {
+ return true
+ }
+ }
+ return false
+}
+
+// Path returns the absolute path to the config file, even if it doesn't
+// yet exist. Used by `openlit configure` for write-side and by Load for
+// read-side.
+func Path() (string, error) {
+ dir, err := configDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(dir, "config.env"), nil
+}
+
+// configDir returns the directory that holds config.env. Honors
+// XDG_CONFIG_HOME, falling back to $HOME/.config/openlit/. We do not
+// path-traverse the value — env that contains ".." or absolute paths is
+// taken at face value here; the consumer (Load/Save) only reads/writes
+// the explicit "config.env" leaf which can't escape via traversal.
+func configDir() (string, error) {
+ if x := os.Getenv("XDG_CONFIG_HOME"); x != "" {
+ return filepath.Join(x, "openlit"), nil
+ }
+ // On Windows the idiomatic config root is %APPDATA% (Roaming).
+ // os.UserConfigDir returns exactly that on Windows, whereas on
+ // macOS/Linux it returns paths we deliberately do NOT want
+ // (~/Library/Application Support and ~/.config respectively —
+ // the latter matches but is also what we already use, and on
+ // macOS we want the XDG-style ~/.config/openlit/ for parity with
+ // Linux so users moving between hosts find the same file).
+ if runtime.GOOS == "windows" {
+ if cfg, err := os.UserConfigDir(); err == nil && cfg != "" {
+ return filepath.Join(cfg, "openlit"), nil
+ }
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("could not resolve home directory: %w", err)
+ }
+ return filepath.Join(home, ".config", "openlit"), nil
+}
+
+// readConfigFile parses ~/.config/openlit/config.env if it exists. Returns
+// an empty map (no error) if the file is missing — that's the expected
+// state on a fresh install.
+func readConfigFile() (map[string]string, error) {
+ path, err := Path()
+ if err != nil {
+ return nil, err
+ }
+ f, err := os.Open(path) //nolint:gosec // path is constructed from $HOME, not user input
+ if os.IsNotExist(err) {
+ return map[string]string{}, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close() //nolint:errcheck
+
+ out := map[string]string{}
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ line := strings.TrimSpace(sc.Text())
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ key, val, ok := strings.Cut(line, "=")
+ if !ok {
+ continue
+ }
+ key = strings.TrimSpace(key)
+ val = strings.TrimSpace(val)
+ val = strings.Trim(val, `"'`)
+ if _, allowed := allowedFileKeys[key]; !allowed {
+ continue
+ }
+ out[key] = val
+ }
+ if err := sc.Err(); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Save writes the supplied key/value pairs to ~/.config/openlit/config.env
+// with mode 0600. Existing keys are preserved unless overridden; unknown
+// (non-allowlisted) keys are dropped silently.
+func Save(updates map[string]string) (string, error) {
+ path, err := Path()
+ if err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ return "", err
+ }
+
+ existing, err := readConfigFile()
+ if err != nil {
+ return "", err
+ }
+ for k, v := range updates {
+ if _, ok := allowedFileKeys[k]; !ok {
+ continue
+ }
+ if v == "" {
+ delete(existing, k)
+ continue
+ }
+ existing[k] = v
+ }
+
+ // Stable ordering: sort keys alphabetically so diffs are clean.
+ var lines []string
+ lines = append(lines,
+ "# openlit CLI config — written by `openlit configure`.",
+ "# Allow-listed keys only; anything else is ignored at read time.",
+ "",
+ )
+ keys := make([]string, 0, len(existing))
+ for k := range existing {
+ keys = append(keys, k)
+ }
+ sortStrings(keys)
+ for _, k := range keys {
+ lines = append(lines, fmt.Sprintf("%s=%s", k, existing[k]))
+ }
+
+ body := strings.Join(lines, "\n") + "\n"
+ if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
+ return "", err
+ }
+ return path, nil
+}
+
+// parseOTLPHeaders reads the comma-separated `k=v,k=v` form used by
+// OTEL_EXPORTER_OTLP_HEADERS.
+func parseOTLPHeaders(s string) map[string]string {
+ out := map[string]string{}
+ for _, part := range strings.Split(s, ",") {
+ part = strings.TrimSpace(part)
+ if part == "" {
+ continue
+ }
+ k, v, ok := strings.Cut(part, "=")
+ if !ok {
+ continue
+ }
+ k = strings.TrimSpace(k)
+ v = strings.TrimSpace(v)
+ if k == "" {
+ continue
+ }
+ out[k] = v
+ }
+ return out
+}
+
+// EffectiveHeaders merges the API-key-derived Authorization header with
+// any OTLPHeaders set explicitly via env. Kept as a small helper so the
+// OTLP exporter and `openlit configure --show` agree on one truth.
+func (r *Resolved) EffectiveHeaders() map[string]string {
+ out := map[string]string{}
+ for k, v := range r.OTLPHeaders {
+ out[k] = v
+ }
+ if r.APIKey != "" {
+ out["Authorization"] = "Bearer " + r.APIKey
+ }
+ return out
+}
+
+// sortStrings is an inline sort helper to avoid pulling in the `sort`
+// package indirectly via the test-runner; the cost is one tiny function.
+func sortStrings(s []string) {
+ // Insertion sort — list is always small (<20 keys).
+ for i := 1; i < len(s); i++ {
+ for j := i; j > 0 && s[j-1] > s[j]; j-- {
+ s[j-1], s[j] = s[j], s[j-1]
+ }
+ }
+}
diff --git a/cli/internal/configure/configure.go b/cli/internal/configure/configure.go
new file mode 100644
index 00000000..6b7edb85
--- /dev/null
+++ b/cli/internal/configure/configure.go
@@ -0,0 +1,132 @@
+// Package configure implements the `openlit configure` subcommand.
+//
+// Writes the allow-listed subset of config to ~/.config/openlit/config.env
+// (mode 0600). Reads the same file via the shared internal/config package
+// for the --show variant.
+package configure
+
+import (
+ "fmt"
+
+ "github.com/openlit/openlit/cli/internal/config"
+ "github.com/spf13/cobra"
+)
+
+// NewCmd returns the cobra `configure` subcommand.
+func NewCmd() *cobra.Command {
+ var (
+ endpoint string
+ apiKey string
+ environment string
+ appName string
+ capture string
+ show bool
+ )
+
+ cmd := &cobra.Command{
+ Use: "configure",
+ Short: "Configure the openlit CLI (writes ~/.config/openlit/config.env)",
+ Long: `Configure the openlit CLI's persistent settings.
+
+Examples:
+
+ openlit configure --endpoint https://otlp.openlit.example.com --api-key sk_...
+ openlit configure --environment staging
+ openlit configure --show
+
+The file is written with mode 0600. Only an explicit allow-list of keys is
+honored; anything else is silently ignored. Per-invocation env vars and
+flags always take precedence over the file at runtime.`,
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ if show {
+ return runShow(cmd)
+ }
+ return runWrite(cmd, endpoint, apiKey, environment, appName, capture)
+ },
+ }
+
+ cmd.Flags().StringVar(&endpoint, "endpoint", "", "OTLP/HTTP endpoint URL (e.g. http://localhost:4318)")
+ cmd.Flags().StringVar(&apiKey, "api-key", "", "API key sent as `Authorization: Bearer <key>`")
+ cmd.Flags().StringVar(&environment, "environment", "", "Deployment environment (e.g. production, staging)")
+ cmd.Flags().StringVar(&appName, "application-name", "", "Application name (default: openlit-cli)")
+ cmd.Flags().StringVar(&capture, "content-capture", "", "Coding-agent content capture mode: minimal | metadata_only | full")
+ cmd.Flags().BoolVar(&show, "show", false, "Print effective resolved configuration without writing anything")
+
+ return cmd
+}
+
+func runWrite(cmd *cobra.Command, endpoint, apiKey, env, app, capture string) error {
+ updates := map[string]string{}
+ if endpoint != "" {
+ updates["OPENLIT_OTLP_ENDPOINT"] = endpoint
+ }
+ if apiKey != "" {
+ updates["OPENLIT_API_KEY"] = apiKey
+ }
+ if env != "" {
+ updates["OPENLIT_ENVIRONMENT"] = env
+ }
+ if app != "" {
+ updates["OPENLIT_APPLICATION_NAME"] = app
+ }
+ if capture != "" {
+ switch capture {
+ case "minimal", "metadata_only", "full":
+ default:
+ return fmt.Errorf("invalid --content-capture %q (allowed: minimal, metadata_only, full)", capture)
+ }
+ updates["OPENLIT_CODING_CONTENT_CAPTURE"] = capture
+ }
+
+ if len(updates) == 0 {
+ return fmt.Errorf("nothing to write — pass at least one of --endpoint / --api-key / --environment / --application-name / --content-capture (or use --show)")
+ }
+
+ path, err := config.Save(updates)
+ if err != nil {
+ return fmt.Errorf("save config: %w", err)
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "openlit: wrote %d setting(s) to %s\n", len(updates), path)
+ return nil
+}
+
+func runShow(cmd *cobra.Command) error {
+ res, err := config.Load(nil)
+ if err != nil {
+ return err
+ }
+ out := cmd.OutOrStdout()
+ fmt.Fprintln(out, "Effective configuration:")
+ fmt.Fprintf(out, " otlp_endpoint = %s (source: %s)\n", res.OTLPEndpoint, sourceOf(res, "otlp_endpoint"))
+ fmt.Fprintf(out, " api_key = %s (source: %s)\n", redact(res.APIKey), sourceOf(res, "api_key"))
+ fmt.Fprintf(out, " environment = %s (source: %s)\n", res.Environment, sourceOf(res, "environment"))
+ fmt.Fprintf(out, " application_name = %s (source: %s)\n", res.ApplicationName, sourceOf(res, "application_name"))
+ fmt.Fprintf(out, " coding_content_capture = %s (source: %s)\n", res.CodingContentCapture, sourceOf(res, "coding_content_capture"))
+ if len(res.OTLPHeaders) > 0 {
+ fmt.Fprintf(out, " otlp_headers (extra) = %d header(s) (source: %s)\n", len(res.OTLPHeaders), sourceOf(res, "otlp_headers"))
+ }
+ path, _ := config.Path()
+ fmt.Fprintf(out, "\nConfig file: %s\n", path)
+ return nil
+}
+
+func sourceOf(r *config.Resolved, key string) string {
+ if v, ok := r.Source[key]; ok {
+ return v
+ }
+ return "default"
+}
+
+// redact returns "(unset)" for empty, otherwise "<first 4 chars>****" so
+// `--show` is safe to paste into a screenshot or chat.
+func redact(s string) string {
+ if s == "" {
+ return "(unset)"
+ }
+ if len(s) <= 4 {
+ return "****"
+ }
+ return s[:4] + "****"
+}
diff --git a/cli/internal/doctor/doctor.go b/cli/internal/doctor/doctor.go
new file mode 100644
index 00000000..3c989c49
--- /dev/null
+++ b/cli/internal/doctor/doctor.go
@@ -0,0 +1,264 @@
+// Package doctor implements `openlit doctor` — a one-shot self-check
+// that prints the active configuration, verifies the OTLP endpoint
+// is reachable, and lists installed coding-agent vendor plugins.
+//
+// Intended use: "my chats aren't appearing in the dashboard, what's
+// wrong?". A doctor invocation answers that in <2s without the user
+// having to grep their shell rc files or stare at hook subprocess
+// logs.
+//
+// Doctor is intentionally read-only: it never edits config, never
+// installs anything, never sends telemetry. Output goes to stdout
+// in a single human-readable block plus a final line:
+//
+// openlit doctor: ok
+// openlit doctor: ok with warnings
+// openlit doctor: failed
+//
+// Exit code is 0 for ok / ok-with-warnings and 1 for failed, so a
+// CI pipeline that wraps `openlit doctor` can gate on it.
+package doctor
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/config"
+ "github.com/openlit/openlit/cli/internal/version"
+ "github.com/spf13/cobra"
+)
+
+// NewCmd returns the cobra command for `openlit doctor`.
+func NewCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "doctor",
+ Short: "Diagnose openlit's setup (config, OTLP reachability, plugins)",
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: run,
+ }
+}
+
+func run(cmd *cobra.Command, _ []string) error {
+ out := cmd.OutOrStdout()
+ warnings := 0
+ failed := 0
+
+ fmt.Fprintf(out, "openlit %s\n", version.Version)
+ if version.Commit != "" {
+ fmt.Fprintf(out, " commit: %s\n", version.Commit)
+ }
+
+ fmt.Fprintln(out)
+ fmt.Fprintln(out, "Configuration")
+ cfg, err := config.Load(nil)
+ if err != nil {
+ fmt.Fprintf(out, " ERROR: load: %v\n", err)
+ failed++
+ } else {
+ fmt.Fprintf(out, " otlp_endpoint: %s\n", maskEmpty(cfg.OTLPEndpoint))
+ fmt.Fprintf(out, " api_key_set: %v\n", cfg.APIKey != "")
+ fmt.Fprintf(out, " environment: %s\n", maskEmpty(cfg.Environment))
+ fmt.Fprintf(out, " application_name: %s\n", maskEmpty(cfg.ApplicationName))
+ fmt.Fprintf(out, " content_capture_mode: %s\n", maskEmpty(cfg.CodingContentCapture))
+ if cfg.OTLPEndpoint == "" {
+ fmt.Fprintln(out, " WARN: OTLP endpoint is empty — telemetry won't ship.")
+ warnings++
+ }
+ }
+
+ fmt.Fprintln(out)
+ fmt.Fprintln(out, "OTLP reachability")
+ if cfg != nil && cfg.OTLPEndpoint != "" {
+ host, port, ok := splitOTLP(cfg.OTLPEndpoint)
+ if !ok {
+ fmt.Fprintf(out, " WARN: couldn't parse OTLP endpoint %q\n", cfg.OTLPEndpoint)
+ warnings++
+ } else {
+ start := time.Now()
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ d := net.Dialer{Timeout: 2 * time.Second}
+ conn, derr := d.DialContext(ctx, "tcp", net.JoinHostPort(host, port))
+ elapsed := time.Since(start).Round(time.Millisecond)
+ if derr != nil {
+ fmt.Fprintf(out, " FAIL: tcp dial %s:%s in %s — %v\n", host, port, elapsed, derr)
+ failed++
+ } else {
+ _ = conn.Close()
+ fmt.Fprintf(out, " ok: tcp dial %s:%s in %s\n", host, port, elapsed)
+ }
+ }
+ } else {
+ fmt.Fprintln(out, " skipped: no endpoint configured")
+ }
+
+ fmt.Fprintln(out)
+ fmt.Fprintln(out, "Coding-agent plugins")
+ plugins := detectInstalledPlugins()
+ if len(plugins) == 0 {
+ fmt.Fprintln(out, " WARN: no vendor plugin install marker found.")
+ fmt.Fprintln(out, " Run `openlit coding install --vendor=cursor` (or claude-code / codex).")
+ warnings++
+ }
+ for _, p := range plugins {
+ fmt.Fprintf(out, " %s: %s\n", p.vendor, p.path)
+ }
+
+ fmt.Fprintln(out)
+ fmt.Fprintln(out, "Session cache")
+ if cache := sessionCachePath(); cache != "" {
+ entries := countDirEntries(cache)
+ fmt.Fprintf(out, " %s — %d cached sessions\n", cache, entries)
+ } else {
+ fmt.Fprintln(out, " WARN: couldn't resolve user cache dir")
+ warnings++
+ }
+
+ fmt.Fprintln(out)
+ switch {
+ case failed > 0:
+ fmt.Fprintln(out, "openlit doctor: failed")
+ return fmt.Errorf("doctor: %d failure(s), %d warning(s)", failed, warnings)
+ case warnings > 0:
+ fmt.Fprintf(out, "openlit doctor: ok with %d warning(s)\n", warnings)
+ default:
+ fmt.Fprintln(out, "openlit doctor: ok")
+ }
+ return nil
+}
+
+func maskEmpty(s string) string {
+ if s == "" {
+ return "(unset)"
+ }
+ return s
+}
+
+// splitOTLP parses `OTLPEndpoint` and returns the (host, port) pair we
+// should dial for reachability. Defaults the port for http/https
+// when unspecified.
+func splitOTLP(endpoint string) (string, string, bool) {
+ u, err := url.Parse(endpoint)
+ if err != nil || u.Host == "" {
+ return "", "", false
+ }
+ host := u.Hostname()
+ port := u.Port()
+ if port == "" {
+ switch strings.ToLower(u.Scheme) {
+ case "https":
+ port = "443"
+ default:
+ port = "80"
+ }
+ }
+ return host, port, true
+}
+
+// installedPlugin is a single (vendor, marker file) detection result
+// surfaced by `openlit doctor`.
+type installedPlugin struct {
+ vendor string
+ path string
+}
+
+// detectInstalledPlugins probes the openlit-specific markers each
+// vendor's install routine writes — not the vendor's own root
+// directory, which exists whenever the vendor itself is installed
+// regardless of openlit. False positives there made doctor report
+// "cursor: installed" for any Cursor user who had never run `openlit
+// coding install --vendor=cursor`.
+//
+// Markers are sourced from cli/internal/coding/install:
+// - cursor: ~/.cursor/hooks.json containing an `openlit coding hook`
+// command (the install routine merges entries into the
+// user's hooks.json, which may pre-exist with other tools).
+// - claude-code: ~/.claude/plugins/openlit-cc/.claude-plugin/plugin.json,
+// created only by the openlit install.
+// - codex: ~/.local/share/openlit/codex-marketplace/, the local
+// marketplace tree that `openlit coding install --vendor=codex`
+// materializes and registers with codex.
+func detectInstalledPlugins() []installedPlugin {
+ home, err := os.UserHomeDir()
+ if err != nil || home == "" {
+ return nil
+ }
+ candidates := []struct {
+ vendor string
+ path string
+ // verify, when set, is run on the file's contents after a
+ // successful stat. The plugin counts as installed only when
+ // verify returns true. Used for cursor, where the hooks.json
+ // file may belong to another tool entirely.
+ verify func([]byte) bool
+ }{
+ {
+ vendor: "cursor",
+ path: filepath.Join(home, ".cursor", "hooks.json"),
+ verify: func(b []byte) bool {
+ return strings.Contains(string(b), "openlit coding hook") ||
+ strings.Contains(string(b), "/.openlit/")
+ },
+ },
+ {
+ vendor: "claude-code",
+ path: filepath.Join(home, ".claude", "plugins", "openlit-cc", ".claude-plugin", "plugin.json"),
+ },
+ {
+ vendor: "codex",
+ path: filepath.Join(home, ".local", "share", "openlit", "codex-marketplace"),
+ },
+ }
+ var out []installedPlugin
+ for _, c := range candidates {
+ info, err := os.Stat(c.path)
+ if err != nil {
+ continue
+ }
+ if c.verify != nil {
+ if info.IsDir() {
+ continue
+ }
+ body, err := os.ReadFile(c.path)
+ if err != nil || !c.verify(body) {
+ continue
+ }
+ }
+ out = append(out, installedPlugin{vendor: c.vendor, path: c.path})
+ }
+ return out
+}
+
+// sessionCachePath returns the directory the hook subcommand stores
+// per-session state in. Empty string when os.UserCacheDir fails.
+func sessionCachePath() string {
+ root, err := os.UserCacheDir()
+ if err != nil || root == "" {
+ return ""
+ }
+ return filepath.Join(root, "openlit", "sessions")
+}
+
+// countDirEntries returns the number of regular files directly inside
+// dir, ignoring the .lock siblings. Zero on error.
+func countDirEntries(dir string) int {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return 0
+ }
+ n := 0
+ for _, e := range entries {
+ if e.IsDir() || strings.HasSuffix(e.Name(), ".lock") {
+ continue
+ }
+ n++
+ }
+ return n
+}
diff --git a/cli/internal/otlp/attrs.go b/cli/internal/otlp/attrs.go
new file mode 100644
index 00000000..a6d32762
--- /dev/null
+++ b/cli/internal/otlp/attrs.go
@@ -0,0 +1,662 @@
+// Helpers that translate normalize.* values into OTel attributes. Kept
+// in their own file so exporter.go stays small.
+//
+// Every string-typed attribute funnels through the supplied scrub
+// function (a no-op-friendly closure from internal/redact). Numeric and
+// boolean attributes go through unscrubbed since they can't carry
+// secrets in any meaningful way.
+//
+// Capture-mode matrix (Phase C):
+//
+// +-----------------------------+---------+-----------+----------+
+// | attribute family | minimal | metadata | full |
+// +-----------------------------+---------+-----------+----------+
+// | session-root timings/cost | ✓ | ✓ | ✓ |
+// | session-root identity (user)| ✓ | ✓ | ✓ |
+// | coding_agent.session.id + | ✓ | ✓ | ✓ |
+// | gen_ai.conversation.id | | | |
+// | repo url / branch / commit | ✓ | ✓ | ✓ |
+// | per-event spans | ─ | ✓ | ✓ |
+// | tool.name + duration + cost | ─ | ✓ | ✓ |
+// | tool.command (first token) | ─ | ✓ (head) | ✓ (full) |
+// | tool args / tool result | ─ | ─ | ✓ |
+// | llm.turn timings + tokens | ─ | ✓ | ✓ |
+// | llm.turn prompt / response | ─ | ─ | ✓ |
+// | llm.turn.thought text | ─ | ─ | ✓ |
+// | coding_agent.content_capture| ✓ | ✓ | ✓ |
+// | resource attribute | | | |
+// +-----------------------------+---------+-----------+----------+
+//
+// The matrix is enforced by:
+// - exporter.go's Emit* methods: in minimal mode, EmitToolCall /
+// EmitLLMTurn / EmitSubagent / EmitEditDecision / EmitEvent become
+// no-ops at the span level and instead bump a counter on the
+// sessionstate cache; the final EmitSession reads the counters
+// onto the session-root span (see C3).
+// - setToolCallAttrs / setLLMTurnAttrs / setSubagentAttrs accept the
+// mode and gate body attributes through `bodyAllowed`.
+
+package otlp
+
+import (
+ "encoding/json"
+ "strings"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/sdk/go/semconv"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/codes"
+ "go.opentelemetry.io/otel/trace"
+)
+
+// scrubFn is the redactor signature emitter passes around. Equivalent
+// to internal/redact.ForCapture's return type but redeclared locally so
+// this file doesn't depend on the redact package.
+type scrubFn func(string) string
+
+// bodyAllowed returns true when the active capture mode permits
+// prompt / response / tool-argument bodies on a span. Centralised
+// here so a future mode (e.g. "redacted_full") only needs to update
+// this single switch.
+func bodyAllowed(mode string) bool {
+ return mode == semconv.CodingAgentContentCaptureFull
+}
+
+// perEventSpansAllowed returns true when the active capture mode
+// permits emitting per-event spans (tool.call, llm.turn, subagent,
+// edit.decision, and events). Minimal mode collapses these into
+// rolled-up counters on the session-root span.
+func perEventSpansAllowed(mode string) bool {
+ return mode != semconv.CodingAgentContentCaptureMinimal
+}
+
+// inferProvider returns the OTel-standard `gen_ai.system` value based
+// on the model name and (as a last resort) the vendor. We deliberately
+// only handle the model families our adapters report; everything else
+// gets the empty string so dashboards know not to render a misleading
+// system value. Extend as we add more agents.
+func inferProvider(model, vendor string) string {
+ m := strings.ToLower(model)
+ switch {
+ case strings.HasPrefix(m, "claude"), strings.HasPrefix(m, "anthropic/"):
+ return "anthropic"
+ case strings.HasPrefix(m, "gpt"), strings.HasPrefix(m, "o1"),
+ strings.HasPrefix(m, "o3"), strings.HasPrefix(m, "o4"),
+ strings.HasPrefix(m, "openai/"):
+ return "openai"
+ case strings.HasPrefix(m, "gemini"), strings.HasPrefix(m, "google/"):
+ return "google"
+ case strings.HasPrefix(m, "grok"):
+ return "xai"
+ case strings.HasPrefix(m, "deepseek"):
+ return "deepseek"
+ }
+ switch strings.ToLower(vendor) {
+ case "claude-code", "claudecode", "cc":
+ return "anthropic"
+ case "codex":
+ return "openai"
+ }
+ return ""
+}
+
+func setSessionAttrs(span trace.Span, s normalize.Session, scrub scrubFn) {
+ span.SetAttributes(
+ attribute.String(semconv.CodingAgentHookSchemaVersion, semconv.CodingAgentSchemaVersion),
+ )
+ setStr(span, semconv.CodingAgentSessionID, s.SessionID, scrub)
+ setStr(span, semconv.GenAIConversationID, s.ConversationID, scrub)
+ if s.Vendor != "" {
+ setStr(span, semconv.CodingAgentClient, s.Vendor, scrub)
+ setStr(span, "gen_ai.agent.name", s.Vendor, scrub)
+ }
+ setStr(span, semconv.CodingAgentClientVersion, s.ClientVersion, scrub)
+
+ if s.Model != "" {
+ setStr(span, semconv.GenAIRequestModel, s.Model, scrub)
+ setStr(span, semconv.GenAIResponseModel, s.Model, scrub)
+ }
+ if s.Provider != "" {
+ // Dual-stamp until every downstream consumer is on
+ // gen_ai.provider.name. See sdk/go/semconv/genai.go for the
+ // rationale — OTel 1.36 renamed `gen_ai.system` and we want
+ // both keys present during the transition window.
+ setStr(span, semconv.GenAISystem, s.Provider, scrub)
+ setStr(span, semconv.GenAIProviderName, s.Provider, scrub)
+ }
+
+ setStr(span, semconv.CodingAgentSessionOutcome, s.Outcome, scrub)
+ if s.Duration > 0 {
+ span.SetAttributes(attribute.Int64(
+ semconv.CodingAgentSessionDurationMs, s.Duration.Milliseconds(),
+ ))
+ }
+ if s.ToolCallCount > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionToolCallCount, s.ToolCallCount))
+ }
+ if s.SubagentCount > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionSubagentCount, s.SubagentCount))
+ }
+ if s.CostUSD > 0 {
+ span.SetAttributes(attribute.Float64(semconv.CodingAgentSessionCostUSD, s.CostUSD))
+ span.SetAttributes(attribute.Float64(semconv.GenAIUsageCost, s.CostUSD))
+ }
+ if s.InputTokens > 0 {
+ span.SetAttributes(attribute.Int64(semconv.GenAIUsageInputTokens, s.InputTokens))
+ }
+ if s.OutputTokens > 0 {
+ span.SetAttributes(attribute.Int64(semconv.GenAIUsageOutputTokens, s.OutputTokens))
+ }
+ if s.TotalTokens > 0 {
+ span.SetAttributes(attribute.Int64(semconv.GenAIUsageTotalTokens, s.TotalTokens))
+ }
+
+ // Code-change rollups — always stamped onto the session-root span
+ // regardless of content-capture mode. Line / accept / reject /
+ // commit / pr counts are scalar telemetry, not user content, so
+ // minimal mode keeps them; otherwise dashboards lose the most
+ // useful column on the Sessions list.
+ if s.LinesAdded > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionLinesAdded, s.LinesAdded))
+ }
+ if s.LinesRemoved > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionLinesRemoved, s.LinesRemoved))
+ }
+ if s.LinesAccepted > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionLinesAccepted, s.LinesAccepted))
+ }
+ if s.LinesRejected > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionLinesRejected, s.LinesRejected))
+ }
+ if s.EditAcceptCount > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionEditAcceptCount, s.EditAcceptCount))
+ }
+ if s.EditRejectCount > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionEditRejectCount, s.EditRejectCount))
+ }
+ if s.CommitCount > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionCommitCount, s.CommitCount))
+ }
+ if s.PRCount > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentSessionPRCount, s.PRCount))
+ }
+
+ // VCS bridging — use OTel-standard vcs.* keys for the values that
+ // have standard equivalents, plus our own coding_agent.vcs.dirty
+ // boolean for the v1 metric.
+ setStr(span, "vcs.repository.url.full", s.RepoURL, scrub)
+ setStr(span, "vcs.ref.head.revision", s.HeadSHA, scrub)
+ setStr(span, "vcs.ref.head.name", s.BranchName, scrub)
+ if s.HeadSHA != "" {
+ // Boolean is stamped only when we have any VCS context at all,
+ // otherwise dashboards would see a column of `false` from
+ // invocations outside any repo.
+ span.SetAttributes(attribute.Bool(semconv.CodingAgentVCSDirty, s.VCSDirty))
+ }
+
+ // Identity / classification.
+ if s.UserID != "" {
+ setStr(span, semconv.GenAIRequestUser, s.UserID, scrub)
+ }
+ setStr(span, semconv.CodingAgentUserClassification, s.UserClassification, scrub)
+ setStr(span, semconv.CodingAgentUserClassificationReason, s.ClassificationReason, scrub)
+ setStr(span, semconv.CodingAgentPolicyPermissionMode, s.PermissionMode, scrub)
+ setStr(span, "code.cwd", s.CWD, scrub)
+
+ for k, v := range s.Extras {
+ setStr(span, k, v, scrub)
+ }
+}
+
+func setToolCallAttrs(span trace.Span, t normalize.ToolCall, scrub scrubFn, capture string) {
+ span.SetAttributes(attribute.String(semconv.CodingAgentHookSchemaVersion, semconv.CodingAgentSchemaVersion))
+ setStr(span, semconv.CodingAgentSessionID, t.SessionID, scrub)
+ setStr(span, semconv.CodingAgentAgentID, t.AgentID, scrub)
+ // OTel GenAI canonical op.name for tool spans. Without this the
+ // GenAI dashboards can't classify the span as a tool execution
+ // (they fall through to "internal" and the tool-latency widget
+ // goes blank).
+ setStr(span, semconv.GenAIOperationName, "execute_tool", scrub)
+ setStr(span, semconv.GenAIToolName, t.ToolName, scrub)
+ setStr(span, semconv.GenAIToolCallID, t.ToolUseID, scrub)
+ setStr(span, semconv.CodingAgentToolGroupID, t.GroupID, scrub)
+ setStr(span, semconv.CodingAgentToolGroupType, t.GroupType, scrub)
+ if t.Iteration > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentToolIteration, t.Iteration))
+ }
+ setStr(span, semconv.CodingAgentToolTriggeringLLMRequestID, t.TriggeringLLMRequestID, scrub)
+ if t.Model != "" {
+ setStr(span, semconv.GenAIRequestModel, t.Model, scrub)
+ }
+ if t.Sandboxed {
+ span.SetAttributes(attribute.Bool("coding_agent.tool.sandboxed", true))
+ }
+ if t.WorkingDir != "" {
+ setStr(span, "code.cwd", t.WorkingDir, scrub)
+ }
+ if t.Command != "" {
+ // In metadata / minimal modes the adapter has already
+ // trimmed `Command` to the binary head via
+ // commandForMode (cursor/handle.go). Re-apply truncation
+ // at full mode only.
+ if bodyAllowed(capture) {
+ setStr(span, "coding_agent.tool.command", truncate(t.Command, 4096), scrub)
+ } else {
+ setStr(span, "coding_agent.tool.command", truncate(t.Command, 256), scrub)
+ }
+ }
+
+ setStr(span, semconv.CodingAgentMCPServerName, t.MCPServerName, scrub)
+ setStr(span, semconv.CodingAgentMCPScope, t.MCPScope, scrub)
+ setStr(span, semconv.CodingAgentMCPTransport, t.MCPTransport, scrub)
+ setStr(span, semconv.CodingAgentMCPSource, t.MCPSource, scrub)
+ setStr(span, semconv.CodingAgentClient, t.Vendor, scrub)
+
+ if t.Errored {
+ // Stamp the boolean alongside the error.type string so
+ // dashboards filtering on `errored = true` work without
+ // the implicit "error.type non-empty" idiom (which fires
+ // false positives on shell tools that surface stderr but
+ // completed successfully).
+ span.SetAttributes(attribute.Bool("coding_agent.tool.errored", true))
+ setStr(span, semconv.ErrorType, nonEmpty(t.FailureType, "tool_error"), scrub)
+ setStr(span, "exception.message", truncate(t.ErrorMsg, 1024), scrub)
+ if t.IsInterrupt {
+ span.SetAttributes(attribute.Bool("coding_agent.tool.interrupted", true))
+ }
+ // Set the OTel span status to Error so the trace tree shows
+ // the failed tool span in red and parent rollups treat the
+ // span as failed. Previously failed tools left the span
+ // status Unset (visually "ok") which masked breakage in
+ // the chat view.
+ span.SetStatus(codes.Error, truncate(nonEmpty(t.ErrorMsg, "tool_error"), 256))
+ }
+ // Bodies are gated through bodyAllowed so adapters can't
+ // accidentally leak args/result when capture is metadata/minimal.
+ // Adapters call captureIfFull themselves too, but this is the
+ // last-line defence so a future adapter that forgets the helper
+ // still can't push prompts onto the wire in metadata mode.
+ if t.Args != "" && bodyAllowed(capture) {
+ setStr(span, semconv.GenAIToolCallArguments, truncate(t.Args, 8192), scrub)
+ }
+ if t.Result != "" && bodyAllowed(capture) {
+ setStr(span, "gen_ai.tool.call.result", truncate(t.Result, 8192), scrub)
+ }
+ if t.AgentMessage != "" && bodyAllowed(capture) {
+ setStr(span, "coding_agent.tool.agent_message", truncate(t.AgentMessage, 4096), scrub)
+ }
+ if dur := t.EndedAt.Sub(t.StartedAt); dur > 0 {
+ span.SetAttributes(attribute.Int64("coding_agent.tool.duration_ms", dur.Milliseconds()))
+ }
+}
+
+func nonEmpty(s, fallback string) string {
+ if s == "" {
+ return fallback
+ }
+ return s
+}
+
+func setLLMTurnAttrs(span trace.Span, t normalize.LLMTurn, scrub scrubFn, capture string) {
+ span.SetAttributes(attribute.String(semconv.CodingAgentHookSchemaVersion, semconv.CodingAgentSchemaVersion))
+ setStr(span, semconv.CodingAgentSessionID, t.SessionID, scrub)
+ setStr(span, semconv.GenAIConversationID, t.ConversationID, scrub)
+ setStr(span, semconv.CodingAgentClient, t.Vendor, scrub)
+ if t.Vendor != "" {
+ setStr(span, "gen_ai.agent.name", t.Vendor, scrub)
+ }
+ // D5: GenAI semconv parity. Every llm.turn span should declare:
+ // gen_ai.operation.name — the OTel-standard verb for "this was
+ // a chat completion". Other valid values are "text_completion",
+ // "embeddings"; coding agents always run chat.
+ // gen_ai.system — the model provider (anthropic/openai/google).
+ // Falls back to vendor when we don't know better.
+ // Without these two attrs the GenAI dashboards in the
+ // OpenTelemetry catalogue can't render this span.
+ setStr(span, "gen_ai.operation.name", "chat", scrub)
+ if sys := inferProvider(t.Model, t.Vendor); sys != "" {
+ setStr(span, semconv.GenAISystem, sys, scrub)
+ setStr(span, semconv.GenAIProviderName, sys, scrub)
+ }
+ if t.Model != "" {
+ setStr(span, semconv.GenAIRequestModel, t.Model, scrub)
+ setStr(span, semconv.GenAIResponseModel, t.Model, scrub)
+ }
+ if t.GenerationID != "" {
+ setStr(span, "gen_ai.response.id", t.GenerationID, scrub)
+ }
+ if len(t.FinishReasons) > 0 {
+ span.SetAttributes(attribute.StringSlice("gen_ai.response.finish_reasons", t.FinishReasons))
+ }
+ if t.CacheReadTokens > 0 {
+ span.SetAttributes(attribute.Int64("gen_ai.usage.cache.read_input_tokens", t.CacheReadTokens))
+ }
+ if t.CacheCreationTokens > 0 {
+ span.SetAttributes(attribute.Int64("gen_ai.usage.cache.creation_input_tokens", t.CacheCreationTokens))
+ }
+ if t.UserEmail != "" {
+ // Mirror onto both keys until consumers cut over. `user.email`
+ // is the legacy `coding_agent.*` shape; `gen_ai.request.user`
+ // is the OTel GenAI canonical (matches the per-request user
+ // identifier semconv).
+ setStr(span, "user.email", t.UserEmail, scrub)
+ setStr(span, semconv.GenAIRequestUser, t.UserEmail, scrub)
+ }
+ if t.AssistantMessageOnly {
+ setStr(span, "coding_agent.llm.turn.kind", "assistant_only", scrub)
+ } else if t.Prompt != "" {
+ setStr(span, "coding_agent.llm.turn.kind", "user_prompt", scrub)
+ }
+
+ if t.InputTokens > 0 {
+ span.SetAttributes(attribute.Int64(semconv.GenAIUsageInputTokens, t.InputTokens))
+ }
+ if t.OutputTokens > 0 {
+ span.SetAttributes(attribute.Int64(semconv.GenAIUsageOutputTokens, t.OutputTokens))
+ }
+ if t.TotalTokens > 0 {
+ span.SetAttributes(attribute.Int64(semconv.GenAIUsageTotalTokens, t.TotalTokens))
+ }
+ if t.CostUSD > 0 {
+ span.SetAttributes(attribute.Float64(semconv.GenAIUsageCost, t.CostUSD))
+ }
+ if t.ThoughtMs > 0 {
+ span.SetAttributes(attribute.Int64("coding_agent.llm.thought.duration_ms", t.ThoughtMs))
+ }
+ if len(t.AttachmentPaths) > 0 {
+ // Paths may be absolute and rooted under $HOME — scrub
+ // every element so token/secret patterns embedded in
+ // filenames (e.g. `/tmp/sk_live_…`) don't leak.
+ setStrSlice(span, "coding_agent.llm.turn.attachment.paths", t.AttachmentPaths, scrub)
+ span.SetAttributes(attribute.Int("coding_agent.llm.turn.attachment.count", len(t.AttachmentPaths)))
+ }
+ for k, v := range t.Extras {
+ setStr(span, k, v, scrub)
+ }
+
+ // Prompt / response / thought bodies cross the wire only when
+ // `bodyAllowed(capture)` is true (i.e. full mode). The redact
+ // tier-2 layer in internal/redact already runs on every string
+ // in this mode. We serialise everything into OTel-canonical
+ // `gen_ai.{input,output}.messages` envelopes here — adapters
+ // pass us plain strings + structured tool refs, never JSON.
+ if bodyAllowed(capture) {
+ if in := buildInputMessagesJSON(t); in != "" {
+ setStr(span, semconv.GenAIInputMessages, truncate(in, 16_000), scrub)
+ }
+ if out := buildOutputMessagesJSON(t); out != "" {
+ setStr(span, semconv.GenAIOutputMessages, truncate(out, 16_000), scrub)
+ }
+ if t.ThoughtText != "" {
+ setStr(span, "coding_agent.llm.thought.text", truncate(t.ThoughtText, 8_000), scrub)
+ }
+ }
+}
+
+// buildInputMessagesJSON produces the JSON value for
+// `gen_ai.input.messages` per the OTel GenAI semantic conventions
+// (https://github.com/open-telemetry/semantic-conventions-genai →
+// docs/gen-ai/gen-ai-spans.md). Each message has `role` + `parts`;
+// each text part uses `{"type":"text","content":"..."}`.
+//
+// Design note — we deliberately do NOT serialise `tool_call_response`
+// parts here even though the OTel GenAI spec allows them. Vendors
+// like Claude Code and Codex bundle every preceding tool's result
+// body into each turn's input (Anthropic / OpenAI message format),
+// which makes a single turn's messages JSON balloon well past the
+// 16 KB span-attribute cap — at which point the value gets truncated,
+// the chat view's JSON parser fails, and the entire truncated blob
+// falls back to rendering as a "user" message bubble.
+//
+// The canonical source for tool inputs / outputs is the dedicated
+// `coding_agent.tool.call` span (which carries
+// `gen_ai.tool.call.arguments` and `gen_ai.tool.call.result`). The
+// chat view interleaves those spans with LLM turns by timestamp, so
+// nothing is lost — the conversation reconstructs from per-turn LLM
+// spans + per-tool tool.call spans without duplicative narration.
+//
+// Returns "" when there is nothing to record so adapters don't stamp
+// an empty `[]`.
+func buildInputMessagesJSON(t normalize.LLMTurn) string {
+ type part map[string]any
+ type message map[string]any
+
+ s := strings.TrimSpace(t.Prompt)
+ if s == "" {
+ return ""
+ }
+ msgs := []message{{
+ "role": "user",
+ "parts": []part{{"type": "text", "content": t.Prompt}},
+ }}
+ body, err := json.Marshal(msgs)
+ if err != nil {
+ return ""
+ }
+ return string(body)
+}
+
+// buildOutputMessagesJSON produces the OTel-canonical JSON for
+// `gen_ai.output.messages`. The output is a single assistant message
+// with the response text and a `finish_reason` at the message level
+// (per the spec example, line 79 of docs/gen-ai/gen-ai-spans.md).
+//
+// See `buildInputMessagesJSON` for why tool_call parts are not
+// serialised here even though the OTel GenAI spec allows them: the
+// `coding_agent.tool.call` span is the canonical source for tool
+// arguments + results, and bundling them into the LLM-turn message
+// blob blows past the span-attribute size cap.
+func buildOutputMessagesJSON(t normalize.LLMTurn) string {
+ type part map[string]any
+ type message map[string]any
+
+ parts := make([]part, 0, 1)
+ if s := strings.TrimSpace(t.Response); s != "" {
+ parts = append(parts, part{"type": "text", "content": t.Response})
+ }
+ if len(parts) == 0 && len(t.FinishReasons) == 0 {
+ return ""
+ }
+ msg := message{
+ "role": "assistant",
+ "parts": parts,
+ }
+ if len(t.FinishReasons) > 0 {
+ msg["finish_reason"] = t.FinishReasons[0]
+ }
+ body, err := json.Marshal([]message{msg})
+ if err != nil {
+ return ""
+ }
+ return string(body)
+}
+
+func setSubagentAttrs(span trace.Span, s normalize.Subagent, scrub scrubFn) {
+ span.SetAttributes(attribute.String(semconv.CodingAgentHookSchemaVersion, semconv.CodingAgentSchemaVersion))
+ setStr(span, semconv.CodingAgentSessionID, s.SessionID, scrub)
+ setStr(span, semconv.CodingAgentClient, s.Vendor, scrub)
+ setStr(span, semconv.GenAIConversationID, s.ParentConversationID, scrub)
+ setStr(span, semconv.CodingAgentAgentID, s.SubagentID, scrub)
+ setStr(span, semconv.CodingAgentAgentParentID, s.ParentConversationID, scrub)
+ setStr(span, semconv.CodingAgentAgentType, semconv.CodingAgentAgentTypeSubagent, scrub)
+ setStr(span, semconv.CodingAgentSubagentType, s.SubagentType, scrub)
+ setStr(span, semconv.CodingAgentLinkageConfidence, semconv.CodingAgentLinkageConfidenceHigh, scrub)
+ setStr(span, "coding_agent.subagent.status", s.Status, scrub)
+ setStr(span, "coding_agent.subagent.task", truncate(s.Task, 2_048), scrub)
+ setStr(span, "coding_agent.subagent.description", truncate(s.Description, 1_024), scrub)
+ setStr(span, "coding_agent.subagent.summary", truncate(s.Summary, 4_096), scrub)
+ if s.Model != "" {
+ setStr(span, semconv.GenAIRequestModel, s.Model, scrub)
+ }
+ if s.GitBranch != "" {
+ setStr(span, "vcs.ref.head.name", s.GitBranch, scrub)
+ }
+ if s.ToolCallID != "" {
+ // Canonical OTel GenAI key for tool-call linkage. Stamping
+ // this on the subagent span lets the UI join (parent's Task
+ // tool call ↔ subagent block) by id, which is what the chat
+ // view's "Subagent" collapsible expects.
+ setStr(span, semconv.GenAIToolCallID, s.ToolCallID, scrub)
+ }
+ if s.IsParallelWorker {
+ span.SetAttributes(attribute.Bool("coding_agent.subagent.parallel_worker", true))
+ }
+ if s.DurationMs > 0 {
+ span.SetAttributes(attribute.Int64("coding_agent.subagent.duration_ms", s.DurationMs))
+ }
+ if s.MessageCount > 0 {
+ span.SetAttributes(attribute.Int("coding_agent.subagent.message_count", s.MessageCount))
+ }
+ if s.ToolCallCount > 0 {
+ span.SetAttributes(attribute.Int("coding_agent.subagent.tool_call_count", s.ToolCallCount))
+ }
+ if s.LoopCount > 0 {
+ span.SetAttributes(attribute.Int("coding_agent.subagent.loop_count", s.LoopCount))
+ }
+ if len(s.ModifiedFiles) > 0 {
+ // Subagent file lists are typically absolute paths under
+ // the user's workspace — route through scrub so any
+ // embedded token-shaped substrings get redacted.
+ setStrSlice(span, "coding_agent.subagent.modified_files", s.ModifiedFiles, scrub)
+ span.SetAttributes(attribute.Int("coding_agent.subagent.modified_files.count", len(s.ModifiedFiles)))
+ }
+}
+
+// setGitCommitAttrs stamps the canonical attributes for a single
+// `coding_agent.git.commit` span. Message body is gated by content
+// capture; SHA + user + working dir are always safe.
+func setGitCommitAttrs(span trace.Span, c normalize.GitCommit, scrub scrubFn, capture string) {
+ span.SetAttributes(attribute.String(semconv.CodingAgentHookSchemaVersion, semconv.CodingAgentSchemaVersion))
+ setStr(span, semconv.CodingAgentSessionID, c.SessionID, scrub)
+ setStr(span, semconv.CodingAgentClient, c.Vendor, scrub)
+ if c.UserID != "" {
+ setStr(span, semconv.GenAIRequestUser, c.UserID, scrub)
+ }
+ if c.Tool != "" {
+ setStr(span, semconv.GenAIToolName, c.Tool, scrub)
+ }
+ setStr(span, semconv.CodingAgentGitCommitSHA, c.SHA, scrub)
+ if c.WorkingDir != "" {
+ setStr(span, "code.cwd", c.WorkingDir, scrub)
+ }
+ if c.Message != "" && bodyAllowed(capture) {
+ setStr(span, semconv.CodingAgentGitCommitMessage, truncate(c.Message, 4096), scrub)
+ }
+}
+
+// setGitPullRequestAttrs stamps the canonical attributes for a single
+// `coding_agent.git.pull_request` span. Title body is gated by
+// content capture; URL + number + user + working dir are always safe.
+func setGitPullRequestAttrs(span trace.Span, p normalize.GitPullRequest, scrub scrubFn, capture string) {
+ span.SetAttributes(attribute.String(semconv.CodingAgentHookSchemaVersion, semconv.CodingAgentSchemaVersion))
+ setStr(span, semconv.CodingAgentSessionID, p.SessionID, scrub)
+ setStr(span, semconv.CodingAgentClient, p.Vendor, scrub)
+ if p.UserID != "" {
+ setStr(span, semconv.GenAIRequestUser, p.UserID, scrub)
+ }
+ if p.Tool != "" {
+ setStr(span, semconv.GenAIToolName, p.Tool, scrub)
+ }
+ setStr(span, semconv.CodingAgentGitPRURL, p.URL, scrub)
+ if p.Number > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentGitPRNumber, p.Number))
+ }
+ if p.WorkingDir != "" {
+ setStr(span, "code.cwd", p.WorkingDir, scrub)
+ }
+ if p.Title != "" && bodyAllowed(capture) {
+ setStr(span, semconv.CodingAgentGitPRTitle, truncate(p.Title, 2048), scrub)
+ }
+}
+
+func setEditDecisionAttrs(span trace.Span, d normalize.EditDecision, scrub scrubFn) {
+ span.SetAttributes(attribute.String(semconv.CodingAgentHookSchemaVersion, semconv.CodingAgentSchemaVersion))
+ setStr(span, semconv.CodingAgentSessionID, d.SessionID, scrub)
+ setStr(span, semconv.CodingAgentAgentID, d.AgentID, scrub)
+ setStr(span, semconv.CodingAgentEditDecision, d.Decision, scrub)
+ setStr(span, semconv.CodingAgentEditDecisionSource, d.Source, scrub)
+ setStr(span, semconv.CodingAgentEditToolName, d.Tool, scrub)
+ setStr(span, semconv.CodingAgentEditLanguage, d.Language, scrub)
+ setStr(span, semconv.CodingAgentClient, d.Vendor, scrub)
+ if d.LinesAdded > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentEditLinesAdded, d.LinesAdded))
+ }
+ if d.LinesRemoved > 0 {
+ span.SetAttributes(attribute.Int(semconv.CodingAgentEditLinesRemoved, d.LinesRemoved))
+ }
+ if d.FilePath != "" {
+ setStr(span, "code.file.path", d.FilePath, scrub)
+ }
+}
+
+// setStr is the choke-point every string attribute flows through. The
+// scrub closure runs on every value before it crosses the wire.
+func setStr(span trace.Span, key, val string, scrub scrubFn) {
+ if val == "" {
+ return
+ }
+ if scrub != nil {
+ val = scrub(val)
+ }
+ span.SetAttributes(attribute.String(key, val))
+}
+
+// setStrSlice is the slice counterpart to setStr — every element is
+// passed through the scrub closure before the slice crosses the wire.
+// Use this for any attribute whose elements may contain user-supplied
+// content (absolute file paths, command lines, free-text args). The
+// raw `attribute.StringSlice` constructor bypasses redaction, which
+// is fine for fully-controlled enum values (vendor names, finish
+// reasons) but a leak for everything else.
+func setStrSlice(span trace.Span, key string, vals []string, scrub scrubFn) {
+ if len(vals) == 0 {
+ return
+ }
+ if scrub != nil {
+ scrubbed := make([]string, len(vals))
+ for i, v := range vals {
+ scrubbed[i] = scrub(v)
+ }
+ vals = scrubbed
+ }
+ span.SetAttributes(attribute.StringSlice(key, vals))
+}
+
+// setAnyAttr handles the heterogeneous values that flow through
+// EmitEvent.Attrs. We narrow to OTel-supported types; anything else is
+// stringified.
+func setAnyAttr(span trace.Span, key string, v any, scrub scrubFn) {
+ switch x := v.(type) {
+ case string:
+ setStr(span, key, x, scrub)
+ case bool:
+ span.SetAttributes(attribute.Bool(key, x))
+ case int:
+ span.SetAttributes(attribute.Int(key, x))
+ case int64:
+ span.SetAttributes(attribute.Int64(key, x))
+ case float32:
+ span.SetAttributes(attribute.Float64(key, float64(x)))
+ case float64:
+ span.SetAttributes(attribute.Float64(key, x))
+ case []string:
+ if scrub != nil {
+ scrubbed := make([]string, len(x))
+ for i, s := range x {
+ scrubbed[i] = scrub(s)
+ }
+ x = scrubbed
+ }
+ span.SetAttributes(attribute.StringSlice(key, x))
+ default:
+ s := defaultString(v)
+ setStr(span, key, s, scrub)
+ }
+}
+
+func truncate(s string, max int) string {
+ if len(s) <= max {
+ return s
+ }
+ return s[:max] + "...(truncated)"
+}
diff --git a/cli/internal/otlp/exporter.go b/cli/internal/otlp/exporter.go
new file mode 100644
index 00000000..552d1415
--- /dev/null
+++ b/cli/internal/otlp/exporter.go
@@ -0,0 +1,913 @@
+// Package otlp wraps the sdk/go OTel exporter for the CLI's hot path.
+//
+// Lifecycle (per hook invocation):
+//
+// emitter, err := otlp.NewEmitter(ctx, cfg)
+// ... emit spans/events ...
+// emitter.Shutdown(ctxWithFlushBudget)
+//
+// The emitter implements the normalize.Emitter interface so per-vendor
+// adapters under hook/<vendor>/ stay decoupled from OTel mechanics.
+//
+// NOTE: There is currently no disk-backed retry queue. The
+// `emitter.Shutdown(ctxWithFlushBudget)` call has a few-hundred-ms
+// flush budget; if the collector is unreachable past that window the
+// spans are dropped on the floor. This is the single biggest gap
+// Phase D8 covers wiring an OTel BatchSpanProcessor with
+// real retry + a XDG-cached fallback queue.
+package otlp
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/user"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/cli/internal/config"
+ "github.com/openlit/openlit/cli/internal/redact"
+ "github.com/openlit/openlit/cli/internal/version"
+ openlit "github.com/openlit/openlit/sdk/go"
+ "github.com/openlit/openlit/sdk/go/semconv"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/trace"
+)
+
+// drainCounters reads the minimal-mode rolled-up counters off the
+// sessionstate cache (scoped to the emitting vendor) and merges them
+// into the session struct, preferring caller-supplied values when
+// present. We DO NOT clear the counters from disk — sessionEnd may
+// run multiple times across retry, and the GC routine in sessionstate
+// handles eventual cleanup.
+//
+// Split into two functions because the LOC / edit / commit / PR
+// counters are bumped regardless of capture mode (a Cursor user on
+// metadata capture still wants to see their LOC numbers); the
+// tool-call / token / cost counters only need draining in minimal
+// mode where their per-event spans were suppressed.
+func drainCounters(s normalize.Session, vendor string) normalize.Session {
+ if s.SessionID == "" {
+ return s
+ }
+ st := sessionstate.Load(s.SessionID, vendor)
+ if st == nil {
+ return s
+ }
+ if s.ToolCallCount == 0 && st.ToolCallCount > 0 {
+ s.ToolCallCount = st.ToolCallCount
+ }
+ if s.SubagentCount == 0 && st.SubagentCount > 0 {
+ s.SubagentCount = st.SubagentCount
+ }
+ if s.InputTokens == 0 && st.InputTokens > 0 {
+ s.InputTokens = st.InputTokens
+ }
+ if s.OutputTokens == 0 && st.OutputTokens > 0 {
+ s.OutputTokens = st.OutputTokens
+ }
+ if s.CostUSD == 0 && st.CostUSD > 0 {
+ s.CostUSD = st.CostUSD
+ }
+ if s.TotalTokens == 0 {
+ s.TotalTokens = s.InputTokens + s.OutputTokens
+ }
+ return s
+}
+
+// drainCodeCounters folds the cached LOC / edit / commit / PR
+// counters onto the session struct, regardless of capture mode.
+// Called from every EmitSession invocation so the session-root span
+// carries the up-to-the-event totals even when the operator runs in
+// `metadata_only` or `full` capture.
+func drainCodeCounters(s normalize.Session, vendor string) normalize.Session {
+ if s.SessionID == "" {
+ return s
+ }
+ st := sessionstate.Load(s.SessionID, vendor)
+ if st == nil {
+ return s
+ }
+ if s.LinesAdded == 0 && st.LinesAdded > 0 {
+ s.LinesAdded = st.LinesAdded
+ }
+ if s.LinesRemoved == 0 && st.LinesRemoved > 0 {
+ s.LinesRemoved = st.LinesRemoved
+ }
+ if s.LinesAccepted == 0 && st.LinesAccepted > 0 {
+ s.LinesAccepted = st.LinesAccepted
+ }
+ if s.LinesRejected == 0 && st.LinesRejected > 0 {
+ s.LinesRejected = st.LinesRejected
+ }
+ if s.EditAcceptCount == 0 && st.EditAcceptCount > 0 {
+ s.EditAcceptCount = st.EditAcceptCount
+ }
+ if s.EditRejectCount == 0 && st.EditRejectCount > 0 {
+ s.EditRejectCount = st.EditRejectCount
+ }
+ if s.CommitCount == 0 && st.CommitCount > 0 {
+ s.CommitCount = st.CommitCount
+ }
+ if s.PRCount == 0 && st.PRCount > 0 {
+ s.PRCount = st.PRCount
+ }
+ return s
+}
+
+// resolveLocalUser produces a stable identifier for the human running
+// the agent. The hook subcommand resolves the canonical identity via
+// `coding/identity.ResolveForVendor` + `FromGitConfig` BEFORE booting
+// the OTel SDK and writes the result back into `OPENLIT_USER`, so this
+// function is normally a single env-var read.
+//
+// The OS-username fallback exists for direct CLI usage outside the
+// hook hot path (e.g. `openlit configure`); it is the last resort and
+// will produce a "Username" row in the hub when no email-shaped
+// identity is available.
+func resolveLocalUser() string {
+ for _, env := range []string{"OPENLIT_USER", "GIT_AUTHOR_EMAIL", "USER_EMAIL"} {
+ if v := strings.TrimSpace(os.Getenv(env)); v != "" {
+ return v
+ }
+ }
+ if u, err := user.Current(); err == nil {
+ if u.Username != "" {
+ return u.Username
+ }
+ }
+ for _, env := range []string{"USER", "USERNAME", "LOGNAME"} {
+ if v := strings.TrimSpace(os.Getenv(env)); v != "" {
+ return v
+ }
+ }
+ return ""
+}
+
+// resolveTerminalType detects the IDE / terminal that HOSTS the agent
+// — not the agent itself. `terminal.type` mirrors Claude Code's standard
+// attribute (https://code.claude.com/docs/en/monitoring-usage#standard-attributes)
+// and is supposed to identify the SHELL/IDE in which the agent runs
+// (e.g. `vscode`, `cursor`, `iterm`, `tmux`). The agent identifier
+// already lives on `coding_agent.client` / `gen_ai.agent.name`, so
+// stamping the agent here would be double-counting and breaks
+// "which IDE drives the most agent usage" dashboards.
+//
+// Detection order: most-specific host signal → terminal-program fallback.
+// Returns "" if we can't tell — the attribute is then omitted entirely.
+func resolveTerminalType() string {
+ // Cursor IDE: set by Cursor's editor process. CURSOR_TRACE_ID is
+ // only set inside Cursor's hook runner; the other CURSOR_* envs
+ // (CURSOR_AGENT, CURSOR_WORKSPACE_LABEL, CURSOR_EXTENSION_HOST_ROLE)
+ // are set by Cursor's extension host whenever Cursor is the
+ // foreground IDE. Any of them indicates the host is Cursor IDE
+ // (regardless of which agent — Claude Code, Cursor Composer,
+ // Codex, etc. — is the one calling us).
+ for _, env := range []string{
+ "CURSOR_TRACE_ID",
+ "CURSOR_AGENT",
+ "CURSOR_PID",
+ "CURSOR_USER",
+ "CURSOR_WORKSPACE_LABEL",
+ "CURSOR_EXTENSION_HOST_ROLE",
+ } {
+ if os.Getenv(env) != "" {
+ return "cursor"
+ }
+ }
+ // VS Code (and forks). VSCODE_IPC_HOOK is the per-session UDS path
+ // containing the IDE's data-dir name — for Cursor it's
+ // `/Library/Application Support/Cursor/...`, for VS Code it's
+ // `/Library/Application Support/Code/...`. Inspecting the path
+ // disambiguates VS Code from forks that also export `VSCODE_PID`.
+ ipc := os.Getenv("VSCODE_IPC_HOOK")
+ if strings.Contains(ipc, "/Cursor/") || strings.Contains(ipc, "/cursor/") {
+ return "cursor"
+ }
+ if strings.Contains(ipc, "/Code/") || strings.Contains(ipc, "/Code - Insiders/") ||
+ strings.Contains(ipc, "/VSCodium/") {
+ return "vscode"
+ }
+ if os.Getenv("VSCODE_PID") != "" || os.Getenv("VSCODE_INJECTION") != "" {
+ return "vscode"
+ }
+ // Codex CLI agents — these run in a real terminal, so we still
+ // fall through to TERM_PROGRAM below when its marker isn't
+ // present. We don't stamp the agent itself as the
+ // terminal.
+ // JetBrains IDEs set TERMINAL_EMULATOR=JetBrains-JediTerm.
+ if strings.Contains(strings.ToLower(os.Getenv("TERMINAL_EMULATOR")), "jetbrains") {
+ return "jetbrains"
+ }
+ // TERM_PROGRAM is the host terminal app — usable when neither
+ // Cursor nor VS Code is involved (plain shell sessions).
+ if v := strings.ToLower(os.Getenv("TERM_PROGRAM")); v != "" {
+ switch v {
+ case "vscode":
+ // VS Code sets this; Cursor also sets it (it's a VS Code
+ // fork) but Cursor is caught above by CURSOR_* / IPC path.
+ return "vscode"
+ case "iterm.app":
+ return "iterm"
+ case "apple_terminal":
+ return "apple-terminal"
+ case "warpterminal":
+ return "warp"
+ case "ghostty":
+ return "ghostty"
+ case "wezterm":
+ return "wezterm"
+ case "alacritty":
+ return "alacritty"
+ case "kitty":
+ return "kitty"
+ case "tabby":
+ return "tabby"
+ default:
+ return v
+ }
+ }
+ if os.Getenv("TMUX") != "" {
+ return "tmux"
+ }
+ // Last resort: walk the process tree. Anthropic Claude Code
+ // scrubs IDE-specific env vars when it spawns hook subprocesses,
+ // so neither CURSOR_* nor VSCODE_* are visible — but the parent
+ // process binary path still reveals the host IDE. Cheap: at most
+ // ~10 `ps` lookups per cold-start hook (we cap recursion depth).
+ if host := detectHostFromProcessTree(); host != "" {
+ return host
+ }
+ return ""
+}
+
+// detectHostFromProcessTree walks up `os.Getppid()` looking for a
+// known IDE / terminal binary in the process's argv[0]. Returns "" if
+// nothing is recognised within `maxDepth` hops. Bounded so a forked
+// daemon tree can't blow up the hook latency.
+func detectHostFromProcessTree() string {
+ const maxDepth = 12
+ pid := os.Getppid()
+ for i := 0; pid > 1 && i < maxDepth; i++ {
+ name, parent, err := readProcessNameAndPPID(pid)
+ if err != nil {
+ return ""
+ }
+ if h := detectHostFromBinary(name); h != "" {
+ return h
+ }
+ pid = parent
+ }
+ return ""
+}
+
+// detectHostFromBinary maps an absolute binary path / argv[0] to a
+// known IDE/terminal label. Case-insensitive substring matching keeps
+// the map small. Patterns cover all three supported OSes:
+//
+// - macOS uses .app bundle paths ("/Cursor.app/Contents/MacOS/Cursor")
+// - Linux uses lowercase binary names ("/usr/bin/cursor", "wezterm")
+// - Windows uses .exe basenames ("Cursor.exe", "Code.exe", "wt.exe")
+//
+// The lowercase + substring strategy means a single check usually
+// matches across all three (e.g. "cursor" appears in every Cursor
+// host path).
+func detectHostFromBinary(bin string) string {
+ b := strings.ToLower(bin)
+ switch {
+ case strings.Contains(b, "/cursor.app/"),
+ strings.Contains(b, "/cursor helper"),
+ strings.Contains(b, "cursor.exe"),
+ // Plain "cursor" appears in Linux package paths and the
+ // Windows AppData install dir alike. Anchored to a path
+ // or extension marker to avoid false positives on words
+ // like "cursorless".
+ strings.Contains(b, "\\cursor\\"),
+ strings.Contains(b, "/cursor/"):
+ return "cursor"
+ case strings.Contains(b, "/visual studio code.app/"),
+ strings.Contains(b, "/code helper"),
+ strings.Contains(b, "/vscodium"),
+ strings.Contains(b, "\\code.exe"),
+ strings.Contains(b, "\\vscodium.exe"):
+ return "vscode"
+ case strings.Contains(b, "/iterm.app/"), strings.Contains(b, "iterm2"):
+ return "iterm"
+ case strings.Contains(b, "/terminal.app/"):
+ return "apple-terminal"
+ case strings.Contains(b, "/warp.app/"), strings.Contains(b, "warp.exe"):
+ return "warp"
+ case strings.Contains(b, "/ghostty.app/"), strings.Contains(b, "ghostty.exe"):
+ return "ghostty"
+ case strings.Contains(b, "wezterm"):
+ return "wezterm"
+ case strings.Contains(b, "alacritty"):
+ return "alacritty"
+ case strings.Contains(b, "kitty"):
+ return "kitty"
+ case strings.Contains(b, "windowsterminal.exe"), strings.Contains(b, "\\wt.exe"):
+ return "windows-terminal"
+ case strings.Contains(b, "powershell.exe"), strings.Contains(b, "pwsh.exe"):
+ return "powershell"
+ case strings.Contains(b, "\\cmd.exe"):
+ return "cmd"
+ case strings.Contains(b, "/idea.app/"),
+ strings.Contains(b, "/intellij idea.app/"),
+ strings.Contains(b, "/pycharm.app/"),
+ strings.Contains(b, "/goland.app/"),
+ strings.Contains(b, "/webstorm.app/"),
+ strings.Contains(b, "idea64.exe"),
+ strings.Contains(b, "pycharm64.exe"),
+ strings.Contains(b, "goland64.exe"),
+ strings.Contains(b, "webstorm64.exe"):
+ return "jetbrains"
+ }
+ return ""
+}
+
+// readProcessNameAndPPID returns argv[0] and the parent pid for `pid`.
+// macOS: shells out to `ps -o ppid=,command= -p <pid>`. Linux: reads
+// /proc/<pid>/stat for ppid and /proc/<pid>/cmdline for argv[0]. The
+// implementation is intentionally tolerant — any failure short-circuits
+// the walk so a non-readable process can never crash the hook.
+func readProcessNameAndPPID(pid int) (binary string, ppid int, err error) {
+ return readProcessNameAndPPIDOS(pid)
+}
+
+// Emitter is the concrete normalize.Emitter implementation. The CLI keeps
+// it tiny — sdk/go does the heavy lifting (resource attrs, batch span
+// processor, OTLP HTTP client).
+type Emitter struct {
+ tracer trace.Tracer
+ cfg *config.Resolved
+
+ // vendor is the canonical vendor identifier ("cursor",
+ // "claude-code", "codex") for the agent that fired
+ // this hook. Mixed into the deterministic TraceID/SpanID so
+ // nested agents (e.g. Claude Code launched inside a Cursor
+ // terminal) get distinct traces even when the host's session id
+ // leaks into the guest's environment.
+ vendor string
+
+ // scrub is the active redactor (tier 1 always; tier 2 when the
+ // configured content-capture mode is "full"). Wraps every string
+ // attribute the adapter passes us so secrets don't leak even
+ // when content capture is opt-in.
+ scrub func(string) string
+
+ mu sync.Mutex
+ shut bool
+ startedAt time.Time
+}
+
+// initOnce guards Init/Shutdown across multiple hook invocations within
+// the same process. In practice the CLI's cold-start pattern means each
+// invocation is a fresh process; the guard is defense in depth.
+var initOnce sync.Mutex
+
+// NewEmitter initializes the OTel SDK and returns an emitter. Callers
+// MUST call Shutdown once they're done so spans flush before the
+// process exits.
+//
+// `vendor` is the canonical agent identifier ("cursor", "claude-code",
+// "codex"). It's mixed into the deterministic TraceID so
+// nested agents (Claude Code inside Cursor's terminal) get distinct
+// traces.
+//
+// `extraAttrs` are merged into the resource bundle on top of the
+// default identity / hostname / terminal attributes. Callers (hook.go)
+// pass session-level facts here — working folder, repo URL, branch,
+// permission mode — so child spans inherit them as resource attributes
+// and the trace-detail header pills stay populated when a developer
+// drills into a non-session span.
+func NewEmitter(_ context.Context, cfg *config.Resolved, vendor string, extraAttrs ...map[string]string) (*Emitter, error) {
+ if cfg == nil {
+ return nil, errors.New("nil config")
+ }
+
+ initOnce.Lock()
+ defer initOnce.Unlock()
+
+ if openlit.IsInitialized() {
+ // Re-use the existing tracer if Init has already been called.
+ // Sane behavior for the rare in-process retry case.
+ return &Emitter{
+ tracer: otel.GetTracerProvider().Tracer("openlit-cli"),
+ cfg: cfg,
+ vendor: vendor,
+ scrub: redact.ForCapture(cfg.CodingContentCapture),
+ startedAt: time.Now(),
+ }, nil
+ }
+
+ // Build a resource-attribute set that rides on every span this
+ // process emits. We always tag the local user identity (so the
+ // dashboard's user roll-ups render something recognisable even
+ // when the vendor's hook payload doesn't carry an email), and we
+ // stamp a host name + the active vendor for filtering.
+ extra := map[string]string{}
+ if u := resolveLocalUser(); u != "" {
+ extra["gen_ai.user.name"] = u
+ }
+ if hn, err := os.Hostname(); err == nil && hn != "" {
+ extra["host.name"] = hn
+ }
+ if t := resolveTerminalType(); t != "" {
+ // Matches Claude Code's standard attribute so a multi-vendor
+ // fleet's `terminal.type` filter has consistent values.
+ extra["terminal.type"] = t
+ }
+ // Caller-supplied attributes win; this lets hook.go layer in
+ // session-scoped values without us having to reach back into
+ // sessionstate from the exporter package (which would create a
+ // circular import in v2 when sessionstate moves alongside the
+ // per-vendor adapters).
+ for _, m := range extraAttrs {
+ for k, v := range m {
+ if v == "" {
+ continue
+ }
+ extra[k] = v
+ }
+ }
+
+ // D5: stamp the CLI version on every span as a resource attribute
+ // so operations can correlate behaviour with the binary that
+ // produced it (e.g. "this regression appeared in 0.5.3"). The
+ // SDK already sets `service.version`; we keep that as the SDK's
+ // version and add `coding_agent.hook.cli.version` for the hook
+ // binary's identity, which can drift from service.version when a
+ // host runs multiple CLIs side-by-side.
+ if extra == nil {
+ extra = map[string]string{}
+ }
+ extra["coding_agent.hook.cli.version"] = version.Version
+ // Stamp the build commit SHA when available so support can pin a
+ // reported behaviour to an exact CLI build. The release workflow
+ // passes the short SHA via -ldflags; `dev` / source builds may
+ // leave this empty.
+ if version.Commit != "" {
+ extra["coding_agent.hook.cli.commit"] = version.Commit
+ }
+ // Mark every span emitted from the hook path so the query layer
+ // can tell hook spans apart from a vendor's native OTel exporter
+ // (e.g. Claude Code's `CLAUDE_CODE_ENABLE_TELEMETRY=1` path). See
+ // `.cursor/rules/coding-agents-convention.mdc` §6 for the full
+ // dual-path coalesce contract; without this stamp, reads can't
+ // reliably prefer native cost/tokens over our hook estimates.
+ extra["coding_agent.signal_source"] = "hook"
+ // Positively brand every CLI span as a distinct OpenTelemetry
+ // distribution. This is the structural barrier that keeps the
+ // agent-hub's SDK discovery (`materialize.ts:discoverAgents`)
+ // from EVER picking up a coding-agent span as if it were a
+ // regular openlit-go SDK service. Without this, the SDK pipeline
+ // only excludes spans that carry `coding_agent.session.id` — a
+ // reactive check that fails open the moment a single span
+ // somewhere drops the attribute (a race during session warm-up,
+ // a future regression, a vendor's native exporter that doesn't
+ // know our conventions). The distro marker is set once at SDK
+ // init, attaches to every span the process emits, and is the
+ // same hook every other OpenTelemetry distribution (ebpf, otel
+ // auto-instrumentation, …) uses to identify itself.
+ extra["telemetry.distro.name"] = "openlit-cli"
+ extra["telemetry.distro.version"] = version.Version
+
+ if err := openlit.Init(openlit.Config{
+ OtlpEndpoint: cfg.OTLPEndpoint,
+ OtlpHeaders: cfg.EffectiveHeaders(),
+ Environment: cfg.Environment,
+ ApplicationName: cfg.ApplicationName,
+ ServiceVersion: version.Version,
+ // We never want sdk/go to capture prompt/completion bodies on
+ // our behalf. Coding-agent content capture is governed by the
+ // per-adapter handlers obeying cfg.CodingContentCapture.
+ DisableCaptureMessageContent: true,
+ // The hook subcommand is short-lived; batch span processor is
+ // fine — sdk/go calls Shutdown which forces a flush.
+ DisableBatch: false,
+ // Pricing fetch is irrelevant for the hook path; disabling it
+ // avoids a network call per invocation.
+ DisablePricingFetch: true,
+ // Metrics ARE enabled — the coding-agent counters
+ // (`coding_agent.lines_of_code.count`,
+ // `coding_agent.code_edit_tool.decision`,
+ // `coding_agent.commit.count`, `coding_agent.pull_request.count`)
+ // always emit, regardless of content-capture mode, so backends
+ // that consume metrics (Prometheus / Mimir / Grafana cloud)
+ // see the same numbers traces backends see. Cost of the
+ // metrics pipeline is negligible on the short-lived hook
+ // process; the openlit-go SDK already wires up a delta
+ // exporter on the same OTLP endpoint as traces.
+ DisableMetrics: false,
+ // All coding-agent spans for a given session share a
+ // deterministic TraceID (and the session-root span gets a
+ // deterministic SpanID) so PR #1200's TraceDetailView resolves
+ // the full session timeline as a single trace. See tracecontext.go.
+ IDGenerator: sessionIDGenerator{},
+ Sampler: defaultSampler(),
+ ExtraResourceAttributes: extra,
+ }); err != nil {
+ return nil, fmt.Errorf("openlit.Init: %w", err)
+ }
+
+ return &Emitter{
+ tracer: otel.GetTracerProvider().Tracer("openlit-cli"),
+ cfg: cfg,
+ vendor: vendor,
+ scrub: redact.ForCapture(cfg.CodingContentCapture),
+ startedAt: time.Now(),
+ }, nil
+}
+
+// Shutdown flushes pending spans within the context's deadline.
+func (e *Emitter) Shutdown(ctx context.Context) error {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if e.shut {
+ return nil
+ }
+ e.shut = true
+ return openlit.Shutdown(ctx)
+}
+
+// bumpToolCounter / bumpLLMCounter / bumpSubagentCounter persist
+// rolled-up totals into the sessionstate cache so the next process
+// reading the session (typically sessionEnd, which runs in its own
+// short-lived hook invocation) can stamp them on the session-root
+// span. Minimal capture mode relies on these to keep dashboards
+// useful without per-event spans.
+//
+// These are best-effort: a cross-process race could undercount by a
+// few events. The flock + atomic rename added in D1 keeps the file
+// consistent; a tiny race window remains between Load and Save.
+func (e *Emitter) bumpToolCounter(sessionID string) {
+ if sessionID == "" {
+ return
+ }
+ st := sessionstate.Load(sessionID, e.vendor)
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ st.ToolCallCount++
+ sessionstate.Save(sessionID, e.vendor, st)
+}
+
+func (e *Emitter) bumpLLMCounter(sessionID string, in, out int64, cost float64) {
+ if sessionID == "" {
+ return
+ }
+ st := sessionstate.Load(sessionID, e.vendor)
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ if in > 0 {
+ st.InputTokens += in
+ }
+ if out > 0 {
+ st.OutputTokens += out
+ }
+ if cost > 0 {
+ st.CostUSD += cost
+ }
+ sessionstate.Save(sessionID, e.vendor, st)
+}
+
+func (e *Emitter) bumpSubagentCounter(sessionID string) {
+ if sessionID == "" {
+ return
+ }
+ st := sessionstate.Load(sessionID, e.vendor)
+ if st == nil {
+ st = &sessionstate.State{}
+ }
+ st.SubagentCount++
+ sessionstate.Save(sessionID, e.vendor, st)
+}
+
+// EmitSession turns a normalize.Session into a single span with
+// coding_agent.* + gen_ai.* attributes set.
+//
+// In minimal mode, before stamping attributes we drain the
+// sessionstate counters (tool calls, subagents, tokens, cost) and
+// fold them into the session struct so the session-root span carries
+// the rolled-up totals dashboards rely on.
+//
+// F2: we used to emit a session-root span on BOTH sessionStart and
+// sessionEnd. With the deterministic IDGenerator both calls produced
+// the same TraceID + SpanID — so otel_traces ended up with two rows
+// per session, doubling counts and breaking the duration math (the
+// first row has startedAt == endedAt, dragging averages to ~0). We
+// now skip emission for the "started" lifecycle and rely on the final
+// sessionEnd call to write the single authoritative row. Sessions
+// that never see a sessionEnd (process killed, network drop) still
+// show their child spans on the trace view by their session_id
+// resource attribute even without the root span. The trade-off:
+// "active" sessions don't appear in the Sessions list until they
+// finish, which beats the previous bug of every active session
+// counting twice.
+//
+// The lifecycle marker is the vendor-stamped Extras key
+// `<vendor>.session.lifecycle` (set to "started" by every adapter's
+// buildSession kind=started path). The previous guard checked
+// `s.Outcome == "started"` but adapters never set Outcome that way —
+// they only set it on END events ("completed" / "cancelled" / …), so
+// the guard was a no-op and the double-emit persisted in production.
+func isSessionStart(s normalize.Session) bool {
+ if s.Outcome == "started" || s.Outcome == "in_progress" {
+ return true
+ }
+ for _, k := range []string{
+ "cursor.session.lifecycle",
+ "claude_code.session.lifecycle",
+ "codex.session.lifecycle",
+ } {
+ if v, ok := s.Extras[k]; ok && v == "started" {
+ return true
+ }
+ }
+ return false
+}
+
+func (e *Emitter) EmitSession(s normalize.Session) error {
+ if e == nil || e.tracer == nil {
+ return errors.New("nil emitter")
+ }
+
+ if isSessionStart(s) {
+ return nil
+ }
+
+ if !perEventSpansAllowed(e.cfg.CodingContentCapture) {
+ s = drainCounters(s, e.vendor)
+ }
+ // LOC / edit / commit / PR rollups are stamped on the session-root
+ // span regardless of capture mode — they are scalar telemetry, not
+ // user content, and the Sessions list's "Lines / Accept %" columns
+ // rely on them being present in every mode.
+ s = drainCodeCounters(s, e.vendor)
+
+ startedAt := s.StartedAt
+ if startedAt.IsZero() {
+ startedAt = e.startedAt
+ }
+ endedAt := s.EndedAt
+ if endedAt.IsZero() {
+ endedAt = time.Now()
+ }
+
+ // Session-root span. We deliberately attach the session id as a
+ // marker in the context (no parent SpanContext) so the
+ // `sessionIDGenerator` produces the deterministic root TraceID +
+ // SpanID derived from `s.SessionID`. The CLI stamps `vcs.*`
+ // resource attributes on this span from local git context (see
+ // `cli/internal/coding/git/git.go`); no remote VCS integration is
+ // required.
+ _, span := e.tracer.Start(
+ sessionRootContext(context.Background(), s.SessionID, e.vendor),
+ semconv.CodingAgentSpanSession,
+ trace.WithTimestamp(startedAt),
+ trace.WithSpanKind(trace.SpanKindInternal),
+ )
+ defer span.End(trace.WithTimestamp(endedAt))
+
+ setSessionAttrs(span, s, e.scrub)
+ return nil
+}
+
+// EmitToolCall produces a coding-agent tool-call span. In minimal
+// capture mode this is a no-op at the span level — counters are
+// instead bumped on the session-state cache so they can be rolled
+// up onto the session-root span at sessionEnd.
+func (e *Emitter) EmitToolCall(t normalize.ToolCall) error {
+ if e == nil || e.tracer == nil {
+ return errors.New("nil emitter")
+ }
+ if !perEventSpansAllowed(e.cfg.CodingContentCapture) {
+ e.bumpToolCounter(t.SessionID)
+ return nil
+ }
+ startedAt := t.StartedAt
+ if startedAt.IsZero() {
+ startedAt = time.Now()
+ }
+ endedAt := t.EndedAt
+ if endedAt.IsZero() {
+ endedAt = startedAt.Add(t.Duration)
+ }
+
+ _, span := e.tracer.Start(
+ sessionTraceContext(context.Background(), t.SessionID, e.vendor),
+ semconv.CodingAgentSpanToolCall,
+ trace.WithTimestamp(startedAt),
+ trace.WithSpanKind(trace.SpanKindInternal),
+ )
+ defer span.End(trace.WithTimestamp(endedAt))
+
+ setToolCallAttrs(span, t, e.scrub, e.cfg.CodingContentCapture)
+ return nil
+}
+
+// EmitEditDecision produces an edit-decision span. We use a span (not an
+// event) so dashboards can drill into individual edits with their own
+// timeline rendering. Minimal mode drops the SPAN entirely (cost +
+// activity dashboards don't need per-edit drilldowns), but the
+// matching metric counters still emit so dashboards keep working.
+func (e *Emitter) EmitEditDecision(d normalize.EditDecision) error {
+ if e == nil || e.tracer == nil {
+ return errors.New("nil emitter")
+ }
+ // Always emit the metrics — even in minimal mode the dashboards
+ // rely on the per-decision counter, and the user-tag carries the
+ // session row through the user roll-ups.
+ user := resolveLocalUser()
+ recordEditDecision(d.Vendor, user, d.Decision, d.Tool, d.Language)
+ recordLines(d.Vendor, user, d.Decision, d.LinesAdded, d.LinesRemoved)
+ if !perEventSpansAllowed(e.cfg.CodingContentCapture) {
+ return nil
+ }
+ at := d.At
+ if at.IsZero() {
+ at = time.Now()
+ }
+ _, span := e.tracer.Start(
+ sessionTraceContext(context.Background(), d.SessionID, e.vendor),
+ semconv.CodingAgentSpanEditDecision,
+ trace.WithTimestamp(at),
+ trace.WithSpanKind(trace.SpanKindInternal),
+ )
+ defer span.End(trace.WithTimestamp(at))
+
+ setEditDecisionAttrs(span, d, e.scrub)
+ return nil
+}
+
+// EmitLLMTurn produces a coding_agent.llm.turn span representing one
+// user-prompt / assistant-response cycle. In minimal mode we instead
+// bump in/out/cost counters on the sessionstate cache for the session
+// bookend to read.
+func (e *Emitter) EmitLLMTurn(t normalize.LLMTurn) error {
+ if e == nil || e.tracer == nil {
+ return errors.New("nil emitter")
+ }
+ if !perEventSpansAllowed(e.cfg.CodingContentCapture) {
+ e.bumpLLMCounter(t.SessionID, t.InputTokens, t.OutputTokens, t.CostUSD)
+ return nil
+ }
+ startedAt := t.StartedAt
+ if startedAt.IsZero() {
+ startedAt = time.Now()
+ }
+ endedAt := t.EndedAt
+ if endedAt.IsZero() {
+ endedAt = startedAt
+ }
+
+ _, span := e.tracer.Start(
+ sessionTraceContext(context.Background(), t.SessionID, e.vendor),
+ semconv.CodingAgentSpanLLMTurn,
+ trace.WithTimestamp(startedAt),
+ trace.WithSpanKind(trace.SpanKindClient),
+ )
+ defer span.End(trace.WithTimestamp(endedAt))
+
+ setLLMTurnAttrs(span, t, e.scrub, e.cfg.CodingContentCapture)
+ return nil
+}
+
+// EmitSubagent produces a coding_agent.subagent span representing one
+// child-agent lifecycle. Minimal mode bumps the subagent counter and
+// drops the span — the parent's session bookend will surface the
+// count via SubagentCount.
+func (e *Emitter) EmitSubagent(s normalize.Subagent) error {
+ if e == nil || e.tracer == nil {
+ return errors.New("nil emitter")
+ }
+ if !perEventSpansAllowed(e.cfg.CodingContentCapture) {
+ e.bumpSubagentCounter(s.SessionID)
+ return nil
+ }
+ startedAt := s.StartedAt
+ if startedAt.IsZero() {
+ startedAt = time.Now()
+ }
+ endedAt := s.EndedAt
+ if endedAt.IsZero() {
+ if s.DurationMs > 0 {
+ endedAt = startedAt.Add(time.Duration(s.DurationMs) * time.Millisecond)
+ } else {
+ endedAt = startedAt
+ }
+ }
+
+ _, span := e.tracer.Start(
+ sessionTraceContext(context.Background(), s.SessionID, e.vendor),
+ semconv.CodingAgentSpanSubagent,
+ trace.WithTimestamp(startedAt),
+ trace.WithSpanKind(trace.SpanKindInternal),
+ )
+ defer span.End(trace.WithTimestamp(endedAt))
+
+ setSubagentAttrs(span, s, e.scrub)
+ return nil
+}
+
+// EmitEvent produces a low-cost child span (kind=internal) representing
+// a hook-event-only signal (e.g. coding_agent.shell.requested,
+// coding_agent.tool.requested). The span's parent is the deterministic
+// session-root SpanID derived from the session id, so it nests
+// correctly in TraceDetailView.
+//
+// We deliberately do NOT use `span.AddEvent(...)` on the session-root
+// here: hook events fire in their own short-lived processes, and the
+// session-root span is created (and closed) in a separate sessionStart
+// process. Re-opening it from a different process by SpanID would
+// create a duplicate row in `otel_traces` rather than mutate the
+// existing one. A short child span is the cleanest OTel pattern that
+// preserves the parent-child relationship the UI needs.
+//
+// Minimal mode drops the event — counters bumped elsewhere are
+// sufficient for budget + activity dashboards, and a per-event span
+// would defeat the cost benefit of the mode.
+func (e *Emitter) EmitEvent(ev normalize.EventEmission) error {
+ if e == nil || e.tracer == nil {
+ return errors.New("nil emitter")
+ }
+ if !perEventSpansAllowed(e.cfg.CodingContentCapture) {
+ return nil
+ }
+ at := ev.At
+ if at.IsZero() {
+ at = time.Now()
+ }
+ _, span := e.tracer.Start(
+ sessionTraceContext(context.Background(), ev.SessionID, e.vendor),
+ ev.Name,
+ trace.WithTimestamp(at),
+ trace.WithSpanKind(trace.SpanKindInternal),
+ )
+ defer span.End(trace.WithTimestamp(at))
+
+ if ev.SessionID != "" {
+ span.SetAttributes(attribute.String(semconv.CodingAgentSessionID, ev.SessionID))
+ }
+ for k, v := range ev.Attrs {
+ setAnyAttr(span, k, v, e.scrub)
+ }
+ return nil
+}
+
+// EmitGitCommit produces a `coding_agent.git.commit` span representing
+// one agent-attributed git commit and bumps the matching metric
+// counter. The session-state CommitCount is bumped by the adapter
+// before this call so the rollup is durable even if span emission
+// fails. Unlike per-tool spans, commit / PR spans are NOT suppressed
+// in minimal mode — they are far rarer than tool calls and the
+// dashboards rely on having a span row per commit for trace drilldown.
+func (e *Emitter) EmitGitCommit(c normalize.GitCommit) error {
+ if e == nil || e.tracer == nil {
+ return errors.New("nil emitter")
+ }
+ at := c.At
+ if at.IsZero() {
+ at = time.Now()
+ }
+ _, span := e.tracer.Start(
+ sessionTraceContext(context.Background(), c.SessionID, e.vendor),
+ semconv.CodingAgentSpanGitCommit,
+ trace.WithTimestamp(at),
+ trace.WithSpanKind(trace.SpanKindInternal),
+ )
+ defer span.End(trace.WithTimestamp(at))
+ setGitCommitAttrs(span, c, e.scrub, e.cfg.CodingContentCapture)
+ recordCommit(c.Vendor, c.UserID)
+ return nil
+}
+
+// EmitGitPullRequest produces a `coding_agent.git.pull_request` span
+// representing one agent-attributed PR / MR create and bumps the
+// matching metric counter. See EmitGitCommit for the minimal-mode
+// rationale.
+func (e *Emitter) EmitGitPullRequest(p normalize.GitPullRequest) error {
+ if e == nil || e.tracer == nil {
+ return errors.New("nil emitter")
+ }
+ at := p.At
+ if at.IsZero() {
+ at = time.Now()
+ }
+ _, span := e.tracer.Start(
+ sessionTraceContext(context.Background(), p.SessionID, e.vendor),
+ semconv.CodingAgentSpanGitPullRequest,
+ trace.WithTimestamp(at),
+ trace.WithSpanKind(trace.SpanKindInternal),
+ )
+ defer span.End(trace.WithTimestamp(at))
+ setGitPullRequestAttrs(span, p, e.scrub, e.cfg.CodingContentCapture)
+ recordPullRequest(p.Vendor, p.UserID)
+ return nil
+}
diff --git a/cli/internal/otlp/host_detect_test.go b/cli/internal/otlp/host_detect_test.go
new file mode 100644
index 00000000..0b8b17c9
--- /dev/null
+++ b/cli/internal/otlp/host_detect_test.go
@@ -0,0 +1,60 @@
+package otlp
+
+import "testing"
+
+// TestDetectHostFromBinary pins the cross-platform host matcher. The
+// matcher must recognise the same logical host across macOS bundle
+// paths, Linux binary names, and Windows .exe basenames — three very
+// different conventions converging on one label.
+func TestDetectHostFromBinary(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ in string
+ want string
+ }{
+ // Cursor across platforms.
+ {"cursor-macos", "/Applications/Cursor.app/Contents/MacOS/Cursor", "cursor"},
+ {"cursor-macos-helper", "/Applications/Cursor.app/Contents/Frameworks/Cursor Helper.app/Contents/MacOS/Cursor Helper", "cursor"},
+ {"cursor-linux", "/usr/share/cursor/cursor", "cursor"},
+ {"cursor-windows", `C:\Users\me\AppData\Local\Programs\cursor\Cursor.exe`, "cursor"},
+
+ // VS Code across platforms.
+ {"vscode-macos", "/Applications/Visual Studio Code.app/Contents/MacOS/Electron", "vscode"},
+ {"vscode-macos-helper", "/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper.app/Contents/MacOS/Code Helper", "vscode"},
+ {"vscode-windows", `C:\Users\me\AppData\Local\Programs\Microsoft VS Code\Code.exe`, "vscode"},
+ {"vscodium-windows", `C:\Program Files\VSCodium\VSCodium.exe`, "vscode"},
+
+ // Terminals.
+ {"warp-macos", "/Applications/Warp.app/Contents/MacOS/stable", "warp"},
+ {"warp-windows", `C:\Users\me\AppData\Local\Programs\Warp\Warp.exe`, "warp"},
+ {"wezterm-linux", "/usr/bin/wezterm-gui", "wezterm"},
+ {"wezterm-windows", `C:\Program Files\WezTerm\wezterm-gui.exe`, "wezterm"},
+
+ // Windows-only hosts.
+ {"windows-terminal", `C:\Program Files\WindowsApps\Microsoft.WindowsTerminal_1.18\WindowsTerminal.exe`, "windows-terminal"},
+ {"windows-terminal-wt", `C:\Users\me\AppData\Local\Microsoft\WindowsApps\wt.exe`, "windows-terminal"},
+ {"powershell-pwsh", `C:\Program Files\PowerShell\7\pwsh.exe`, "powershell"},
+ {"powershell-legacy", `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`, "powershell"},
+ {"cmd", `C:\Windows\System32\cmd.exe`, "cmd"},
+
+ // JetBrains across platforms.
+ {"jetbrains-macos", "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea", "jetbrains"},
+ {"jetbrains-windows", `C:\Program Files\JetBrains\IntelliJ IDEA 2025.3\bin\idea64.exe`, "jetbrains"},
+
+ // Negative cases.
+ {"empty", "", ""},
+ {"unrelated", "/usr/bin/bash", ""},
+ {"unrelated-windows", `C:\Windows\System32\notepad.exe`, ""},
+ }
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got := detectHostFromBinary(tc.in)
+ if got != tc.want {
+ t.Errorf("detectHostFromBinary(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/cli/internal/otlp/metrics.go b/cli/internal/otlp/metrics.go
new file mode 100644
index 00000000..f9a20d76
--- /dev/null
+++ b/cli/internal/otlp/metrics.go
@@ -0,0 +1,159 @@
+// metrics.go — coding-agent OTel metrics, emitted alongside the
+// matching spans so backends that consume metrics see the same
+// numbers traces backends see.
+//
+// We always emit these counters, regardless of content-capture mode:
+//
+// - `coding_agent.lines_of_code.count` — added / removed lines,
+// tagged with type=added|removed, decision (accept/reject/auto),
+// vendor, user.
+// - `coding_agent.code_edit_tool.decision` — count of edit
+// decisions, tagged with decision, vendor, tool_name, language,
+// user.
+// - `coding_agent.commit.count` — agent-attributed git commits,
+// tagged with vendor, user.
+// - `coding_agent.pull_request.count` — agent-attributed pull/merge
+// requests, tagged with vendor, user.
+//
+// The instruments are package-level so they survive the lifetime of
+// the in-process MeterProvider (one per hook invocation). Lazily
+// initialised on first use so a `NewEmitter` failure path that never
+// calls Init still leaves them as nil and the Record* helpers no-op.
+package otlp
+
+import (
+ "context"
+ "sync"
+
+ "github.com/openlit/openlit/sdk/go/semconv"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/metric"
+)
+
+var (
+ meterOnce sync.Once
+ linesOfCodeCnt metric.Int64Counter
+ editDecisionCnt metric.Int64Counter
+ commitCnt metric.Int64Counter
+ pullRequestCnt metric.Int64Counter
+)
+
+// initMetrics initialises the coding-agent metric instruments on
+// first use. The function is safe to call repeatedly; only the first
+// call does any work. Returns silently on instrument-creation
+// failure — the helpers downstream all guard against a nil counter.
+func initMetrics() {
+ meterOnce.Do(func() {
+ m := otel.GetMeterProvider().Meter("openlit-cli/coding_agent")
+ var err error
+ if linesOfCodeCnt, err = m.Int64Counter(
+ semconv.CodingAgentMetricLinesOfCode,
+ metric.WithDescription("Lines of code added or removed by a coding-agent edit, grouped by accept/reject decision."),
+ metric.WithUnit("{line}"),
+ ); err != nil {
+ linesOfCodeCnt = nil
+ }
+ if editDecisionCnt, err = m.Int64Counter(
+ semconv.CodingAgentMetricEditDecisionCnt,
+ metric.WithDescription("Count of coding-agent edit decisions, by accept/reject/modify."),
+ metric.WithUnit("{decision}"),
+ ); err != nil {
+ editDecisionCnt = nil
+ }
+ if commitCnt, err = m.Int64Counter(
+ semconv.CodingAgentMetricCommit,
+ metric.WithDescription("Count of agent-attributed git commits."),
+ metric.WithUnit("{commit}"),
+ ); err != nil {
+ commitCnt = nil
+ }
+ if pullRequestCnt, err = m.Int64Counter(
+ semconv.CodingAgentMetricPullRequest,
+ metric.WithDescription("Count of agent-attributed pull/merge requests."),
+ metric.WithUnit("{pull_request}"),
+ ); err != nil {
+ pullRequestCnt = nil
+ }
+ })
+}
+
+// commonAttrs builds the standard set of attribute tags used on the
+// commit / PR counters. We deliberately keep the cardinality low —
+// only vendor + user. Per-session tags would explode metric series.
+func commonAttrs(vendor, user string) []attribute.KeyValue {
+ out := make([]attribute.KeyValue, 0, 2)
+ if vendor != "" {
+ out = append(out, attribute.String(semconv.CodingAgentClient, vendor))
+ }
+ if user != "" {
+ out = append(out, attribute.String(semconv.GenAIRequestUser, user))
+ }
+ return out
+}
+
+// recordLines bumps `coding_agent.lines_of_code.count` once for added
+// and once for removed (so backends can sum / split via the `type`
+// tag). Decision identifies whether the change landed (accept /
+// auto_accepted) or didn't (reject) so the resulting metric series
+// can drive the "acceptance %" dashboard widget.
+func recordLines(vendor, user, decision string, added, removed int) {
+ initMetrics()
+ if linesOfCodeCnt == nil {
+ return
+ }
+ if added == 0 && removed == 0 {
+ return
+ }
+ ctx := context.Background()
+ base := commonAttrs(vendor, user)
+ if decision != "" {
+ base = append(base, attribute.String(semconv.CodingAgentEditDecision, decision))
+ }
+ if added > 0 {
+ linesOfCodeCnt.Add(ctx, int64(added), metric.WithAttributes(append(base, attribute.String("type", "added"))...))
+ }
+ if removed > 0 {
+ linesOfCodeCnt.Add(ctx, int64(removed), metric.WithAttributes(append(base, attribute.String("type", "removed"))...))
+ }
+}
+
+// recordEditDecision bumps `coding_agent.code_edit_tool.decision` by
+// one. tool / language are best-effort tags.
+func recordEditDecision(vendor, user, decision, tool, language string) {
+ initMetrics()
+ if editDecisionCnt == nil {
+ return
+ }
+ if decision == "" {
+ return
+ }
+ ctx := context.Background()
+ attrs := commonAttrs(vendor, user)
+ attrs = append(attrs, attribute.String(semconv.CodingAgentEditDecision, decision))
+ if tool != "" {
+ attrs = append(attrs, attribute.String(semconv.CodingAgentEditToolName, tool))
+ }
+ if language != "" {
+ attrs = append(attrs, attribute.String(semconv.CodingAgentEditLanguage, language))
+ }
+ editDecisionCnt.Add(ctx, 1, metric.WithAttributes(attrs...))
+}
+
+// recordCommit bumps `coding_agent.commit.count` by one.
+func recordCommit(vendor, user string) {
+ initMetrics()
+ if commitCnt == nil {
+ return
+ }
+ commitCnt.Add(context.Background(), 1, metric.WithAttributes(commonAttrs(vendor, user)...))
+}
+
+// recordPullRequest bumps `coding_agent.pull_request.count` by one.
+func recordPullRequest(vendor, user string) {
+ initMetrics()
+ if pullRequestCnt == nil {
+ return
+ }
+ pullRequestCnt.Add(context.Background(), 1, metric.WithAttributes(commonAttrs(vendor, user)...))
+}
diff --git a/cli/internal/otlp/process_other.go b/cli/internal/otlp/process_other.go
new file mode 100644
index 00000000..bbcab162
--- /dev/null
+++ b/cli/internal/otlp/process_other.go
@@ -0,0 +1,14 @@
+//go:build !darwin && !linux && !windows
+
+package otlp
+
+import "fmt"
+
+// readProcessNameAndPPIDOS is unimplemented on exotic platforms (plan9,
+// js/wasm, the various BSDs we don't ship binaries for, etc.). The host-
+// detection walk simply short-circuits, returning "" — the caller already
+// treats process-tree walking as a best-effort fallback. macOS, Linux,
+// and Windows have proper implementations in their own _<os>.go files.
+func readProcessNameAndPPIDOS(pid int) (string, int, error) {
+ return "", 0, fmt.Errorf("process introspection unsupported on this platform")
+}
diff --git a/cli/internal/otlp/process_unix.go b/cli/internal/otlp/process_unix.go
new file mode 100644
index 00000000..28fc44ab
--- /dev/null
+++ b/cli/internal/otlp/process_unix.go
@@ -0,0 +1,84 @@
+//go:build darwin || linux
+
+package otlp
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// psTimeout caps how long the macOS `ps` fallback may run. Host
+// detection walks up to ~12 ancestors from a cold start (see the
+// readProcessNameAndPPIDOS callers in exporter.go), so an unbounded
+// `ps` invocation that hung even briefly could compound into a full
+// stall of the 5s hook budget. 100ms is generous for a process that
+// normally returns in single-digit ms.
+const psTimeout = 100 * time.Millisecond
+
+// readProcessNameAndPPIDOS returns the argv[0] and parent pid of `pid`.
+// On Linux it reads /proc directly; on macOS it shells out to `ps`.
+// Failures bubble up so the caller can short-circuit the host-detection
+// walk — telemetry must never fail on a missing process.
+func readProcessNameAndPPIDOS(pid int) (string, int, error) {
+ if pid <= 0 {
+ return "", 0, fmt.Errorf("invalid pid %d", pid)
+ }
+ // Linux: /proc is always cheaper and stable.
+ if data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)); err == nil {
+ // /proc/PID/stat layout: pid (comm) state ppid …
+ // `comm` is parenthesised and may contain spaces, so we
+ // search for the FINAL ')' before extracting the rest.
+ s := string(data)
+ if end := strings.LastIndex(s, ")"); end > 0 {
+ fields := strings.Fields(s[end+1:])
+ if len(fields) >= 2 {
+ ppid, perr := strconv.Atoi(fields[1])
+ if perr == nil {
+ if cmdline, cerr := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)); cerr == nil {
+ argv0 := string(cmdline)
+ if idx := strings.IndexByte(argv0, 0); idx >= 0 {
+ argv0 = argv0[:idx]
+ }
+ return argv0, ppid, nil
+ }
+ }
+ }
+ }
+ }
+ // macOS / fallback: `ps -o ppid=,command= -p <pid>` returns
+ // " <ppid> <full command line>" on one line. `command=` strips
+ // the header. The CommandContext bound bails immediately if a
+ // hung `ps` would otherwise dominate the hook budget.
+ psCtx, cancel := context.WithTimeout(context.Background(), psTimeout)
+ defer cancel()
+ out, err := exec.CommandContext(psCtx, "ps", "-o", "ppid=,command=", "-p", strconv.Itoa(pid)).Output()
+ if err != nil {
+ return "", 0, err
+ }
+ line := strings.TrimSpace(string(out))
+ if line == "" {
+ return "", 0, fmt.Errorf("no process %d", pid)
+ }
+ // Split into ppid + command. The first whitespace-separated token
+ // is the ppid; the remainder is argv[0] (possibly with args).
+ fields := strings.Fields(line)
+ if len(fields) < 2 {
+ return "", 0, fmt.Errorf("unparseable ps output for pid %d: %q", pid, line)
+ }
+ ppid, err := strconv.Atoi(fields[0])
+ if err != nil {
+ return "", 0, err
+ }
+ bin := strings.Join(fields[1:], " ")
+ // argv[0] is the binary path before the first space — drop later
+ // args so substring matching is reliable.
+ if idx := strings.IndexByte(bin, ' '); idx > 0 {
+ bin = bin[:idx]
+ }
+ return bin, ppid, nil
+}
diff --git a/cli/internal/otlp/process_windows.go b/cli/internal/otlp/process_windows.go
new file mode 100644
index 00000000..d0b9deb3
--- /dev/null
+++ b/cli/internal/otlp/process_windows.go
@@ -0,0 +1,73 @@
+//go:build windows
+
+package otlp
+
+import (
+ "fmt"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+// readProcessNameAndPPIDOS — Windows implementation. Walks the
+// Toolhelp32 snapshot once to find the matching pid (cheap; the
+// snapshot is in-memory and the OS already has the data ready). Then
+// opens that process with PROCESS_QUERY_LIMITED_INFORMATION (the
+// minimal right that works for non-elevated callers across all
+// supported Windows versions) and reads the full executable path. We
+// fall back to the snapshot's ExeFile basename if
+// QueryFullProcessImageName fails — protected system processes deny
+// PROCESS_QUERY_LIMITED_INFORMATION on hardened hosts but the snapshot
+// is always readable.
+//
+// Why Toolhelp and not psapi.EnumProcesses? Toolhelp returns ppid
+// directly in the same snapshot pass; EnumProcesses doesn't, and we'd
+// have to make a second OpenProcess call per pid anyway. Toolhelp is
+// the cheaper single-pass path.
+func readProcessNameAndPPIDOS(pid int) (string, int, error) {
+ if pid <= 0 {
+ return "", 0, fmt.Errorf("invalid pid %d", pid)
+ }
+ snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)
+ if err != nil {
+ return "", 0, fmt.Errorf("CreateToolhelp32Snapshot: %w", err)
+ }
+ defer windows.CloseHandle(snap)
+
+ var entry windows.ProcessEntry32
+ entry.Size = uint32(unsafe.Sizeof(entry))
+ if err := windows.Process32First(snap, &entry); err != nil {
+ return "", 0, fmt.Errorf("Process32First: %w", err)
+ }
+ for {
+ if int(entry.ProcessID) == pid {
+ ppid := int(entry.ParentProcessID)
+ if full, ferr := queryFullImageName(entry.ProcessID); ferr == nil && full != "" {
+ return full, ppid, nil
+ }
+ // Fallback: snapshot basename (e.g. "cursor.exe").
+ return windows.UTF16ToString(entry.ExeFile[:]), ppid, nil
+ }
+ if err := windows.Process32Next(snap, &entry); err != nil {
+ break
+ }
+ }
+ return "", 0, fmt.Errorf("no process %d", pid)
+}
+
+// queryFullImageName resolves a pid's full executable path via the
+// QueryFullProcessImageNameW Win32 API. Returns "" + error if the
+// process is gone or denies the open.
+func queryFullImageName(pid uint32) (string, error) {
+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
+ if err != nil {
+ return "", err
+ }
+ defer windows.CloseHandle(h)
+ buf := make([]uint16, windows.MAX_PATH)
+ size := uint32(len(buf))
+ if err := windows.QueryFullProcessImageName(h, 0, &buf[0], &size); err != nil {
+ return "", err
+ }
+ return windows.UTF16ToString(buf[:size]), nil
+}
diff --git a/cli/internal/otlp/sampler.go b/cli/internal/otlp/sampler.go
new file mode 100644
index 00000000..b1defcd8
--- /dev/null
+++ b/cli/internal/otlp/sampler.go
@@ -0,0 +1,81 @@
+// Head sampling for the coding-agent hook pipeline. Wires into the
+// SDK via openlit.Config.Sampler.
+//
+// Beta default (used when OPENLIT_CODING_SAMPLE_EVENTS is unset): keep
+// everything. Operators with high-volume hosts can drop the noisy
+// "*.requested" events while keeping session bookends, tool.call, and
+// llm.turn — the spans dashboards actually read.
+//
+// Set OPENLIT_CODING_SAMPLE_EVENTS=drop_requested to enable the
+// pre-canned policy. Future modes can extend the switch below
+// without changing call sites.
+
+package otlp
+
+import (
+ "os"
+ "strings"
+
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
+ "go.opentelemetry.io/otel/trace"
+)
+
+// sampleEventsEnv controls which head sampling policy the hook uses.
+// We intentionally read it once at sampler construction time so the
+// value is stable for the lifetime of the hook process.
+const sampleEventsEnv = "OPENLIT_CODING_SAMPLE_EVENTS"
+
+// defaultSampler returns the sampler the hook should plug into the
+// SDK. Returns nil to mean "let the SDK pick its default
+// (AlwaysSample)" so the beta posture stays unchanged for ops who
+// haven't opted in.
+func defaultSampler() sdktrace.Sampler {
+ mode := strings.ToLower(strings.TrimSpace(os.Getenv(sampleEventsEnv)))
+ switch mode {
+ case "", "all", "always_on":
+ return nil
+ case "drop_requested":
+ // Drop the per-tool/per-shell "requested" events but keep
+ // every other span. These events fire once per pending tool
+ // invocation and are pure noise for cost / outcome
+ // dashboards — yet on a chatty session they account for
+ // roughly 1/3 of all spans.
+ return spanNameSampler{
+ drop: map[string]struct{}{
+ "coding_agent.tool.requested": {},
+ "coding_agent.shell.requested": {},
+ "coding_agent.mcp.tool.requested": {},
+ "coding_agent.user_prompt.submit": {},
+ },
+ }
+ default:
+ // Unknown values fall back to AlwaysSample; we never want
+ // a typo in an env var to silently drop telemetry.
+ return nil
+ }
+}
+
+// spanNameSampler is a head sampler that drops spans whose name is
+// in `drop` and keeps everything else. Faster than the OTel
+// composite samplers for our very small drop list, and easier to
+// reason about than ParentBased.
+type spanNameSampler struct {
+ drop map[string]struct{}
+}
+
+func (s spanNameSampler) ShouldSample(p sdktrace.SamplingParameters) sdktrace.SamplingResult {
+ if _, drop := s.drop[p.Name]; drop {
+ return sdktrace.SamplingResult{
+ Decision: sdktrace.Drop,
+ Tracestate: trace.SpanContextFromContext(p.ParentContext).TraceState(),
+ }
+ }
+ return sdktrace.SamplingResult{
+ Decision: sdktrace.RecordAndSample,
+ Tracestate: trace.SpanContextFromContext(p.ParentContext).TraceState(),
+ }
+}
+
+func (s spanNameSampler) Description() string {
+ return "openlit.coding_agent.span_name_sampler"
+}
diff --git a/cli/internal/otlp/string.go b/cli/internal/otlp/string.go
new file mode 100644
index 00000000..546288c7
--- /dev/null
+++ b/cli/internal/otlp/string.go
@@ -0,0 +1,9 @@
+package otlp
+
+import "fmt"
+
+// defaultString isolates the fmt import to a single tiny file. Used as
+// the last-resort fallback for non-string values flowing through EmitEvent.
+func defaultString(v any) string {
+ return fmt.Sprintf("%v", v)
+}
diff --git a/cli/internal/otlp/tracecontext.go b/cli/internal/otlp/tracecontext.go
new file mode 100644
index 00000000..3c7c7fe5
--- /dev/null
+++ b/cli/internal/otlp/tracecontext.go
@@ -0,0 +1,210 @@
+// Package otlp — see exporter.go for the package overview.
+//
+// This file makes every span emitted across separate hook invocations
+// for the same coding-agent session land in the same OTel trace, with
+// a stable session-root span the children all reference as parent.
+//
+// Why we need it
+// --------------
+// Each Cursor / Claude Code / Codex hook fires its own
+// `openlit coding hook` process. Without coordination every emitted
+// span would generate its own random TraceId — the otel_traces table
+// would have one trace per emit, correlated only by the
+// `coding_agent.session.id` attribute. The new trace-detail UI
+// (PR #1200's `TraceDetailView` + `SpanHierarchyExplorer`) walks the
+// trace tree by TraceId+ParentSpanId, so it would show one orphan
+// span per hook event instead of a real session timeline.
+//
+// How it works
+// ------------
+// - traceID = first 16 bytes of HMAC(session_id + "|" + vendor) (stable across processes)
+// - rootSpanID = first 8 bytes of HMAC(session_id + "|" + vendor + "|root") (stable across processes)
+//
+// The vendor is mixed into the derivation so an agent running INSIDE
+// another agent (e.g. Claude Code launched from a Cursor terminal) gets
+// its own trace even when the host editor leaks its session id into
+// the guest's environment. Without this, both vendors' spans would
+// collapse onto the same TraceID and the trace-detail view would
+// interleave them — the user explicitly wants per-vendor isolation
+// ("cursor chat in cursor sessions, claude code chats in claude code
+// sessions no matter the terminal").
+//
+// For NON-session emissions (LLMTurn, ToolCall, EditDecision, Subagent,
+// Event), we wrap the parent context with `sessionTraceContext` which
+// installs a remote SpanContext carrying the deterministic TraceID +
+// rootSpanID. OTel's Start sees a valid parent and reuses the TraceID;
+// the new span gets a random SpanID and the deterministic rootSpanID
+// as its ParentSpanId.
+//
+// For the SESSION span itself we use `sessionRootContext`, which marks
+// the context with a sentinel value but DOES NOT set a parent
+// SpanContext — so OTel treats the span as a trace root and asks our
+// custom IDGenerator (`sessionIDGenerator`) for fresh IDs. The
+// generator's NewIDs() reads the sentinel and returns the deterministic
+// (traceID, rootSpanID); for every other span it falls back to random.
+package otlp
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "os"
+
+ "go.opentelemetry.io/otel/sdk/trace"
+ otrace "go.opentelemetry.io/otel/trace"
+)
+
+// Per-deployment salt mixed into the derived TraceID so the session id
+// can't be reverse-engineered from the trace id. Without the salt, an
+// adversary observing TraceIDs (e.g. via shared logging infrastructure)
+// could probe candidate session ids and confirm matches by recomputing
+// the hash.
+//
+// HMAC-SHA256 instead of plain sha256 makes the salt the key, so
+// without it the TraceID looks like a uniform random value. We read
+// the salt once at package init from `OPENLIT_TRACEID_SALT`;
+// deployments are expected to set a long-lived random value (e.g.
+// 32-byte hex). When the env var is unset, we fall back to an empty
+// key — the TraceID stays stable across processes as long as the
+// salt is stable, which is the correlation guarantee we need.
+var traceIDSalt = func() []byte {
+ if v := os.Getenv("OPENLIT_TRACEID_SALT"); v != "" {
+ return []byte(v)
+ }
+ return nil
+}()
+
+// sessionRootMarkerKey is the context key used to flag the in-flight
+// session-root span so `sessionIDGenerator.NewIDs` returns deterministic
+// IDs derived from the carried session id. We keep it private so only
+// this file can emit a session-root span.
+type sessionRootMarkerKey struct{}
+
+// sessionRootMarker carries the session id + vendor along with the
+// marker. Vendor is mixed into the deterministic derivation so an
+// agent running INSIDE another agent (e.g. Claude Code launched from
+// a Cursor terminal) gets a distinct trace even when the host's
+// session id leaks into the guest's environment.
+type sessionRootMarker struct {
+ sessionID string
+ vendor string
+}
+
+// deriveSessionTraceID produces a deterministic 16-byte TraceID from a
+// (session id, vendor) pair. Two CLI invocations that share BOTH
+// values derive the same TraceID without coordinating via shared
+// storage; two invocations that differ in vendor get distinct traces
+// so the trace-detail view never interleaves a Cursor turn with a
+// Claude Code turn for the same chat id.
+//
+// F1: keyed with `OPENLIT_TRACEID_SALT` via HMAC-SHA256 so neither the
+// session id nor the vendor can be brute-forced back from the
+// TraceID.
+func deriveSessionTraceID(sessionID, vendor string) otrace.TraceID {
+ mac := hmac.New(sha256.New, traceIDSalt)
+ mac.Write([]byte(sessionID + "|" + vendor))
+ sum := mac.Sum(nil)
+ var tid otrace.TraceID
+ copy(tid[:], sum[:16])
+ return tid
+}
+
+// deriveSessionRootSpanID produces a deterministic 8-byte SpanID for the
+// session-root span. Children stamp this as their ParentSpanId so the
+// trace tree resolves cleanly.
+//
+// Mirrors deriveSessionTraceID's vendor mixing so each vendor's
+// session-root span has a unique SpanID even when the chat id matches.
+func deriveSessionRootSpanID(sessionID, vendor string) otrace.SpanID {
+ mac := hmac.New(sha256.New, traceIDSalt)
+ mac.Write([]byte(sessionID + "|" + vendor + "|root"))
+ sum := mac.Sum(nil)
+ var sid otrace.SpanID
+ copy(sid[:], sum[:8])
+ return sid
+}
+
+// sessionTraceContext wraps `parent` with a remote SpanContext that
+// carries the deterministic (traceID, rootSpanID) for the (session,
+// vendor) pair. Use this for every NON-session emission so OTel
+// treats the span as a child of the session root.
+//
+// When sessionID is empty the parent context is returned unchanged —
+// callers that have no session correlation (e.g. ad-hoc debug events)
+// keep their existing behavior.
+func sessionTraceContext(parent context.Context, sessionID, vendor string) context.Context {
+ if sessionID == "" {
+ return parent
+ }
+ sc := otrace.NewSpanContext(otrace.SpanContextConfig{
+ TraceID: deriveSessionTraceID(sessionID, vendor),
+ SpanID: deriveSessionRootSpanID(sessionID, vendor),
+ TraceFlags: otrace.FlagsSampled,
+ Remote: true,
+ })
+ return otrace.ContextWithSpanContext(parent, sc)
+}
+
+// sessionRootContext flags `parent` so the next span started against it
+// will be treated by `sessionIDGenerator` as the session-root span and
+// receive deterministic ids.
+//
+// The session-root span MUST have NO parent SpanContext on its starting
+// context — OTel's tracer.Start only calls IDGenerator.NewIDs (which
+// produces both TraceID and SpanID) when the parent context lacks a
+// valid SpanContext. So this helper deliberately does NOT install a
+// SpanContext; it only stamps the marker.
+func sessionRootContext(parent context.Context, sessionID, vendor string) context.Context {
+ if sessionID == "" {
+ return parent
+ }
+ return context.WithValue(parent, sessionRootMarkerKey{}, sessionRootMarker{sessionID: sessionID, vendor: vendor})
+}
+
+// sessionIDGenerator is the trace.IDGenerator wired into the SDK. It
+// returns deterministic ids when the context carries a sessionRootMarker
+// (i.e. when starting a coding-agent session-root span); otherwise it
+// falls back to crypto/rand-backed random ids so every other span keeps
+// the standard OTel uniqueness guarantees.
+type sessionIDGenerator struct{}
+
+// NewIDs is invoked by OTel when a span has no parent SpanContext —
+// i.e. when we are starting a trace root. We treat the root as the
+// session span when the marker is present.
+func (sessionIDGenerator) NewIDs(ctx context.Context) (otrace.TraceID, otrace.SpanID) {
+ if marker, ok := ctx.Value(sessionRootMarkerKey{}).(sessionRootMarker); ok && marker.sessionID != "" {
+ return deriveSessionTraceID(marker.sessionID, marker.vendor), deriveSessionRootSpanID(marker.sessionID, marker.vendor)
+ }
+ return randomTraceID(), randomSpanID()
+}
+
+// NewSpanID is invoked when starting a child span. Children get random
+// SpanIDs unconditionally — the determinism only matters for the
+// session-root SpanId so children can reference it as ParentSpanId.
+func (sessionIDGenerator) NewSpanID(_ context.Context, _ otrace.TraceID) otrace.SpanID {
+ return randomSpanID()
+}
+
+// Compile-time assertion that we implement the SDK contract.
+var _ trace.IDGenerator = sessionIDGenerator{}
+
+func randomTraceID() otrace.TraceID {
+ var tid otrace.TraceID
+ for {
+ _, _ = rand.Read(tid[:])
+ if tid.IsValid() {
+ return tid
+ }
+ }
+}
+
+func randomSpanID() otrace.SpanID {
+ var sid otrace.SpanID
+ for {
+ _, _ = rand.Read(sid[:])
+ if sid.IsValid() {
+ return sid
+ }
+ }
+}
diff --git a/cli/internal/otlp/tracecontext_test.go b/cli/internal/otlp/tracecontext_test.go
new file mode 100644
index 00000000..c2b4f1a0
--- /dev/null
+++ b/cli/internal/otlp/tracecontext_test.go
@@ -0,0 +1,245 @@
+package otlp
+
+import (
+ "context"
+ "testing"
+
+ "go.opentelemetry.io/otel/sdk/trace"
+ "go.opentelemetry.io/otel/sdk/trace/tracetest"
+ otrace "go.opentelemetry.io/otel/trace"
+)
+
+// newTestTracer builds a tracer that mirrors the production wiring —
+// our `sessionIDGenerator` plus a synchronous in-memory exporter — so a
+// test can drive the same code paths the real Emitter takes without
+// going through openlit.Init's HTTP exporter.
+func newTestTracer(t *testing.T) (otrace.Tracer, *tracetest.InMemoryExporter, func()) {
+ t.Helper()
+ exp := tracetest.NewInMemoryExporter()
+ tp := trace.NewTracerProvider(
+ // SimpleSpanProcessor flushes synchronously — `tracer.Start +
+ // span.End` is enough; no explicit force-flush call needed.
+ trace.WithSpanProcessor(trace.NewSimpleSpanProcessor(exp)),
+ trace.WithIDGenerator(sessionIDGenerator{}),
+ )
+ tracer := tp.Tracer("openlit-cli-test")
+ return tracer, exp, func() {
+ _ = tp.Shutdown(context.Background())
+ }
+}
+
+func TestSessionTraceContext_DerivesStableIDs(t *testing.T) {
+ const sessionID = "sess-abc-123"
+ const vendor = "cursor"
+
+ tid1 := deriveSessionTraceID(sessionID, vendor)
+ tid2 := deriveSessionTraceID(sessionID, vendor)
+ if tid1 != tid2 {
+ t.Fatalf("traceID not stable across calls: %v vs %v", tid1, tid2)
+ }
+ if !tid1.IsValid() {
+ t.Fatalf("derived traceID must be non-zero")
+ }
+
+ rid1 := deriveSessionRootSpanID(sessionID, vendor)
+ rid2 := deriveSessionRootSpanID(sessionID, vendor)
+ if rid1 != rid2 {
+ t.Fatalf("rootSpanID not stable across calls: %v vs %v", rid1, rid2)
+ }
+ if !rid1.IsValid() {
+ t.Fatalf("derived rootSpanID must be non-zero")
+ }
+
+ // Different sessions must produce different ids.
+ otherTID := deriveSessionTraceID("sess-other", vendor)
+ if otherTID == tid1 {
+ t.Fatalf("trace ids collided across distinct sessions")
+ }
+
+ // Same session id but different vendor must produce different
+ // trace ids — this is the nested-agent isolation contract.
+ differentVendorTID := deriveSessionTraceID(sessionID, "claude-code")
+ if differentVendorTID == tid1 {
+ t.Fatalf("trace ids collided across vendors for the same session id; nested-agent isolation broken")
+ }
+ differentVendorRID := deriveSessionRootSpanID(sessionID, "claude-code")
+ if differentVendorRID == rid1 {
+ t.Fatalf("root span ids collided across vendors for the same session id")
+ }
+}
+
+func TestSessionTraceContext_EmptySessionPassthrough(t *testing.T) {
+ parent := context.Background()
+ got := sessionTraceContext(parent, "", "cursor")
+ if got != parent {
+ t.Fatalf("sessionTraceContext('') must return parent unchanged so non-coding callers are untouched")
+ }
+ got = sessionRootContext(parent, "", "cursor")
+ if got != parent {
+ t.Fatalf("sessionRootContext('') must return parent unchanged")
+ }
+}
+
+// TestEmitFlow_OneTracePerSession is the single most important
+// regression: every emission for the same `coding_agent.session.id`
+// MUST land in one OTel trace, with the session-root span's SpanID
+// reused as ParentSpanId by every child. PR #1200's TraceDetailView
+// will not render the timeline correctly without this property.
+func TestEmitFlow_OneTracePerSession(t *testing.T) {
+ tracer, exp, done := newTestTracer(t)
+ defer done()
+
+ const sessionID = "session-emitflow-001"
+ const vendor = "cursor"
+
+ // 1) Session-root span — uses sessionRootContext so the IDGenerator
+ // returns the deterministic (traceID, rootSpanID).
+ _, sessSpan := tracer.Start(
+ sessionRootContext(context.Background(), sessionID, vendor),
+ "coding_agent.session",
+ )
+ sessSpan.End()
+
+ // 2..5) Children — use sessionTraceContext so they inherit the
+ // derived TraceID and stamp the deterministic rootSpanID as
+ // their ParentSpanId.
+ for _, name := range []string{
+ "coding_agent.llm.turn",
+ "coding_agent.tool_call",
+ "coding_agent.edit_decision",
+ "coding_agent.subagent",
+ } {
+ _, sp := tracer.Start(
+ sessionTraceContext(context.Background(), sessionID, vendor),
+ name,
+ )
+ sp.End()
+ }
+
+ stubs := exp.GetSpans()
+ if len(stubs) != 5 {
+ t.Fatalf("expected 5 spans (session + 4 children), got %d", len(stubs))
+ }
+
+ expectedTraceID := deriveSessionTraceID(sessionID, vendor)
+ expectedRootSpanID := deriveSessionRootSpanID(sessionID, vendor)
+
+ var sessionSpan tracetest.SpanStub
+ var children []tracetest.SpanStub
+ for _, s := range stubs {
+ if s.Name == "coding_agent.session" {
+ sessionSpan = s
+ continue
+ }
+ children = append(children, s)
+ }
+
+ if got := sessionSpan.SpanContext.TraceID(); got != expectedTraceID {
+ t.Fatalf("session span TraceID mismatch: want %v got %v", expectedTraceID, got)
+ }
+ if got := sessionSpan.SpanContext.SpanID(); got != expectedRootSpanID {
+ t.Fatalf("session span SpanID must equal derived rootSpanID: want %v got %v", expectedRootSpanID, got)
+ }
+ // The session-root span has no parent — its parent SpanContext
+ // must be invalid (all zeros).
+ if sessionSpan.Parent.IsValid() {
+ t.Fatalf("session span must be a trace root; got parent=%v", sessionSpan.Parent)
+ }
+
+ if len(children) != 4 {
+ t.Fatalf("expected 4 child spans, got %d", len(children))
+ }
+ for _, c := range children {
+ if c.SpanContext.TraceID() != expectedTraceID {
+ t.Fatalf("%s TraceID mismatch: want %v got %v",
+ c.Name, expectedTraceID, c.SpanContext.TraceID())
+ }
+ if c.Parent.SpanID() != expectedRootSpanID {
+ t.Fatalf("%s ParentSpanID mismatch: want %v got %v",
+ c.Name, expectedRootSpanID, c.Parent.SpanID())
+ }
+ // Children must have their own random SpanIDs — not the root's.
+ if c.SpanContext.SpanID() == expectedRootSpanID {
+ t.Fatalf("%s reuses rootSpanID as its own SpanID; children must get random SpanIDs",
+ c.Name)
+ }
+ }
+}
+
+// TestEmitFlow_DistinctSessionsAreDistinctTraces guards against any
+// global-state leak in `sessionIDGenerator` — two sessions emitted in
+// the same process must produce two separate traces.
+func TestEmitFlow_DistinctSessionsAreDistinctTraces(t *testing.T) {
+ tracer, exp, done := newTestTracer(t)
+ defer done()
+
+ const vendor = "cursor"
+ for _, sid := range []string{"sess-A", "sess-B"} {
+ _, sp := tracer.Start(sessionRootContext(context.Background(), sid, vendor), "coding_agent.session")
+ sp.End()
+ _, child := tracer.Start(sessionTraceContext(context.Background(), sid, vendor), "coding_agent.tool_call")
+ child.End()
+ }
+
+ stubs := exp.GetSpans()
+ if len(stubs) != 4 {
+ t.Fatalf("expected 4 spans (2 sessions × 2 spans), got %d", len(stubs))
+ }
+
+ tidA := deriveSessionTraceID("sess-A", vendor)
+ tidB := deriveSessionTraceID("sess-B", vendor)
+ countA, countB := 0, 0
+ for _, s := range stubs {
+ switch s.SpanContext.TraceID() {
+ case tidA:
+ countA++
+ case tidB:
+ countB++
+ default:
+ t.Fatalf("span %s has unexpected TraceID %v", s.Name, s.SpanContext.TraceID())
+ }
+ }
+ if countA != 2 || countB != 2 {
+ t.Fatalf("expected 2 spans per session, got A=%d B=%d", countA, countB)
+ }
+}
+
+// TestEmitFlow_NestedAgentIsolation is the new contract that came out
+// of the May-2026 "cursor session leaked into claude-code list" bug:
+// when Claude Code runs INSIDE Cursor's terminal, both hooks may see
+// the SAME session id (Cursor's chat UUID propagates via env), but
+// the two vendors' spans must still land in TWO traces so the UI can
+// show one Cursor session and one Claude Code session for the same
+// chat thread, not one merged row.
+func TestEmitFlow_NestedAgentIsolation(t *testing.T) {
+ tracer, exp, done := newTestTracer(t)
+ defer done()
+
+ const sharedSessionID = "shared-chat-id"
+
+ for _, vendor := range []string{"cursor", "claude-code"} {
+ _, sp := tracer.Start(sessionRootContext(context.Background(), sharedSessionID, vendor), "coding_agent.session")
+ sp.End()
+ }
+
+ stubs := exp.GetSpans()
+ if len(stubs) != 2 {
+ t.Fatalf("expected 2 spans (one per vendor), got %d", len(stubs))
+ }
+ if stubs[0].SpanContext.TraceID() == stubs[1].SpanContext.TraceID() {
+ t.Fatalf("nested-agent isolation broken: vendors share trace id %v", stubs[0].SpanContext.TraceID())
+ }
+}
+
+func TestSessionIDGenerator_FallsBackToRandomWithoutMarker(t *testing.T) {
+ gen := sessionIDGenerator{}
+ // No marker in ctx — must yield random, valid ids.
+ tid, sid := gen.NewIDs(context.Background())
+ if !tid.IsValid() || !sid.IsValid() {
+ t.Fatalf("expected valid random ids without marker, got tid=%v sid=%v", tid, sid)
+ }
+ tid2, sid2 := gen.NewIDs(context.Background())
+ if tid == tid2 || sid == sid2 {
+ t.Fatalf("random generator must not collide on consecutive calls")
+ }
+}
diff --git a/cli/internal/redact/redact.go b/cli/internal/redact/redact.go
new file mode 100644
index 00000000..af90ac3b
--- /dev/null
+++ b/cli/internal/redact/redact.go
@@ -0,0 +1,154 @@
+// Package redact strips obvious secrets from strings before they're
+// emitted as OTel attributes.
+//
+// Two tiers:
+//
+// - Tier 1 (always on): high-confidence secret patterns where false
+// positives are very rare — AWS access keys, GitHub tokens, OpenAI
+// keys, JWTs, private keys, generic Bearer tokens, etc. Run on
+// every string that crosses the wire.
+//
+// - Tier 2 (off by default, enabled when ContentCapture == "full"):
+// more aggressive heuristics that catch in-prose secrets — long
+// hex/base64 blobs, "password=foo" assignments. False positives
+// are possible (e.g. a long base64 image hash). We accept those
+// because the user has explicitly opted in to capturing prompt
+// and tool-arg content.
+//
+// JSON-shape preservation: redaction runs *after* JSON parsing where the
+// caller has already extracted string values, so we never touch
+// structural braces / quotes. For tool-call argument blobs the caller
+// passes the entire JSON string; we run regex replacements that only
+// rewrite secret-looking substrings and leave the JSON parseable.
+package redact
+
+import "regexp"
+
+// Replacement is the placeholder we substitute for matched secrets.
+const Replacement = "[REDACTED]"
+
+// tier1Patterns are the always-on secret patterns. Order doesn't matter
+// since each rewrites in place.
+var tier1Patterns = []*regexp.Regexp{
+ // AWS access key id (AKIA + 16 chars) and the secret access key
+ // (40 base64 chars after `aws_secret_access_key`).
+ regexp.MustCompile(`AKIA[0-9A-Z]{16}`),
+ regexp.MustCompile(`(?i)aws[_-]?secret[_-]?access[_-]?key\s*[:=]\s*["']?[A-Za-z0-9/+=]{40}["']?`),
+
+ // GitHub tokens.
+ regexp.MustCompile(`gh[opsu]_[A-Za-z0-9]{16,}`),
+ regexp.MustCompile(`github_pat_[A-Za-z0-9_]{20,}`),
+
+ // OpenAI / Anthropic / generic provider keys.
+ regexp.MustCompile(`sk-(?:proj-)?[A-Za-z0-9_\-]{20,}`),
+ regexp.MustCompile(`sk-ant-[A-Za-z0-9_\-]{20,}`),
+
+ // Slack tokens.
+ regexp.MustCompile(`xox[abprs]-[0-9]+-[0-9]+-[0-9]+-[A-Za-z0-9]{20,}`),
+
+ // Google API keys.
+ regexp.MustCompile(`AIza[0-9A-Za-z_\-]{35}`),
+
+ // Stripe live keys.
+ regexp.MustCompile(`sk_live_[A-Za-z0-9]{20,}`),
+ regexp.MustCompile(`rk_live_[A-Za-z0-9]{20,}`),
+
+ // Generic JWTs (3 base64url segments separated by dots, leading "ey").
+ regexp.MustCompile(`eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}`),
+
+ // Bearer tokens in headers (always strip the value, keep the prefix).
+ regexp.MustCompile(`(?i)(authorization\s*:\s*bearer\s+)[A-Za-z0-9_\-\.=]+`),
+
+ // PEM-style private keys: collapse the entire block.
+ regexp.MustCompile(`(?s)-----BEGIN [A-Z ]+PRIVATE KEY-----.*?-----END [A-Z ]+PRIVATE KEY-----`),
+
+ // Azure storage / SAS keys. ?sv=… signature tail is sensitive
+ // even when the SAS itself looks like a URL-encoded blob.
+ regexp.MustCompile(`(?i)(sig=)[A-Za-z0-9%]{20,}`),
+ regexp.MustCompile(`(?i)DefaultEndpointsProtocol=https?;AccountName=[A-Za-z0-9]+;AccountKey=[A-Za-z0-9+/=]{20,}`),
+
+ // HuggingFace user tokens. Two formats are in the wild
+ // (`hf_…` short tokens and the longer fine-grained variants).
+ regexp.MustCompile(`hf_[A-Za-z0-9]{20,}`),
+
+ // Discord bot tokens — three dot-separated segments, first is
+ // a base64-encoded user id, fairly distinctive.
+ regexp.MustCompile(`[MN][A-Za-z0-9]{23}\.[A-Za-z0-9_\-]{6}\.[A-Za-z0-9_\-]{20,}`),
+
+ // npm tokens — both the legacy 36-char hex format and the
+ // modern `npm_…` prefix.
+ regexp.MustCompile(`npm_[A-Za-z0-9]{30,}`),
+}
+
+// tier1CaptureRewrites are patterns whose match must NOT be wholly
+// replaced — instead the redactor keeps some capture groups intact
+// (e.g. the DB scheme + host on a connection URL) and zeroes the
+// secret-bearing groups. Each entry is applied after tier1Patterns
+// on every call to String / StringFull.
+var tier1CaptureRewrites = []struct {
+ re *regexp.Regexp
+ repl string
+}{
+ // Postgres / MySQL / Mongo / Redis / AMQP connection URLs carry
+ // the password inline in the userinfo segment. Keep the scheme
+ // and host so dashboards can still tell which DB the agent was
+ // touching; mask the credentials.
+ {
+ re: regexp.MustCompile(`(?i)((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp)://)[^:\s/@]+:[^@\s]+@`),
+ repl: "${1}[REDACTED]:[REDACTED]@",
+ },
+}
+
+// tier2Patterns are aggressive heuristics enabled when content capture
+// is set to "full". They risk false positives but catch in-prose secrets
+// that tier 1 misses.
+var tier2Patterns = []*regexp.Regexp{
+ // Generic password= / token= / secret= / api_key= assignments.
+ regexp.MustCompile(`(?i)(password|passwd|pwd|secret|token|api[_-]?key)\s*[:=]\s*["']?[A-Za-z0-9+/=_\-\.]{8,}["']?`),
+ // Long hex strings (40+ chars) — typical for SHA256, OAuth, etc.
+ regexp.MustCompile(`\b[A-Fa-f0-9]{40,}\b`),
+ // Long base64 blobs (60+ chars) outside of obvious URL/path context.
+ regexp.MustCompile(`\b[A-Za-z0-9+/]{60,}={0,2}\b`),
+}
+
+// String runs tier-1 redaction on s. Always safe to call.
+func String(s string) string {
+ if s == "" {
+ return s
+ }
+ for _, re := range tier1Patterns {
+ s = re.ReplaceAllString(s, Replacement)
+ }
+ for _, r := range tier1CaptureRewrites {
+ s = r.re.ReplaceAllString(s, r.repl)
+ }
+ return s
+}
+
+// StringFull runs tier-1 + tier-2 redaction. Use only when content
+// capture is set to "full".
+func StringFull(s string) string {
+ if s == "" {
+ return s
+ }
+ s = String(s)
+ for _, re := range tier2Patterns {
+ s = re.ReplaceAllString(s, Replacement)
+ }
+ return s
+}
+
+// ForCapture returns the appropriate redactor for the given capture mode.
+//
+// - "minimal" / "metadata_only" → tier 1 redaction
+// - "full" → tier 1 + tier 2
+//
+// Unknown modes default to the safer tier 1 only — never weaker.
+func ForCapture(mode string) func(string) string {
+ switch mode {
+ case "full":
+ return StringFull
+ default:
+ return String
+ }
+}
diff --git a/cli/internal/redact/redact_test.go b/cli/internal/redact/redact_test.go
new file mode 100644
index 00000000..3b8fd39c
--- /dev/null
+++ b/cli/internal/redact/redact_test.go
@@ -0,0 +1,118 @@
+package redact
+
+import (
+ "strings"
+ "testing"
+)
+
+// Vendor prefixes that GitHub's push-protection scanner shape-matches
+// against (Stripe `sk_live_…`, etc.) are assembled at runtime via
+// `strings.Repeat` so the source file never contains
+// "<prefix><20+ alphanumerics>" as a single literal. The redactor still
+// sees the full, well-formed fake key when the test runs because Go
+// string concatenation produces the same bytes the regex expects —
+// the scanner just can't see it on disk. Don't inline these.
+var (
+ stripeSkLiveFake = "sk_live_" + strings.Repeat("a", 30)
+ stripeRkLiveFake = "rk_live_" + strings.Repeat("a", 30)
+)
+
+// shouldRedactTier1 lists strings that contain a secret tier-1 should
+// remove. The check is "Replacement appears in the output" rather than
+// exact equality, since some patterns leave a prefix in place
+// (e.g. "Authorization: Bearer ...").
+var shouldRedactTier1 = []struct {
+ name string
+ in string
+}{
+ {"aws_access_key_id", "AKIAIOSFODNN7EXAMPLE inside a sentence"},
+ {"aws_secret_access_key_assignment", `aws_secret_access_key="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"`},
+ {"gh_pat", "ghp_abcdefghijklmnopqrstuvwxyz0123456789"},
+ {"openai_sk", "sk-proj-abc123_XYZ-secrets-living-here-now"},
+ {"anthropic_sk", "sk-ant-abc123-secrets-456-zzz"},
+ {"google_api_key", "AIza0123456789abcdefghijklmnopqrstuv-_X"},
+ {"slack_xoxb", "xoxb-12345678-1234567890123-123456789012-abc123def456ghi789jkl"},
+ {"stripe_sk_live", stripeSkLiveFake},
+ {"stripe_rk_live", stripeRkLiveFake},
+ {"jwt", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.signature123"},
+ {"bearer_header", "Authorization: Bearer abc123def456ghi789jkl"},
+ {"private_key", "-----BEGIN RSA PRIVATE KEY-----\nMIIEvQIBADANBgkq\n-----END RSA PRIVATE KEY-----"},
+ {"azure_sas_sig", "?sv=2021-08-06&sig=AbCdEf%2BGhIj0123456789xyzPQR%3D"},
+ {"azure_storage_conn", "DefaultEndpointsProtocol=https;AccountName=foo;AccountKey=AbCdEfGh1234567890abcdefghijklmn=="},
+ {"hf_token", "hf_AbCdEfGhIjKlMnOpQrStUvWx12"},
+ {"npm_token", "npm_abcdefghijklmnopqrstuvwxyz012345"},
+ {"postgres_url", "postgres://app:[email protected]:5432/main"},
+ {"mysql_url", "mysql://root:[email protected]/orders"},
+}
+
+func TestStringTier1RedactsKnownSecrets(t *testing.T) {
+ for _, tc := range shouldRedactTier1 {
+ t.Run(tc.name, func(t *testing.T) {
+ out := String(tc.in)
+ if !strings.Contains(out, Replacement) {
+ t.Errorf("expected replacement marker; got %q", out)
+ }
+ })
+ }
+}
+
+func TestPostgresURLKeepsHostDropsCreds(t *testing.T) {
+ // The capture-rewrite path must keep the scheme + host so a
+ // dashboard can still tell which DB the agent was hitting, while
+ // dropping the user + password. Asserts the exact shape so a
+ // future refactor of the replacement template can't silently
+ // regress (e.g. swallowing the path).
+ in := "postgres://app:[email protected]:5432/main"
+ want := "postgres://[REDACTED]:[REDACTED]@db.internal:5432/main"
+ if got := String(in); got != want {
+ t.Errorf("String(%q) = %q, want %q", in, got, want)
+ }
+}
+
+func TestStringTier1LeavesNonSecretsAlone(t *testing.T) {
+ cases := []string{
+ "hello world",
+ "User clicked the merge button",
+ "no secrets here, just an explanation about authentication",
+ "sk-", // too short to match
+ "AKIA1", // too short to match
+ }
+ for _, s := range cases {
+ if got := String(s); got != s {
+ t.Errorf("String(%q) = %q (changed unexpectedly)", s, got)
+ }
+ }
+}
+
+func TestStringFullCatchesGenericPasswords(t *testing.T) {
+ cases := []string{
+ `password="hunter22hunter22"`,
+ `password=hunter22hunter22`,
+ `api_key: "sk-some-thing-12345-678"`,
+ }
+ for _, s := range cases {
+ out := StringFull(s)
+ if !strings.Contains(out, Replacement) {
+ t.Errorf("StringFull(%q) did not redact: got %q", s, out)
+ }
+ }
+}
+
+func TestForCaptureSelector(t *testing.T) {
+ if got := ForCapture("metadata_only")("password=secret_value_123"); got == "password="+Replacement {
+ // Tier 1 alone should NOT match this generic password pattern.
+ t.Errorf("metadata_only mode unexpectedly applied tier 2: %q", got)
+ }
+ if got := ForCapture("full")("password=secret_value_123"); !strings.Contains(got, Replacement) {
+ t.Errorf("full mode should have redacted: %q", got)
+ }
+}
+
+func TestEmptyString(t *testing.T) {
+ if got := String(""); got != "" {
+ t.Errorf("String(%q) = %q", "", got)
+ }
+ if got := StringFull(""); got != "" {
+ t.Errorf("StringFull(%q) = %q", "", got)
+ }
+}
diff --git a/cli/internal/semconvgen/main.go b/cli/internal/semconvgen/main.go
new file mode 100644
index 00000000..e0c3db25
--- /dev/null
+++ b/cli/internal/semconvgen/main.go
@@ -0,0 +1,142 @@
+// Code generator that mirrors sdk/go/semconv/coding_agent.go to TypeScript
+// constants under cli/gen/semconv.ts. Invoked via `go generate ./...` from
+// the cli/ module so the dashboard imports stay in lockstep with the Go
+// source of truth.
+//
+// Usage (run from anywhere; resolves paths from this file's location):
+//
+// go run ./internal/semconvgen
+//
+// Or, transitively, from `go generate ./...`.
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+)
+
+func main() {
+ if err := run(); err != nil {
+ fmt.Fprintln(os.Stderr, "semconvgen:", err)
+ os.Exit(1)
+ }
+}
+
+func run() error {
+ _, here, _, ok := runtime.Caller(0)
+ if !ok {
+ return fmt.Errorf("could not determine caller location")
+ }
+ cliDir := filepath.Clean(filepath.Join(filepath.Dir(here), "..", ".."))
+ repoRoot := filepath.Clean(filepath.Join(cliDir, ".."))
+
+ src := filepath.Join(repoRoot, "sdk", "go", "semconv", "coding_agent.go")
+ dst := filepath.Join(cliDir, "gen", "semconv.ts")
+
+ consts, err := parseConsts(src)
+ if err != nil {
+ return fmt.Errorf("parse %s: %w", src, err)
+ }
+
+ var buf bytes.Buffer
+ buf.WriteString("// Code generated by cli/internal/semconvgen. DO NOT EDIT.\n")
+ buf.WriteString("// Source: sdk/go/semconv/coding_agent.go\n")
+ buf.WriteString("//\n")
+ buf.WriteString("// Run `go generate ./...` from the cli/ module to regenerate.\n\n")
+
+ for _, c := range consts {
+ if c.doc != "" {
+ for _, line := range strings.Split(strings.TrimRight(c.doc, "\n"), "\n") {
+ if line == "" {
+ buf.WriteString("//\n")
+ continue
+ }
+ buf.WriteString("// ")
+ buf.WriteString(line)
+ buf.WriteByte('\n')
+ }
+ }
+ fmt.Fprintf(&buf, "export const %s = %s;\n\n", c.name, strconv.Quote(c.value))
+ }
+
+ if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
+ return fmt.Errorf("mkdir %s: %w", filepath.Dir(dst), err)
+ }
+ if err := os.WriteFile(dst, buf.Bytes(), 0o644); err != nil {
+ return fmt.Errorf("write %s: %w", dst, err)
+ }
+ fmt.Printf("semconvgen: wrote %d constants to %s\n", len(consts), dst)
+ return nil
+}
+
+type constDecl struct {
+ name string
+ value string
+ doc string
+}
+
+func parseConsts(src string) ([]constDecl, error) {
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, src, nil, parser.ParseComments)
+ if err != nil {
+ return nil, err
+ }
+
+ var out []constDecl
+ for _, decl := range f.Decls {
+ gen, ok := decl.(*ast.GenDecl)
+ if !ok || gen.Tok != token.CONST {
+ continue
+ }
+ groupDoc := ""
+ if gen.Doc != nil {
+ groupDoc = gen.Doc.Text()
+ }
+ // Track the first spec we successfully emit so we can attach
+ // the group's doc comment as a section header. Subsequent
+ // specs without their own doc render undocumented.
+ groupHeaderEmitted := false
+ for _, spec := range gen.Specs {
+ vs, ok := spec.(*ast.ValueSpec)
+ if !ok {
+ continue
+ }
+ for i, name := range vs.Names {
+ if i >= len(vs.Values) {
+ continue
+ }
+ lit, ok := vs.Values[i].(*ast.BasicLit)
+ if !ok || lit.Kind != token.STRING {
+ // Only string consts cross the wire as semconv keys.
+ continue
+ }
+ val, err := strconv.Unquote(lit.Value)
+ if err != nil {
+ continue
+ }
+ doc := ""
+ switch {
+ case vs.Doc != nil:
+ doc = vs.Doc.Text()
+ case !groupHeaderEmitted && groupDoc != "":
+ doc = groupDoc
+ groupHeaderEmitted = true
+ }
+ out = append(out, constDecl{
+ name: name.Name,
+ value: val,
+ doc: doc,
+ })
+ }
+ }
+ }
+ return out, nil
+}
diff --git a/cli/internal/version/version.go b/cli/internal/version/version.go
new file mode 100644
index 00000000..4afea47d
--- /dev/null
+++ b/cli/internal/version/version.go
@@ -0,0 +1,35 @@
+// Package version exposes the CLI build version and a `version` subcommand.
+package version
+
+import (
+ "fmt"
+
+ "github.com/spf13/cobra"
+)
+
+// Version is the CLI's semver string. Overridden at build time via
+// `-ldflags "-X github.com/openlit/openlit/cli/internal/version.Version=v1.2.3"`.
+// The default `dev` is what local `go build` produces.
+var Version = "dev"
+
+// Commit is the short commit SHA, set at build time via -ldflags.
+var Commit = ""
+
+// NewCmd returns the cobra `version` subcommand.
+func NewCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "version",
+ Short: "Print the openlit CLI version",
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ out := cmd.OutOrStdout()
+ if Commit != "" {
+ _, err := fmt.Fprintf(out, "openlit %s (%s)\n", Version, Commit)
+ return err
+ }
+ _, err := fmt.Fprintf(out, "openlit %s\n", Version)
+ return err
+ },
+ }
+}
diff --git a/cli/scripts/install-local.sh b/cli/scripts/install-local.sh
new file mode 100755
index 00000000..87cf2d84
--- /dev/null
+++ b/cli/scripts/install-local.sh
@@ -0,0 +1,115 @@
+#!/usr/bin/env sh
+# Local-build installer for the openlit CLI.
+#
+# Dev-mode escape hatch for testing the onboarding flow before a
+# `cli-X.Y.Z` GitHub Release exists. Builds the CLI from the current
+# checkout with `go build` and installs the result to the same path
+# that `install.sh` would (~/.openlit/bin/openlit), so the rest of the
+# onboarding snippet (`openlit configure` + `openlit coding install`)
+# behaves identically whether the user installed from source or from
+# a release.
+#
+# Usage:
+# sh /path/to/openlit/cli/scripts/install-local.sh
+#
+# Or, from inside the repo:
+# sh cli/scripts/install-local.sh
+#
+# Environment overrides (same names install.sh recognises so the two
+# scripts feel interchangeable):
+# OPENLIT_INSTALL_DIR Target directory. Default: $HOME/.openlit/bin
+#
+# Delete with:
+# rm ~/.openlit/bin/openlit # the binary
+# openlit coding uninstall --vendor=all --purge # before deleting the binary
+
+set -eu
+
+OPENLIT_INSTALL_DIR=${OPENLIT_INSTALL_DIR:-"$HOME/.openlit/bin"}
+
+info() { printf 'openlit: %s\n' "$*"; }
+warn() { printf 'openlit: %s\n' "$*" >&2; }
+fatal() { printf 'openlit: error: %s\n' "$*" >&2; exit 1; }
+
+need() {
+ command -v "$1" >/dev/null 2>&1 || fatal "missing required command: $1"
+}
+need go
+need uname
+
+# --- Locate the cli/ module relative to THIS script -------------------------
+
+# We resolve via the script's own directory so the user can sh
+# install-local.sh from anywhere — from inside the repo, from outside,
+# piped through `cat`, doesn't matter. Falls back to $PWD if dirname
+# returns something nonsensical (shouldn't happen on POSIX systems
+# but the fallback keeps the failure modes loud).
+script_dir=$(cd "$(dirname "$0")" 2>/dev/null && pwd) || script_dir=$(pwd)
+cli_dir=$(cd "$script_dir/.." && pwd)
+
+if [ ! -f "$cli_dir/go.mod" ] || [ ! -d "$cli_dir/cmd/openlit" ]; then
+ fatal "expected cli/ module at $cli_dir but go.mod or cmd/openlit is missing"
+fi
+
+# --- Build into a temp file, atomic-move into place ------------------------
+
+# Build into a temp dir + final rename so we never leave a partially
+# linked binary in PATH if the build fails mid-link. Cleanup runs on
+# both success and error paths.
+tmpdir=$(mktemp -d -t openlit-build-XXXXXX)
+trap 'rm -rf "$tmpdir"' EXIT INT TERM
+
+info "Building from $cli_dir"
+(
+ cd "$cli_dir"
+ # -trimpath strips local filesystem paths from the binary so
+ # stack traces don't leak the developer's homedir; -ldflags
+ # -s -w drops the symbol + DWARF tables, which knocks ~30% off
+ # the binary size and matches what cli-release.yml produces.
+ # Keep these in sync with the release workflow so behaviour
+ # differences between source builds and release builds stay
+ # small.
+ #
+ # Stamp `dev-<short-sha>` into the version vars in
+ # cli/internal/version. Without this every local install reports
+ # `dev` with no commit, which is impossible to distinguish from
+ # an old build. Best-effort: silently fall back to `dev` if the
+ # checkout isn't a git tree.
+ VERSION_PKG="github.com/openlit/openlit/cli/internal/version"
+ COMMIT=$(git -C "$cli_dir" rev-parse --short HEAD 2>/dev/null || echo "")
+ VERSION="dev"
+ if [ -n "$COMMIT" ]; then
+ VERSION="dev-$COMMIT"
+ fi
+ CGO_ENABLED=0 go build -trimpath \
+ -ldflags "-s -w -X ${VERSION_PKG}.Version=${VERSION} -X ${VERSION_PKG}.Commit=${COMMIT}" \
+ -o "$tmpdir/openlit" ./cmd/openlit
+)
+
+mkdir -p "$OPENLIT_INSTALL_DIR"
+target="$OPENLIT_INSTALL_DIR/openlit"
+mv "$tmpdir/openlit" "$target"
+chmod +x "$target"
+
+info "Installed: $target"
+
+# --- PATH hint --------------------------------------------------------------
+
+case ":$PATH:" in
+ *":$OPENLIT_INSTALL_DIR:"*) ;;
+ *)
+ warn ""
+ warn "Add the install directory to your PATH (one of):"
+ warn " echo 'export PATH=\"$OPENLIT_INSTALL_DIR:\$PATH\"' >> ~/.zshrc # zsh"
+ warn " echo 'export PATH=\"$OPENLIT_INSTALL_DIR:\$PATH\"' >> ~/.bashrc # bash"
+ warn "Then reload your shell or 'source' the file."
+ ;;
+esac
+
+info ""
+info "Next: configure + wire a vendor. The current shell may not have"
+info " \$OPENLIT_INSTALL_DIR on PATH yet — open a new terminal, or"
+info " use the absolute path below:"
+info ""
+info " $target configure --endpoint <url> --api-key <key>"
+info " $target coding install --vendor=cursor # or claude-code / codex"
diff --git a/cli/scripts/install.ps1 b/cli/scripts/install.ps1
new file mode 100644
index 00000000..0dd60bad
--- /dev/null
+++ b/cli/scripts/install.ps1
@@ -0,0 +1,117 @@
+# openlit CLI installer for Windows.
+#
+# Detects architecture, downloads the matching zip from the latest
+# `cli-*.*.*` GitHub Release of openlit/openlit, extracts the binary
+# to $env:USERPROFILE\.openlit\bin\openlit.exe, and adds that
+# directory to the user-scope PATH if it is not already there.
+#
+# Usage:
+# iwr -useb https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/install.ps1 | iex
+#
+# Environment overrides:
+# $env:OPENLIT_INSTALL_DIR Target install directory.
+# Default: $env:USERPROFILE\.openlit\bin
+# $env:OPENLIT_VERSION Release tag WITHOUT the `cli-` prefix,
+# e.g. `1.2.0`. Default: `latest`.
+
+$ErrorActionPreference = 'Stop'
+
+$Repo = if ($env:OPENLIT_REPO) { $env:OPENLIT_REPO } else { 'openlit/openlit' }
+$InstallDir = if ($env:OPENLIT_INSTALL_DIR) {
+ $env:OPENLIT_INSTALL_DIR
+} else {
+ Join-Path $env:USERPROFILE '.openlit\bin'
+}
+$Version = if ($env:OPENLIT_VERSION) { $env:OPENLIT_VERSION } else { 'latest' }
+
+function Write-OpenLit($msg) { Write-Host "openlit: $msg" }
+function Write-OpenLitWarn($msg) { Write-Warning "openlit: $msg" }
+function Stop-OpenLit($msg) { throw "openlit: $msg" }
+
+# --- Detect architecture ----------------------------------------------------
+
+# PROCESSOR_ARCHITECTURE under WoW64 is "x86" on 64-bit hosts, so we
+# fall through to Is64BitOperatingSystem for the AMD64 case. ARM64
+# stays as-is.
+$archEnv = $env:PROCESSOR_ARCHITECTURE
+if ($archEnv -eq 'ARM64') {
+ $arch = 'arm64'
+} elseif ([Environment]::Is64BitOperatingSystem) {
+ $arch = 'amd64'
+} else {
+ Stop-OpenLit "unsupported architecture: $archEnv (the CLI is 64-bit only)"
+}
+
+# --- Resolve the asset URL --------------------------------------------------
+
+$asset = "openlit-windows-$arch.zip"
+$url = if ($Version -eq 'latest') {
+ "https://github.com/$Repo/releases/latest/download/$asset"
+} else {
+ "https://github.com/$Repo/releases/download/cli-$Version/$asset"
+}
+
+Write-OpenLit "Downloading $asset"
+
+# --- Stage download into a temp dir then atomic-move -----------------------
+
+$tmpDir = Join-Path $env:TEMP ("openlit-install-" + [System.Guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Path $tmpDir | Out-Null
+
+try {
+ $zipPath = Join-Path $tmpDir $asset
+ # Use TLS 1.2 explicitly for older Windows PowerShell builds that
+ # default to TLS 1.0; GitHub disabled that years ago and the
+ # download would fail with a misleading "could not create SSL/TLS
+ # secure channel" otherwise.
+ [Net.ServicePointManager]::SecurityProtocol = `
+ [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
+
+ Invoke-WebRequest -Uri $url -OutFile $zipPath -UseBasicParsing
+
+ Expand-Archive -Path $zipPath -DestinationPath $tmpDir -Force
+
+ # cli-release.yml zips the binary as `openlit-windows-<arch>.exe`.
+ # Find it defensively so a future rename in the workflow doesn't
+ # silently break this installer.
+ $extracted = Get-ChildItem -Path $tmpDir -Filter 'openlit*.exe' -Recurse |
+ Select-Object -First 1
+ if (-not $extracted) {
+ Stop-OpenLit "no openlit*.exe found inside $asset"
+ }
+
+ if (-not (Test-Path $InstallDir)) {
+ New-Item -ItemType Directory -Path $InstallDir | Out-Null
+ }
+
+ $target = Join-Path $InstallDir 'openlit.exe'
+ Move-Item -Path $extracted.FullName -Destination $target -Force
+
+ Write-OpenLit "Installed: $target"
+
+ # --- User PATH update ---------------------------------------------------
+
+ # Only touch the User scope; never the Machine scope. That keeps
+ # the installer usable without admin rights and avoids accidentally
+ # publishing the binary to other Windows accounts on the same box.
+ $currentUserPath = [Environment]::GetEnvironmentVariable('Path', 'User')
+ if (-not $currentUserPath) { $currentUserPath = '' }
+
+ $pathParts = $currentUserPath -split ';' | Where-Object { $_ -ne '' }
+ if ($pathParts -notcontains $InstallDir) {
+ $newPath = if ($currentUserPath) { "$currentUserPath;$InstallDir" } else { $InstallDir }
+ [Environment]::SetEnvironmentVariable('Path', $newPath, 'User')
+ Write-OpenLit "Added $InstallDir to your user PATH (open a new terminal to pick it up)"
+ }
+
+ Write-OpenLit ""
+ Write-OpenLit "Next: configure + wire a vendor. The current shell may not"
+ Write-OpenLit " have the install dir on PATH yet -- open a new terminal,"
+ Write-OpenLit " or use the absolute path below:"
+ Write-OpenLit ""
+ Write-OpenLit " & `"$target`" configure --endpoint <url> --api-key <key>"
+ Write-OpenLit " & `"$target`" coding install --vendor=cursor # or claude-code / codex"
+}
+finally {
+ Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
+}
diff --git a/cli/scripts/install.sh b/cli/scripts/install.sh
new file mode 100755
index 00000000..70335a30
--- /dev/null
+++ b/cli/scripts/install.sh
@@ -0,0 +1,157 @@
+#!/usr/bin/env sh
+# openlit CLI installer for macOS + Linux.
+#
+# Detects OS + architecture, downloads the matching tarball from the
+# latest `cli-*.*.*` GitHub Release of openlit/openlit, and installs
+# the binary to $HOME/.openlit/bin/openlit. Prints a PATH-add hint if
+# that directory is not already on $PATH.
+#
+# Usage:
+# curl -fsSL https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/install.sh | sh
+#
+# Environment overrides:
+# OPENLIT_INSTALL_DIR Target install directory.
+# Default: $HOME/.openlit/bin
+# OPENLIT_VERSION Release tag WITHOUT the `cli-` prefix, e.g.
+# `1.2.0`. Default: `latest` (resolved by
+# GitHub Releases' /latest redirect).
+#
+# Exit codes:
+# 0 Installed (or already present).
+# 1 Unsupported OS/arch, network failure, or missing curl/tar.
+
+set -eu
+
+OPENLIT_REPO=${OPENLIT_REPO:-openlit/openlit}
+OPENLIT_INSTALL_DIR=${OPENLIT_INSTALL_DIR:-"$HOME/.openlit/bin"}
+OPENLIT_VERSION=${OPENLIT_VERSION:-latest}
+
+info() { printf 'openlit: %s\n' "$*"; }
+warn() { printf 'openlit: %s\n' "$*" >&2; }
+fatal() { printf 'openlit: error: %s\n' "$*" >&2; exit 1; }
+
+need() {
+ command -v "$1" >/dev/null 2>&1 || fatal "missing required command: $1"
+}
+need curl
+need tar
+need uname
+
+# `sha256sum` lives on Linux, `shasum` on macOS — fall back gracefully
+# below. We don't fatal on missing either: if neither tool is present,
+# the verifier degrades to a clear warning instead of a hard failure,
+# matching how every other "official" CLI installer behaves on systems
+# without GNU coreutils (e.g. minimal Alpine images).
+sha256_cmd=""
+if command -v sha256sum >/dev/null 2>&1; then
+ sha256_cmd="sha256sum"
+elif command -v shasum >/dev/null 2>&1; then
+ sha256_cmd="shasum -a 256"
+fi
+
+# --- Detect OS + arch -------------------------------------------------------
+
+uname_os=$(uname -s | tr '[:upper:]' '[:lower:]')
+case "$uname_os" in
+ darwin) os=darwin ;;
+ linux) os=linux ;;
+ *) fatal "unsupported OS: $uname_os (this installer supports macOS + Linux; on Windows use install.ps1)" ;;
+esac
+
+uname_arch=$(uname -m)
+case "$uname_arch" in
+ x86_64|amd64) arch=amd64 ;;
+ aarch64|arm64) arch=arm64 ;;
+ *) fatal "unsupported architecture: $uname_arch" ;;
+esac
+
+# --- Resolve the asset URL --------------------------------------------------
+
+# The cli-release.yml workflow uploads one tarball per OS/arch named
+# openlit-<os>-<arch>.tar.gz. Latest is a redirect; pinned versions
+# use the `cli-X.Y.Z` tag layout that the workflow keys off of.
+asset="openlit-${os}-${arch}.tar.gz"
+if [ "$OPENLIT_VERSION" = "latest" ]; then
+ url="https://github.com/${OPENLIT_REPO}/releases/latest/download/${asset}"
+else
+ url="https://github.com/${OPENLIT_REPO}/releases/download/cli-${OPENLIT_VERSION}/${asset}"
+fi
+
+info "Downloading ${asset}"
+
+# --- Stage download into a temp dir, then atomic-move ----------------------
+
+# A temp dir + final rename avoids leaving a half-written binary in
+# place if curl/tar fails mid-stream. Cleanup runs even on errors.
+tmpdir=$(mktemp -d -t openlit-install-XXXXXX)
+trap 'rm -rf "$tmpdir"' EXIT INT TERM
+
+if ! curl -fsSL --retry 3 --retry-delay 1 -o "$tmpdir/$asset" "$url"; then
+ fatal "download failed: $url"
+fi
+
+# Pull the matching `.sha256` sidecar uploaded by cli-release.yml and
+# verify the tarball before extracting. The sidecar is best-effort —
+# if the release predates the sidecar upload or the network drops the
+# second request, we warn but continue rather than hard-fail (the
+# tarball was already served over HTTPS from GitHub, so we're paying
+# defense-in-depth, not establishing the only trust anchor).
+sha_url="${url}.sha256"
+if curl -fsSL --retry 3 --retry-delay 1 -o "$tmpdir/$asset.sha256" "$sha_url" 2>/dev/null; then
+ if [ -n "$sha256_cmd" ]; then
+ expected=$(awk '{print $1}' "$tmpdir/$asset.sha256")
+ # shellcheck disable=SC2086 # $sha256_cmd is a deliberate split for `shasum -a 256`.
+ actual=$($sha256_cmd "$tmpdir/$asset" | awk '{print $1}')
+ if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then
+ fatal "checksum mismatch for ${asset} — expected ${expected:-<empty>}, got ${actual}. Refusing to install a tampered tarball."
+ fi
+ info "Verified sha256 ${actual}"
+ else
+ warn "no sha256/shasum command found — skipping checksum verification"
+ fi
+else
+ warn "sha256 sidecar not available at ${sha_url}; skipping checksum verification"
+fi
+
+if ! tar -xzf "$tmpdir/$asset" -C "$tmpdir"; then
+ fatal "extract failed; archive may be corrupt"
+fi
+
+# The tarball contains a single binary named openlit-<os>-<arch>; the
+# release-side packaging step doesn't rename it. Find it defensively
+# so a future rename in cli-release.yml doesn't silently break us.
+extracted=$(find "$tmpdir" -maxdepth 2 -type f -name 'openlit*' ! -name '*.tar.gz' -print -quit)
+if [ -z "$extracted" ]; then
+ fatal "no openlit binary found inside ${asset}"
+fi
+
+mkdir -p "$OPENLIT_INSTALL_DIR"
+target="$OPENLIT_INSTALL_DIR/openlit"
+mv "$extracted" "$target"
+chmod +x "$target"
+
+info "Installed: $target"
+
+# --- PATH hint --------------------------------------------------------------
+
+# Only print the hint if the install dir isn't already on PATH. Using
+# `case` rather than `[[` keeps this portable to /bin/sh on Debian
+# (dash) and BusyBox (Alpine container images).
+case ":$PATH:" in
+ *":$OPENLIT_INSTALL_DIR:"*) ;;
+ *)
+ warn ""
+ warn "Add the install directory to your PATH (one of):"
+ warn " echo 'export PATH=\"$OPENLIT_INSTALL_DIR:\$PATH\"' >> ~/.zshrc # zsh"
+ warn " echo 'export PATH=\"$OPENLIT_INSTALL_DIR:\$PATH\"' >> ~/.bashrc # bash"
+ warn "Then reload your shell or 'source' the file."
+ ;;
+esac
+
+info ""
+info "Next: configure + wire a vendor. The current shell may not have"
+info " \$OPENLIT_INSTALL_DIR on PATH yet — open a new terminal, or"
+info " use the absolute path below:"
+info ""
+info " $target configure --endpoint <url> --api-key <key>"
+info " $target coding install --vendor=cursor # or claude-code / codex"
diff --git a/cli/scripts/sync-plugins.sh b/cli/scripts/sync-plugins.sh
new file mode 100755
index 00000000..66b97284
--- /dev/null
+++ b/cli/scripts/sync-plugins.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+# Assembles the embedded marketplace tree under
+# cli/internal/coding/install/marketplace/
+# from the two canonical source-of-truth locations at the repo root:
+# .claude-plugin/marketplace.json (root marketplace manifest)
+# plugins/<vendor>/ (per-vendor plugin manifests)
+#
+# Layout produced (identical to the repo-root layout so a single
+# marketplace.json works for both Claude's GitHub-source fetch and the
+# CLI's local materialize path):
+#
+# marketplace/
+# .claude-plugin/marketplace.json -- mirrored from repo-root
+# plugins/claude-code/ -- mirrored from repo-root
+# plugins/cursor/ -- mirrored from repo-root
+# plugins/codex/ -- mirrored from repo-root
+#
+# Run after editing any file under either source tree. CI verifies the
+# embedded copy is in sync (see .github/workflows/cli-tests.yml).
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+CLI_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
+REPO_ROOT="$(cd "${CLI_DIR}/.." && pwd)"
+
+SRC_MARKETPLACE="${REPO_ROOT}/.claude-plugin"
+SRC_PLUGINS="${REPO_ROOT}/plugins"
+DEST="${CLI_DIR}/internal/coding/install/marketplace"
+
+if [ ! -f "${SRC_MARKETPLACE}/marketplace.json" ]; then
+ echo "sync-plugins: missing ${SRC_MARKETPLACE}/marketplace.json" >&2
+ exit 1
+fi
+if [ ! -d "${SRC_PLUGINS}" ]; then
+ echo "sync-plugins: missing ${SRC_PLUGINS}/" >&2
+ exit 1
+fi
+
+# Wipe the dest tree wholesale so deletions in the source (e.g. dropping
+# a vendor) propagate. The README at the dest root is hand-maintained
+# and lives outside the wiped paths, so it survives.
+rm -rf "${DEST}/.claude-plugin" "${DEST}/plugins"
+
+mkdir -p "${DEST}/.claude-plugin" "${DEST}/plugins"
+
+cp "${SRC_MARKETPLACE}/marketplace.json" "${DEST}/.claude-plugin/marketplace.json"
+
+for vendor_dir in "${SRC_PLUGINS}"/*/; do
+ vendor=$(basename "${vendor_dir}")
+ cp -R "${vendor_dir}" "${DEST}/plugins/${vendor}"
+done
+
+echo "synced: .claude-plugin/ + plugins/ -> cli/internal/coding/install/marketplace/"
diff --git a/cli/scripts/uninstall.ps1 b/cli/scripts/uninstall.ps1
new file mode 100644
index 00000000..b0bd66d8
--- /dev/null
+++ b/cli/scripts/uninstall.ps1
@@ -0,0 +1,107 @@
+# openlit CLI uninstaller for Windows.
+#
+# Removes the binary installed by install.ps1 plus the on-disk state
+# that the coding-agent hook subcommand caches per session. Does NOT
+# touch the host-level vendor plugins — those carry user config the
+# uninstaller has no business deleting. Run:
+#
+# openlit coding uninstall --vendor=all
+#
+# BEFORE this script if you also want to detach the hooks from Claude
+# Code / Cursor / Codex.
+#
+# Usage:
+# iwr -useb https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/uninstall.ps1 | iex
+#
+# Environment overrides:
+# $env:OPENLIT_INSTALL_DIR Target install directory.
+# Default: $env:USERPROFILE\.openlit\bin
+# $env:OPENLIT_PURGE_STATE When `1`, also wipe the session cache +
+# config dir. Default: 0.
+#
+# Exit codes:
+# 0 Successfully removed (or nothing to remove).
+# 1 Refused (path looks suspicious — see below).
+
+$ErrorActionPreference = 'Stop'
+
+$InstallDir = if ($env:OPENLIT_INSTALL_DIR) {
+ $env:OPENLIT_INSTALL_DIR
+} else {
+ Join-Path $env:USERPROFILE '.openlit\bin'
+}
+$PurgeState = $env:OPENLIT_PURGE_STATE -eq '1'
+
+function Write-OpenLit($msg) { Write-Host "openlit: $msg" }
+function Stop-OpenLit($msg) { throw "openlit: $msg" }
+
+# Safety net: refuse to operate on suspicious install dirs. A typoed
+# OPENLIT_INSTALL_DIR=C:\ or =$env:USERPROFILE would otherwise blow
+# away the user's home. Require the path to look like something
+# install.ps1 actually creates.
+$normalised = $InstallDir.TrimEnd('\','/').ToLowerInvariant()
+$suspicious = @(
+ '',
+ 'c:',
+ $env:USERPROFILE.TrimEnd('\','/').ToLowerInvariant(),
+ 'c:\windows',
+ 'c:\program files',
+ 'c:\program files (x86)'
+)
+if ($suspicious -contains $normalised) {
+ Stop-OpenLit "refusing to uninstall from suspicious path: '$InstallDir'"
+}
+
+# --- Remove binary ---------------------------------------------------------
+
+$bin = Join-Path $InstallDir 'openlit.exe'
+if (Test-Path -LiteralPath $bin) {
+ Remove-Item -LiteralPath $bin -Force
+ Write-OpenLit "Removed binary: $bin"
+} else {
+ Write-OpenLit "No binary at $bin (already uninstalled?)"
+}
+
+# Remove the bin dir only when empty so we don't trample on other tools
+# the user might have stored there.
+if (Test-Path -LiteralPath $InstallDir) {
+ if (-not (Get-ChildItem -LiteralPath $InstallDir -Force | Select-Object -First 1)) {
+ Remove-Item -LiteralPath $InstallDir -Force
+ }
+}
+
+# --- Optional purge of state + config -------------------------------------
+
+if ($PurgeState) {
+ # Mirrors cli/internal/coding/sessionstate/sessionstate.go (uses
+ # os.UserCacheDir → %LOCALAPPDATA% on Windows) and
+ # cli/internal/config/config.go (uses os.UserConfigDir →
+ # %APPDATA% on Windows, with $XDG_CONFIG_HOME taking precedence).
+ $cacheRoot = if ($env:LOCALAPPDATA) { $env:LOCALAPPDATA } else { Join-Path $env:USERPROFILE 'AppData\Local' }
+ $configRoot = if ($env:XDG_CONFIG_HOME) {
+ $env:XDG_CONFIG_HOME
+ } elseif ($env:APPDATA) {
+ $env:APPDATA
+ } else {
+ Join-Path $env:USERPROFILE 'AppData\Roaming'
+ }
+ $cacheDir = Join-Path $cacheRoot 'openlit'
+ $configDir = Join-Path $configRoot 'openlit'
+ if (Test-Path -LiteralPath $cacheDir) {
+ Remove-Item -LiteralPath $cacheDir -Recurse -Force
+ Write-OpenLit "Removed session cache: $cacheDir"
+ }
+ if (Test-Path -LiteralPath $configDir) {
+ Remove-Item -LiteralPath $configDir -Recurse -Force
+ Write-OpenLit "Removed config: $configDir"
+ }
+} else {
+ Write-OpenLit "Left session cache + config in place. Set `$env:OPENLIT_PURGE_STATE='1' to also remove them."
+}
+
+Write-OpenLit ""
+Write-OpenLit "Note: this script does NOT detach openlit from your coding agents."
+Write-OpenLit "If you previously ran 'openlit coding install', also run:"
+Write-OpenLit " openlit coding uninstall --vendor=all"
+Write-OpenLit "(while the binary is still on `$env:PATH), or remove the hook entries"
+Write-OpenLit "manually from your vendor configs."
diff --git a/cli/scripts/uninstall.sh b/cli/scripts/uninstall.sh
new file mode 100755
index 00000000..8aaeab00
--- /dev/null
+++ b/cli/scripts/uninstall.sh
@@ -0,0 +1,88 @@
+#!/usr/bin/env sh
+# openlit CLI uninstaller for macOS + Linux.
+#
+# Removes the binary installed by `install.sh` plus the on-disk state
+# that the coding-agent hook subcommand caches per session. Does NOT
+# touch the host-level vendor plugins — those carry user config the
+# uninstaller has no business deleting. Use
+# `openlit coding uninstall --vendor=all` BEFORE running this script
+# if you also want to detach the hooks from Claude Code / Cursor /
+# Codex.
+#
+# Usage:
+# curl -fsSL https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/uninstall.sh | sh
+#
+# Environment overrides:
+# OPENLIT_INSTALL_DIR Target install directory; default $HOME/.openlit/bin
+# OPENLIT_PURGE_STATE When `1`, also wipe the session cache + config dir.
+# Default: 0 (leaves them in place so a fresh install
+# picks up where the old one left off).
+#
+# Exit codes:
+# 0 Successfully removed (or nothing to remove).
+# 1 Refused (path looks suspicious; see comment below).
+
+set -eu
+
+OPENLIT_INSTALL_DIR=${OPENLIT_INSTALL_DIR:-"$HOME/.openlit/bin"}
+OPENLIT_PURGE_STATE=${OPENLIT_PURGE_STATE:-0}
+
+info() { printf 'openlit: %s\n' "$*"; }
+warn() { printf 'openlit: %s\n' "$*" >&2; }
+fatal() { printf 'openlit: error: %s\n' "$*" >&2; exit 1; }
+
+# Safety net: refuse to operate on suspicious install dirs. A typoed
+# OPENLIT_INSTALL_DIR=/ or =$HOME would otherwise blow away the
+# user's home or root file system. Require the path to look like
+# something installer.sh actually creates.
+case "$OPENLIT_INSTALL_DIR" in
+ /|"$HOME"|"$HOME/"|"")
+ fatal "refusing to uninstall from suspicious path: '$OPENLIT_INSTALL_DIR'"
+ ;;
+esac
+
+bin="$OPENLIT_INSTALL_DIR/openlit"
+if [ -f "$bin" ]; then
+ rm -f "$bin"
+ info "Removed binary: $bin"
+else
+ info "No binary at $bin (already uninstalled?)"
+fi
+
+# `rmdir` only removes empty dirs — if the user keeps other tools in
+# $HOME/.openlit/bin we leave it alone. The 2>/dev/null swallow keeps
+# this clean for the common "dir is empty" path.
+rmdir "$OPENLIT_INSTALL_DIR" 2>/dev/null || true
+
+if [ "$OPENLIT_PURGE_STATE" = "1" ]; then
+ # Mirror the resolution rules in cli/internal/config/config.go
+ # (configDir) and cli/internal/coding/sessionstate/sessionstate.go
+ # (which uses os.UserCacheDir). The CLI deliberately stays on
+ # ~/.config/openlit on macOS for parity with Linux, even though
+ # os.UserConfigDir returns ~/Library/Application Support there.
+ if [ "$(uname -s)" = "Darwin" ]; then
+ cache_root="$HOME/Library/Caches"
+ else
+ cache_root="${XDG_CACHE_HOME:-$HOME/.cache}"
+ fi
+ config_root="${XDG_CONFIG_HOME:-$HOME/.config}"
+ cache_dir="$cache_root/openlit"
+ config_dir="$config_root/openlit"
+ if [ -d "$cache_dir" ]; then
+ rm -rf "$cache_dir"
+ info "Removed session cache: $cache_dir"
+ fi
+ if [ -d "$config_dir" ]; then
+ rm -rf "$config_dir"
+ info "Removed config: $config_dir"
+ fi
+else
+ info "Left session cache + config in place. Pass OPENLIT_PURGE_STATE=1 to also remove them."
+fi
+
+info ""
+info "Note: this script does NOT detach openlit from your coding agents."
+info "If you previously ran 'openlit coding install', also run:"
+info " openlit coding uninstall --vendor=all"
+info "(while the binary is still on \$PATH), or remove the hook entries"
+info "manually from your vendor configs."
diff --git a/docs/docs.json b/docs/docs.json
index 4d98b78e..ab2be952 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -75,6 +75,14 @@
"latest/controller/architecture",
"latest/controller/configuration"
]
+ },
+ {
+ "group": "Coding Agents",
+ "icon": "code",
+ "pages": [
+ "latest/openlit/coding-agents/onboarding",
+ "latest/openlit/coding-agents/architecture"
+ ]
}
]
},
diff --git a/docs/latest/openlit/coding-agents/architecture.mdx b/docs/latest/openlit/coding-agents/architecture.mdx
new file mode 100644
index 00000000..01b34c82
--- /dev/null
+++ b/docs/latest/openlit/coding-agents/architecture.mdx
@@ -0,0 +1,398 @@
+---
+title: "Coding Agents — Architecture & Vendor Authoring"
+sidebarTitle: "Architecture"
+description: "How OpenLit ingests, normalises, and rolls up coding-agent telemetry — and how to add a new vendor without breaking what's already there."
+---
+
+This page is for contributors. If you just want to send Claude Code or
+Cursor telemetry into OpenLit, the
+[Onboarding](/latest/features/coding-agents/onboarding) page is what you
+want. Read on if you're:
+
+- Adding a new vendor adapter (Claude Code, Codex, Windsurf, …).
+- Touching the rollup / materializer that powers the `/agents` and
+ `/coding-agents` views.
+- Debugging missing rows, empty pills, or doubled sessions.
+
+<Note>
+This doc is paired with the in-repo Cursor rule
+`.cursor/rules/coding-agents-hook.mdc`. The rule auto-loads when you
+edit anything under `cli/internal/coding/`, `sdk/go/semconv/`, or the
+coding-agents query layer; the rule is the canonical authoring
+checklist, this doc is the conceptual overview.
+</Note>
+
+## Data flow
+
+```
+Vendor hook event ──► openlit CLI ──► OTLP/HTTP ──► OpenLit collector
+ │ │
+ ▼ ▼
+ sessionstate cache otel_traces (ClickHouse)
+ (XDG cache dir) │
+ ▼
+ materializer (cron)
+ │
+ ▼
+ openlit_agents_summary
+ │
+ ▼
+ /agents + /coding-agents UI
+```
+
+Each developer machine runs one `openlit` CLI binary. The vendor's
+plugin / hook system invokes `openlit hook <vendor>` on every event;
+the CLI is short-lived (one process per event) so anything stateful
+lives in the session-state cache at
+`$XDG_CACHE_HOME/openlit/sessions/<session-id>.json`.
+
+## Identity model
+
+| Concept | Where it lives | Stable across |
+| ------- | -------------- | ------------- |
+| `session.id` | Span + resource attr `coding_agent.session.id` | One process / hook invocation |
+| `conversation.id` | Resource attr `gen_ai.conversation.id` | Multiple sessions when the vendor reports a stable chat id |
+| `chat_id` (UI) | Derived: `coalesce(parent_id, session_id)` | One chat thread including its subagents |
+| `agent_key` | Computed `computeAgentKey(cluster, env, vendor)` | One per vendor per environment |
+| `user` | Resource attr `gen_ai.user.name` | One developer per machine |
+
+The UI rolls up at `chat_id`. The materializer rolls up at `chat_id`,
+then by `vendor`. The hub on `/agents` shows one row per vendor.
+
+## Capture modes
+
+`OPENLIT_CODING_CONTENT_CAPTURE` controls what lands on spans. Pick one:
+
+| Mode | Identifiers | Tool names + paths | File diffs / message bodies |
+| --------------- | ----------- | ------------------ | --------------------------- |
+| `minimal` | ✅ | ❌ | ❌ |
+| `metadata_only` | ✅ | ✅ | ❌ |
+| `full` | ✅ | ✅ | ✅ |
+
+Two redaction tiers always run, regardless of mode: a token-pattern
+scrubber (`tier 1`) and a body-scope scrubber (`tier 2`, only active in
+`full`). See `cli/internal/redact/redact.go`.
+
+The mode is stamped as a resource attribute
+`coding_agent.content_capture_mode` so audit trails can prove what the
+session was recorded under.
+
+## Vendor adapter contract
+
+Each adapter under `cli/internal/coding/hook/<vendor>/` is responsible
+for:
+
+1. Parsing the vendor's JSON payload into Go structs.
+2. Picking the **session id** (vendor-specific key name).
+3. Mapping the vendor's event semantics onto our `normalize` types:
+ - `Session` — sessionStart / sessionEnd lifecycle.
+ - `LLMTurn` — one LLM call (prompt + completion).
+ - `ToolCall` — one tool invocation by the agent.
+ - `EditDecision` — accept / reject / undo of a code edit.
+ - `ShellRequest` — agent-issued shell command.
+ - `Event` — generic counter or "something happened" marker.
+4. Calling the matching `emit.Emit*` method on the OTLP emitter.
+
+The adapter does **not** decide what to redact, what to drop, or what
+trace id to use. Those live in the OTLP layer
+(`cli/internal/otlp/{attrs,exporter,sampler,tracecontext}.go`) so
+adapters stay narrow and consistent.
+
+## Common pitfalls (and what to do instead)
+
+### Empty `/agents` "Coding Agents" tab
+
+Cause: the materializer's discovery query has an aggregate in `GROUP BY`,
+or a CTE that inlines into nested aggregates. The materializer's
+`/api/agents/materialize` route returns `processed: N` for *other*
+rows while the coding-vendor row silently errors.
+
+Fix: rewrite the discovery query to use a per-row chat_id expression
+(map lookups + coalesce, no `any()`) and group by it directly. See
+`discoverCodingAgents` in `src/client/src/lib/platform/agents/materialize.ts`.
+
+### Empty Repository / Working Folder pills on tool / llm spans
+
+Cause: Cursor only sends `workspace_roots` on session lifecycle events.
+Per-tool hooks come in without any cwd field, and `os.Getwd()` wasn't
+persisted to the session-state cache.
+
+Fix: in `hook.go`, when `cached.CWD == ""`, resolve `os.Getwd()` and
+write it back to `cached.CWD` before calling `git.Snapshot`. The save
+gate already covers `cached.CWD != ""`.
+
+### One chat appears as N sessions
+
+Cause: a subagent is reporting its own `session_id` but not the
+parent's `parent_conversation_id`, so the chat-thread coalesce falls
+through to per-process session_id.
+
+Fix: confirm `peekContext` is picking the vendor's parent-id field,
+and that it's promoted to the `coding_agent.agent.parent_id` resource
+attribute in the `sessionAttrs` block of `hook.go`.
+
+### Double session-root span
+
+Cause: `EmitSession` is emitting a root span on both `sessionStart`
+("started") and `sessionEnd` (outcome="completed" / "errored").
+
+Fix: only emit on `End` events. The `started` / `in_progress` outcomes
+are no-ops in `EmitSession` — they only update the session-state cache.
+
+### `coding_active_users_24h` is always 0 on a single-user install
+
+Cause: `COHORT_K_FLOOR` was applied at materialize time. Since the
+single developer is below the floor, the count is masked to 0 in
+the materialized table.
+
+Fix: don't apply the floor in the materializer. Store the raw count.
+Apply the floor at query time in `queries.ts` where auth context is
+available, so admins see the truth and viewers see the masked view.
+
+### `active_users_24h` shows 0 in queries even after fix
+
+Cause: `USER_EXPR` doesn't include the vendor's identity key. For
+Cursor, identity arrives as `user.email` on tool spans and
+`gen_ai.user.name` as a resource attribute on every span.
+
+Fix: confirm the resource attribute is set (check
+`sessionstate/<sid>.json` for a `user` field). If not, the vendor's
+payload didn't include identity and we need to widen `peekContext`'s
+key list.
+
+### Agent detail page renders the SDK layout for a coding agent
+
+You click into a Cursor (or Claude Code, …) row in the **Coding
+Agents** tab and instead of the Overview / Sessions / Users tabs you
+get the generic Overview / Dashboard / Monitoring / Definition /
+Configuration tabs from the SDK/Controller detail page. Refresh a few
+times and the layout flips back.
+
+Cause: two rows exist in `openlit_agents_summary` with the **same
+agent_key** but different `source` — one `coding` and one `sdk`.
+The CLI sets `service.name = '<vendor>'` and emits through the
+openlit-go SDK, so the SDK discovery in `materialize.ts:discoverAgents`
+picks the same `service.name` up unless explicitly excluded. The
+summary table is a `ReplacingMergeTree(updated_at)`, so `FINAL` on
+read picks whichever row was written most recently — and the detail
+page chooses its layout from `agent.source`.
+
+Fix: the SDK discovery query must filter out CLI rows by checking
+`ResourceAttributes['coding_agent.session.id']` AND
+`SpanAttributes['coding_agent.session.id']` are both empty.
+
+When adding a new vendor, sanity-check that exactly one row exists
+per agent in the summary table:
+
+```sql
+SELECT agent_key, source, count() AS rows
+FROM openlit_agents_summary
+WHERE service_name = '<vendor>'
+GROUP BY agent_key, source;
+```
+
+A single row with `source='coding'` is correct. Two rows
+(`coding` + anything else) means the exclusion isn't catching the
+vendor's spans — usually because the vendor's CLI is emitting some
+spans before the session id is stamped as a resource attribute.
+
+## Claude Code: dual-path coalesce
+
+Claude Code is the first vendor where users can send telemetry to
+OpenLit through **two independent paths** at the same time:
+
+1. **Hook path** (recommended primary). The `openlit-cc` plugin sits
+ in `~/.claude/plugins/openlit-cc/` and is invoked on every
+ `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
+ `Stop`, `SubagentStop`, and `SessionEnd` hook event. The adapter
+ in `cli/internal/coding/hook/claudecode/handle.go` normalises each
+ event into our canonical `coding_agent.*` / `gen_ai.*` schema. It
+ tails the transcript JSONL for authoritative token + cost numbers
+ at session end.
+2. **Native OTel path** (optional, complementary). When the user
+ exports `CLAUDE_CODE_ENABLE_TELEMETRY=1` (plus the usual OTLP
+ endpoint / headers), Claude Code itself emits metrics, events,
+ and — with `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` — spans, all
+ under `service.name=claude-code` and the `claude_code.*`
+ attribute namespace.
+
+The two paths overlap. OpenLit dedupes per `session.id` at read
+time. The query layer (`queries.ts`, `materialize.ts`) coalesces both
+schemas into one chat row:
+
+- **Cost / tokens**: native wins when present (authoritative
+ Anthropic API numbers). Hook tail-of-transcript is the fallback
+ estimate.
+- **Repository / working folder / branch**: hook wins. Claude Code's
+ native exporter does not see the user's `cwd` or run
+ `git.Snapshot(cwd)`; only the openlit hook does.
+- **User identity**: either path. When the user is OAuth-authenticated
+ in Claude Code, the native path supplies `user.email` as a resource
+ attribute; the hook path supplies `gen_ai.user.name` from the local
+ env. Both are coalesced into the canonical user column.
+- **Vendor identifier**: any of `coding_agent.client = 'claude-code'`
+ (stamped by hook), `gen_ai.agent.name = 'claude-code'`, or
+ `service.name = 'claude-code'` (native default). The materializer
+ recognises all three.
+
+Every adapter stamps `coding_agent.signal_source = "hook"` on its
+resource attributes. The native path leaves the attribute unset; the
+query layer infers `"native"` from `service.name = 'claude-code'`. The
+SDK discovery in `materialize.ts:discoverAgents` excludes any span
+that carries `coding_agent.session.id` AND `telemetry.sdk.name =
+'openlit'`, so the openlit hook spans are never double-materialized
+as SDK rows. Native Claude Code spans use Claude Code's own SDK name
+(not `openlit`), so they too are excluded from SDK discovery.
+
+### Native Claude Code metric mapping
+
+Claude Code's native exporter emits a stable set of metrics under the
+`claude_code.*` namespace. The openlit CLI emits the same observable
+behavior under the canonical `coding_agent.*` namespace so a single
+OpenLit installation can ingest both streams interchangeably and any
+custom Grafana / Mimir dashboard the operator already has continues
+to work. The mapping:
+
+| Native Claude Code metric | Canonical openlit-CLI metric | Notes |
+|---|---|---|
+| `claude_code.session.count` | `coding_agent.session.count` | Counter; vendor-tagged via `coding_agent.client`. Native path is unitless; openlit-CLI counter is `{session}`. |
+| `claude_code.code_edit_tool.decision` | `coding_agent.edit.decision.count` | Counter, tags include `coding_agent.edit.decision` (`accept` / `auto_accepted` / `reject`) and `coding_agent.edit.source`. |
+| `claude_code.lines_of_code.count` | `coding_agent.lines_of_code.count` | Counter, tags include `coding_agent.edit.decision` so the same metric powers "lines added" and "lines accepted vs rejected" without two emitters. |
+| `claude_code.commit.count` | `coding_agent.commit.count` | Counter; the openlit-CLI adapters detect commits from Bash / shell / local_shell hooks and stamp the same canonical tags. |
+| `claude_code.pull_request.count` | `coding_agent.pull_request.count` | Counter; gated on `gh pr create / gh pr new` detection so it survives copy-pasted aliases. |
+| `claude_code.token.usage` | `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` | OpenLit follows the OTel GenAI semantic-conventions for token usage. Tags: `gen_ai.system`, `gen_ai.request.model`. |
+| `claude_code.cost.usage` | `gen_ai.usage.cost` | OTel GenAI semantic-conventions counter, USD. |
+| `claude_code.active_time.total` | (derived) | Active time is rolled up at query time as `duration_ms = ended_at - started_at` on the session-root span; we deliberately don't emit it as a separate counter because it is recoverable from the span timings. |
+
+All canonical counters are emitted via the openlit-go MeterProvider
+in `cli/internal/otlp/metrics.go` and pass through the same OTLP
+exporter as the spans, so a Prometheus / Mimir / Datadog backend
+attached to the OpenLit collector sees the same data as the trace
+backend.
+
+**Does coalesce-at-read scale?** Yes for current OpenLit volumes
+(under ~1M coding-agent spans per tenant per day). ClickHouse
+evaluates the per-row coalesce in a few milliseconds; the query
+bottleneck is the wider session scan, not the attribute lookup. Above
+that volume we'll ship a `coding_agent_sessions` materialized view
+that normalises both schemas at ingest. That deferral is documented
+inline in `queries.ts` next to the `E1 deferral note`.
+
+## Adding a new vendor
+
+The Cursor, Claude Code, and Codex adapters are the three reference
+implementations. Each one models a different vendor shape:
+
+- **Cursor** — IDE extension; 13+ named hook events, no per-session
+ transcript file, prompt/response/thought arrive as separate hooks.
+- **Claude Code** — CLI / IDE plugin; richer hook events plus a
+ per-session JSONL transcript that's the authoritative source for
+ per-turn LLM content + token usage. The adapter streams the
+ transcript with byte-offset bookkeeping.
+- **Codex** — CLI; per-turn hook protocol with `turn_id` on every
+ event and a separate rollout JSONL under
+ `~/.codex/sessions/YYYY/MM/DD/` that carries the `token_count`
+ events. The adapter accumulates a per-turn fragment in
+ sessionstate and drains it on `Stop`.
+
+To add another vendor (Windsurf / OpenCode / …):
+
+1. **Read the convention rule** — `.cursor/rules/coding-agents-convention.mdc`.
+ It defines the strict attribute matrix every adapter must follow.
+ New vendors must NOT introduce a new namespace for facts that
+ already have a canonical key.
+2. **Create the adapter package** under `cli/internal/coding/hook/<vendor>/`.
+ Map the vendor's hook payload keys onto the canonical `coding_agent.*`
+ / `gen_ai.*` schema. Use `setStr(..., scrub)` for any string —
+ never bypass the redaction layer.
+3. **Extend `peekContext`** in `hook.go` so the vendor's session id,
+ user, cwd, permission mode, model, and parent-conversation id
+ resolve from the payload. The function is intentionally a thin
+ string-pick — add new key names to the `pickString` calls.
+4. **Wire the plugin manifest** under `plugins/<vendor>/`. Mirror
+ `plugins/claude-code/` for Anthropic-style hooks or `plugins/cursor/`
+ for IDE-extension-style hooks. Add a marketplace entry in
+ `plugins/.claude-plugin/marketplace.json`.
+5. **Bound transcript reads** with `tailfile.Tail` if the vendor
+ exposes a per-session log file. Never read an unbounded file in a
+ hook process.
+6. **Stamp `gen_ai.system`** correctly: `anthropic` for Claude Code,
+ `openai` for Codex, `google` for Gemini-backed agents.
+ Use the `inferProvider(model, vendor)` helper.
+7. **Honor capture modes** — drop bodies in `minimal` and
+ `metadata_only`. The `bodyAllowed(mode)` and `setStr(..., scrub)`
+ helpers in `cli/internal/otlp/attrs.go` are mandatory.
+8. **Add UI icon + label**: register an inline SVG in
+ `src/client/src/components/svg/coding-agents.tsx` and add a switch
+ case in `CodingAgentVendorIcon` AND `hasCodingAgentVendorIcon`.
+ The existing call sites pick the icon up automatically once the
+ helpers know about the vendor.
+9. **Add the onboarding snippet** to `docs/features/coding-agents/onboarding.mdx`.
+ Document any vendor-specific env vars (`OTEL_*` overrides,
+ transcript paths, dual-path notes if applicable).
+10. **Sanity-check end to end**:
+ - Fire a real session through the vendor.
+ - Confirm `otel_traces` has spans with
+ `SpanAttributes['coding_agent.client'] = '<vendor>'`.
+ - Trigger the materializer
+ (`curl -X POST http://localhost:3000/api/agents/materialize -H 'X-CRON-JOB: true'`).
+ - Confirm a row lands in `openlit_agents_summary` with
+ `coding_agent_vendor = '<vendor>'` and `source = 'coding'`.
+ - Open `/agents`, click into the row, verify the Sessions and
+ Users tabs render without errors and that the trace-detail
+ pills (Repository, Working Folder, Branch, Mode, Terminal)
+ populate.
+
+## Threat model & accepted risks
+
+The CLI runs **on the developer's machine** alongside the coding
+agent. Anyone who can run `openlit coding hook` on that machine can
+emit arbitrary `coding_agent.*` spans into the configured collector
+— including spans claiming to be from a different session, vendor,
+or user. We accept this:
+
+- **Spoofing scope is bounded by who already has shell access.** A
+ developer who can run the hook can equally well run any other
+ process under their own user. There is no privilege boundary the
+ CLI is the only gate on.
+- **The OTLP endpoint authenticates the host, not the event.** The
+ Authorization header carries an org-scoped API key, so spans
+ reaching the backend are at least "from some machine our org
+ authorised". Per-event signing is intentionally out of scope for
+ v1 — the cost (key distribution, rotation, hook-latency budget)
+ outweighs the benefit for the threat model of in-org telemetry.
+- **Materialization runs k=5 cohort floors** so a single user
+ cannot inflate their own visible metrics by spamming events; the
+ per-user page refuses to render below five sessions.
+- **Repos and API keys drive the personal-vs-work classifier**, not
+ hook content. A user cannot relabel their own `personal` activity
+ as `work` by tampering with hook payloads.
+
+Operators that need stricter guarantees (e.g. an untrusted developer
+fleet) should:
+
+- Front the OTLP endpoint with a collector that drops events
+ whose `coding_agent.client.user.id` doesn't match the
+ authenticated key's owner.
+- Disable the hook tier and rely on vendor-native OTel only
+ (Claude Code's `CLAUDE_CODE_ENABLE_TELEMETRY=1` path) where the
+ vendor signs its own egress.
+
+## Where to read next
+
+- `.cursor/rules/coding-agents-convention.mdc` — the strict schema
+ contract every vendor must follow. The attribute matrix, the
+ Cursor + Claude Code inbound mappings, and the dual-path coalesce
+ rules all live here.
+- `.cursor/rules/coding-agents-hook.mdc` — canonical authoring rules
+ + failure modes, auto-loaded by Cursor when editing hook code.
+- `cli/internal/coding/hook/cursor/handle.go` — reference adapter.
+- `cli/internal/coding/hook/claudecode/handle.go` — second reference
+ adapter, demonstrates dual-path-aware design.
+- `cli/internal/coding/normalize/normalize.go` — schema all adapters
+ emit into.
+- `cli/internal/otlp/attrs.go` — capture-mode gating and scrubbing.
+- `src/client/src/lib/platform/agents/materialize.ts` — rollup that
+ populates `openlit_agents_summary`.
+- `src/client/src/lib/platform/coding-agents/queries.ts` — Sessions,
+ Users, Overview query layer.
diff --git a/docs/latest/openlit/coding-agents/onboarding.mdx b/docs/latest/openlit/coding-agents/onboarding.mdx
new file mode 100644
index 00000000..f75e3416
--- /dev/null
+++ b/docs/latest/openlit/coding-agents/onboarding.mdx
@@ -0,0 +1,319 @@
+---
+title: "Coding Agents — Onboarding"
+sidebarTitle: "Coding Agents Onboarding"
+description: "Send Claude Code, Cursor, and Codex telemetry into OpenLit in under a minute."
+---
+
+OpenLit ships first-class observability for AI coding agents. The
+`openlit` CLI ingests events from each vendor's hook system, normalizes
+them onto OpenTelemetry's `gen_ai.*` and OpenLit's `coding_agent.*`
+semantic conventions, and ships them to your existing OpenLit
+collector. The `/agents` page detects them automatically — no
+controller, no SDK, no code change in your repos.
+
+<Note>
+You only need an OpenLit instance and the `openlit` CLI on each
+developer's machine. The CLI talks **only** to your OpenLit endpoint.
+There is no managed cloud for coding-agent telemetry.
+</Note>
+
+## Prerequisites
+
+- A running OpenLit instance — see
+ [Installation](/latest/openlit/installation) if you don't have one.
+- An OpenLit API key (Settings → API Keys).
+- The OTLP endpoint of your OpenLit collector (defaults to
+ `http://localhost:4318` for local installs).
+
+## 1. Install the CLI
+
+Pick the path that matches your OS. All paths install the same
+`openlit` binary built by `cli-release.yml`.
+
+<CodeGroup>
+```bash macOS
+brew install openlit/openlit/openlit
+```
+
+```bash Linux
+curl -fsSL https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/install.sh | sh
+```
+
+```powershell Windows
+iwr -useb https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/install.ps1 | iex
+```
+
+```bash docker
+docker run --rm -it ghcr.io/openlit/openlit-cli:latest --help
+```
+</CodeGroup>
+
+The Linux and Windows scripts install to `~/.openlit/bin/openlit` and
+`%USERPROFILE%\.openlit\bin\openlit.exe` respectively. The Linux
+script prints a PATH-add hint if the directory is not already on
+`$PATH`; the Windows script updates user-scope PATH automatically
+(open a new terminal to pick it up).
+
+If you prefer to build from source: `go install github.com/openlit/openlit/cli/cmd/openlit@latest`.
+
+## 2. Configure once
+
+The fastest path is `openlit configure` — it answers the same
+questions a CI / Helm chart would set via env. The result is written
+to `~/.config/openlit/config.env` (Linux/macOS) or
+`%APPDATA%\openlit\config.env` (Windows). For headless / fleet
+rollouts, prefer env vars or flags directly — they take precedence
+over the file (flags > env > config file).
+
+```bash
+openlit configure \
+ --endpoint https://openlit.example.com:4318 \
+ --api-key $OPENLIT_API_KEY
+```
+
+Equivalent environment variables (precedence: flags > env > config file):
+
+| Variable | Purpose |
+|---|---|
+| `OPENLIT_OTLP_ENDPOINT` | OTLP/HTTP endpoint of your collector |
+| `OPENLIT_API_KEY` | Authenticates the OTLP exporter |
+| `OPENLIT_USER` | Optional override for `gen_ai.user.name` (email or login) |
+| `OPENLIT_CODING_CONTENT_CAPTURE` | `minimal` \| `metadata_only` \| `full` *(default: `full`)* |
+
+Standard `OTEL_EXPORTER_OTLP_*` variables are honoured as fallbacks
+so existing OTel users can reuse their setup.
+
+<Tip>
+`OPENLIT_CODING_CONTENT_CAPTURE` defaults to `full` so the trace
+detail view is useful on first use — prompt bodies, agent replies,
+and tool I/O are stamped onto every per-event span, scrubbed by the
+tier-1 secret redactor on the way out. Switch to `metadata_only`
+when rolling out across a team where prompts may carry confidential
+material (the trace-detail page will surface a note on every span
+explaining how). Use `minimal` if you only need cost + activity
+dashboards and not the per-event timeline.
+</Tip>
+
+## 3. Wire each vendor
+
+`openlit coding install` writes the right hook config for the agent
+you pass and is fully idempotent. You can also point at the
+[plugin marketplace](https://github.com/openlit/openlit/tree/main/plugins)
+and let the agent pull the manifest itself, or invoke the agent
+through `openlit coding launch` which auto-installs and execs.
+
+<Tabs>
+<Tab title="Claude Code">
+
+```bash
+# One-time install
+openlit coding install --vendor=claude-code
+
+# Or run Claude Code through the launcher (auto-installs)
+openlit coding launch claude-code
+```
+
+Manifest path: `~/.claude/plugins/openlit-cc/`. Hooks wired:
+`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
+`Stop`, `SubagentStop`, `SessionEnd`. Claude Code's transcript JSONL
+(`transcript_path` in the hook payload) is tailed on `SessionStart`
+for early model attribution and on `SessionEnd` for authoritative
+token usage and cost.
+
+**Optional: Claude Code's native OpenTelemetry exporter.** If you'd
+rather not install the plugin, or you want a second signal source
+for cross-checking, you can point Claude Code's built-in OTel
+exporter at your OpenLit collector instead. Both paths can run side
+by side — OpenLit dedupes per `session.id` (Claude Code's authoritative
+cost / tokens from the native path win, while the hook path provides
+the repository / working folder context that Claude Code itself
+can't see).
+
+```bash
+export CLAUDE_CODE_ENABLE_TELEMETRY=1
+export OTEL_METRICS_EXPORTER=otlp
+export OTEL_LOGS_EXPORTER=otlp
+export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
+export OTEL_EXPORTER_OTLP_ENDPOINT=$OPENLIT_OTLP_ENDPOINT
+export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer $OPENLIT_API_KEY"
+# Optional: also enable traces (beta — gives per-tool / per-LLM-turn spans)
+export CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1
+export OTEL_TRACES_EXPORTER=otlp
+```
+
+See [Claude Code's monitoring docs](https://code.claude.com/docs/en/monitoring-usage)
+for the full environment-variable surface (managed settings, dynamic
+headers, cardinality controls, content-capture gates). When both
+paths are active OpenLit folds them into one chat thread; see the
+"Dual-path coalesce" section of the [architecture guide](./architecture)
+for the details.
+
+</Tab>
+<Tab title="Cursor">
+
+```bash
+openlit coding install --vendor=cursor
+```
+
+Manifest path: `~/.cursor/hooks.json` (user scope — applies to every
+workspace you open in Cursor; works the same on macOS, Linux, and
+Windows). All Cursor hook events (sessionStart/End, prompt /
+response / thought, tool + shell + MCP phases, subagent lifecycle,
+file edits, preCompact) invoke
+`openlit coding hook --vendor=cursor --event=<name>` directly.
+At install time the `openlit` token in each `command` is rewritten
+to the absolute path of the CLI binary that ran
+`openlit coding install`, which sidesteps the minimal-PATH that
+GUI-launched Cursor windows inherit on macOS and Linux, and makes
+the same manifest work on Windows where there is no shell wrapper.
+
+<Note>
+We merge into `~/.cursor/hooks.json` (user scope) rather than drop
+a plugin tree elsewhere because Cursor only auto-discovers plugins
+that were registered through its in-app `/add-plugin` flow.
+User-scope hooks are the supported way to install agent-wide hooks
+without an in-app step, and re-running
+`openlit coding install --vendor=cursor` is idempotent: prior
+openlit entries are dropped before the new ones are appended, and
+any third-party entries you (or another tool) have added are left
+in place.
+</Note>
+
+</Tab>
+<Tab title="Codex">
+
+```bash
+openlit coding install --vendor=codex
+```
+
+Manifest path: `~/.codex/plugins/openlit/`. Hooks wired:
+`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
+`Stop`. Codex scopes every hook to a `turn_id` so we emit one
+`coding_agent.llm.turn` span per turn (built on `Stop`), with the
+prompt, last-assistant message, and the per-tool calls produced
+during that turn folded into the OTel-canonical
+`gen_ai.input.messages` / `gen_ai.output.messages` envelopes.
+
+The CLI tails `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` on
+`Stop` to compute the per-turn token delta (input, output, cached,
+reasoning) from Codex's running `token_count` events, so cost
+rollups in OpenLit reflect the same per-turn deltas Codex itself
+records.
+
+Subagent linkage is read from the transcript's `session_meta`
+record at `SessionStart`; child turns inherit
+`coding_agent.agent.parent_id` automatically so the UI folds them
+under the spawning chat. Codex doesn't expose a `SessionEnd` event,
+so the session row updates incrementally as each `Stop` lands.
+
+If `codex features list` doesn't already enable `codex_hooks` on
+your build, add this to `~/.codex/config.toml`:
+
+```toml
+[features]
+codex_hooks = true
+
+[plugins."openlit"]
+enabled = true
+```
+
+Older Codex builds use `hooks = true` and `plugin_hooks = true`
+instead of `codex_hooks`.
+
+</Tab>
+</Tabs>
+
+## 4. Verify
+
+Run any short coding-agent session, then refresh `/agents` in your
+OpenLit UI. You should see a new row labelled with the vendor and a
+"Coding" badge. Click in for the dedicated Overview / Sessions /
+Dashboard tabs.
+
+## What gets captured
+
+| Surface | What you get out of the box |
+|---|---|
+| `/agents` row | Per-vendor row with sessions, active users, cost, lines added/removed, acceptance %, commits and PRs — all evaluated over the time range selected in the global filter picker (the materialized rollups are overlaid with a live recompute for any custom window). |
+| Overview tab | The seeded "Coding Agents" dashboard, scoped to this vendor, honoring the picker. |
+| Sessions tab | `coding_agent.session.id` rows within the selected window — outcome, cost, classification, per-session lines (+/−), acceptance %, commits, PRs. |
+| Dashboard tab | Seeded board (vendor breakdown, top tools, top users, top repos, classification, MCP servers, edit decisions, lines accepted, acceptance %, commits, PRs, lines-over-time area, top users by accepted, acceptance breakdown pie). Every widget reads `{{filter.timeLimit.start}}` / `{{filter.timeLimit.end}}`. |
+| Per-user page | Code-impact stat row (lines added, lines accepted, acceptance %, commits, PRs) above the user-scoped dashboard. The stat row re-fetches when the picker changes, so the row and the widgets below it stay in lockstep. |
+| Custom dashboards | Same data — query `otel_traces WHERE SpanName IN ('coding_agent.session', 'coding_agent.edit.decision', 'coding_agent.git.commit', 'coding_agent.git.pull_request', …)` |
+| Metrics pipeline | `coding_agent.session.count`, `coding_agent.session.duration`, `coding_agent.tool.call.count`, `coding_agent.lines_of_code.count`, `coding_agent.edit.decision.count`, `coding_agent.commit.count`, `coding_agent.pull_request.count` counters emitted via the openlit-go MeterProvider |
+
+## Privacy & governance
+
+- **Tier-1 redaction** runs on every export and scrubs API keys,
+ tokens, and known secret patterns without breaking JSON structure.
+- **Personal vs Work classification** is stamped at hook time using
+ the org's API-key and repo-origin allowlists (configured in OpenLit
+ Settings). Disputes can be filed via
+ `POST /api/coding-agents/classification/dispute`; surfacing a
+ dispute button on the Sessions tab is planned for the next release.
+- **k=5 cohort floor**: viewer-tier accounts cannot see per-user
+ attribution below five sessions. Admins can.
+
+## Stop tracking / uninstall
+
+The inverse of `openlit coding install`. Removes the per-vendor host
+plugin manifests written by install, deregisters the plugin from the
+vendor's own CLI where applicable (Claude Code, Codex), and leaves
+your shared config alone by default so you can re-onboard without
+re-entering credentials.
+
+```bash
+openlit coding uninstall --vendor=cursor # one vendor
+openlit coding uninstall --vendor=all # every vendor at once
+openlit coding uninstall --vendor=all --purge # also drop ~/.config/openlit + session-state cache
+openlit coding uninstall --vendor=cursor --dry-run # preview without touching disk
+```
+
+What each flag removes:
+
+| Path | Removed by `--vendor=<v>` | Removed by `--purge` |
+|---|---|---|
+| `~/.claude/plugins/openlit-cc/` | ✓ (when `<v>` is `claude-code` or `all`) | — |
+| `~/.local/share/openlit/claude-marketplace/` | ✓ (when `<v>` is `claude-code` or `all`) | — |
+| openlit entries in `~/.cursor/hooks.json` (other tools' entries preserved; file deleted if it ends up empty) | ✓ (when `<v>` is `cursor` or `all`) | — |
+| `~/.local/share/openlit/codex-marketplace/` | ✓ (when `<v>` is `codex` or `all`) | — |
+| `claude plugin uninstall openlit-cc@openlit` | ✓ best-effort | — |
+| `codex plugin remove openlit@openlit` + `codex plugin marketplace remove openlit` | ✓ best-effort | — |
+| `~/.config/openlit/` (your `configure` output) | — | ✓ |
+| `<UserCacheDir>/openlit/sessions/` (session-state cache) | — | ✓ |
+
+The `openlit` binary itself is **not** touched. Uninstall it the way
+you installed it:
+
+```bash
+brew uninstall openlit # Homebrew
+rm ~/.openlit/bin/openlit # curl|sh installer
+rm $(go env GOPATH)/bin/openlit # go install
+```
+
+## Troubleshooting
+
+- **First stop** — run `openlit doctor`. It prints the resolved
+ config, the cached session count, the installed plugin paths, and
+ TCP-dials your OTLP endpoint. Exit code 1 means at least one
+ failure; 0 (possibly with warnings) means the CLI is wired up.
+- **No row on /agents** — the hook never writes to a log file; it
+ emits to stderr, which is captured by the host coding agent's
+ own logs (Claude Code: `~/.claude/logs/`; Cursor: Developer
+ Tools → Console; Codex: `~/.codex/`). Set
+ `OPENLIT_DEBUG_PAYLOAD_DIR=/tmp/openlit-debug` to capture the
+ exact JSON the vendor is sending the hook — useful when fields
+ appear to be missing on the resulting spans.
+- **Hooks ran but no spans** — confirm `openlit configure --show`
+ reports the right endpoint. The CLI never reads `~/.zshrc`; if you
+ set OPENLIT_* in your shell rc, source it before launching the agent.
+- **"Database config not found" on /agents** — your OpenLit
+ installation hasn't run the latest migrations. Restart the
+ `openlit` container or run the migration manually
+ (`pnpm --filter client run migrate`).
+
+## What's next
+
+- The CLI reserves subcommands for `prompts`, `traces`, and `eval`;
+ these will light up in subsequent releases without breaking the
+ coding-agent integration.
diff --git a/plugins/claude-code/.claude-plugin/plugin.json b/plugins/claude-code/.claude-plugin/plugin.json
new file mode 100644
index 00000000..b2165aeb
--- /dev/null
+++ b/plugins/claude-code/.claude-plugin/plugin.json
@@ -0,0 +1,11 @@
+{
+ "name": "openlit-cc",
+ "version": "0.1.0",
+ "description": "OpenLit telemetry for Claude Code: sessions, tool calls, edit decisions, and cost rollups.",
+ "author": {
+ "name": "OpenLit",
+ "url": "https://openlit.io"
+ },
+ "repository": "https://github.com/openlit/openlit",
+ "homepage": "https://openlit.io"
+}
diff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.json
new file mode 100644
index 00000000..c00dfabe
--- /dev/null
+++ b/plugins/claude-code/hooks/hooks.json
@@ -0,0 +1,83 @@
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=SessionStart",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=UserPromptSubmit",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=PreToolUse",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=PostToolUse",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=Stop",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "SubagentStop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=SubagentStop",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "SessionEnd": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=cc --event=SessionEnd",
+ "timeout": 5
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/codex/.agents/plugins/marketplace.json b/plugins/codex/.agents/plugins/marketplace.json
new file mode 100644
index 00000000..ab786b53
--- /dev/null
+++ b/plugins/codex/.agents/plugins/marketplace.json
@@ -0,0 +1,23 @@
+{
+ "name": "openlit",
+ "interface": {
+ "displayName": "OpenLit",
+ "shortDescription": "OpenTelemetry-native session, tool, and turn capture for Codex.",
+ "developerName": "OpenLit",
+ "websiteURL": "https://openlit.io"
+ },
+ "plugins": [
+ {
+ "name": "openlit",
+ "source": {
+ "source": "local",
+ "path": "./plugins/openlit"
+ },
+ "policy": {
+ "installation": "AVAILABLE",
+ "authentication": "ON_INSTALL"
+ },
+ "category": "Engineering"
+ }
+ ]
+}
diff --git a/plugins/codex/plugins/openlit/.codex-plugin/plugin.json b/plugins/codex/plugins/openlit/.codex-plugin/plugin.json
new file mode 100644
index 00000000..4c6152ee
--- /dev/null
+++ b/plugins/codex/plugins/openlit/.codex-plugin/plugin.json
@@ -0,0 +1,22 @@
+{
+ "name": "openlit",
+ "displayName": "OpenLit",
+ "version": "0.1.0",
+ "description": "OpenLit telemetry for Codex: sessions, tool calls, LLM turns with token usage, and cost rollups.",
+ "author": {
+ "name": "OpenLit",
+ "url": "https://openlit.io"
+ },
+ "repository": "https://github.com/openlit/openlit",
+ "homepage": "https://openlit.io",
+ "license": "Apache-2.0",
+ "keywords": ["telemetry", "observability", "openlit", "codex"],
+ "hooks": "./hooks/hooks.json",
+ "interface": {
+ "displayName": "OpenLit for Codex",
+ "shortDescription": "OpenTelemetry-native session, tool, and turn capture",
+ "developerName": "OpenLit",
+ "category": "Engineering",
+ "capabilities": ["Read", "Write"]
+ }
+}
diff --git a/plugins/codex/plugins/openlit/hooks/hooks.json b/plugins/codex/plugins/openlit/hooks/hooks.json
new file mode 100644
index 00000000..94e96ac2
--- /dev/null
+++ b/plugins/codex/plugins/openlit/hooks/hooks.json
@@ -0,0 +1,62 @@
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "matcher": "startup|resume|clear",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=SessionStart",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=UserPromptSubmit",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=PreToolUse",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=PostToolUse",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "openlit coding hook --vendor=codex --event=Stop",
+ "timeout": 30
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/cursor/.cursor-plugin/plugin.json b/plugins/cursor/.cursor-plugin/plugin.json
new file mode 100644
index 00000000..4a274d5b
--- /dev/null
+++ b/plugins/cursor/.cursor-plugin/plugin.json
@@ -0,0 +1,12 @@
+{
+ "name": "openlit",
+ "displayName": "OpenLit",
+ "version": "0.1.0",
+ "description": "OpenLit telemetry for Cursor: sessions, tool calls, edit decisions, and cost rollups.",
+ "author": {
+ "name": "OpenLit",
+ "url": "https://openlit.io"
+ },
+ "repository": "https://github.com/openlit/openlit",
+ "homepage": "https://openlit.io"
+}
diff --git a/plugins/cursor/hooks/hooks.json b/plugins/cursor/hooks/hooks.json
new file mode 100644
index 00000000..4fa4e420
--- /dev/null
+++ b/plugins/cursor/hooks/hooks.json
@@ -0,0 +1,113 @@
+{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=sessionStart",
+ "timeout": 5000
+ }
+ ],
+ "sessionEnd": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=sessionEnd",
+ "timeout": 5000
+ }
+ ],
+ "beforeSubmitPrompt": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=beforeSubmitPrompt",
+ "timeout": 5000
+ }
+ ],
+ "afterAgentResponse": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterAgentResponse",
+ "timeout": 5000
+ }
+ ],
+ "afterAgentThought": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterAgentThought",
+ "timeout": 5000
+ }
+ ],
+ "preToolUse": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=preToolUse",
+ "timeout": 5000
+ }
+ ],
+ "postToolUse": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=postToolUse",
+ "timeout": 5000
+ }
+ ],
+ "postToolUseFailure": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=postToolUseFailure",
+ "timeout": 5000
+ }
+ ],
+ "subagentStart": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=subagentStart",
+ "timeout": 5000
+ }
+ ],
+ "subagentStop": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=subagentStop",
+ "timeout": 5000
+ }
+ ],
+ "beforeShellExecution": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=beforeShellExecution",
+ "timeout": 5000
+ }
+ ],
+ "afterShellExecution": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterShellExecution",
+ "timeout": 5000
+ }
+ ],
+ "beforeMCPExecution": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=beforeMCPExecution",
+ "timeout": 5000
+ }
+ ],
+ "afterMCPExecution": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterMCPExecution",
+ "timeout": 5000
+ }
+ ],
+ "beforeReadFile": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=beforeReadFile",
+ "timeout": 5000
+ }
+ ],
+ "afterFileEdit": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=afterFileEdit",
+ "timeout": 5000
+ }
+ ],
+ "preCompact": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=preCompact",
+ "timeout": 5000
+ }
+ ],
+ "stop": [
+ {
+ "command": "openlit coding hook --vendor=cursor --event=stop",
+ "timeout": 5000
+ }
+ ]
+ }
+}
diff --git a/sdk/go/config.go b/sdk/go/config.go
index ff143da8..d728f359 100644
--- a/sdk/go/config.go
+++ b/sdk/go/config.go
@@ -2,6 +2,8 @@ package openlit
import (
"time"
+
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
// Config holds the configuration for OpenLIT SDK initialization
@@ -70,6 +72,27 @@ type Config struct {
// DetailedTracing enables detailed component-level tracing.
// Default: false
DetailedTracing bool
+
+ // IDGenerator overrides the default OTel ID generator. Use this when
+ // callers need deterministic trace/span IDs (e.g. the openlit CLI's
+ // coding-agent hook deriving a stable TraceId from a session id so
+ // every span emitted across separate hook invocations lands in the
+ // same trace). When nil, OTel's random generator is used.
+ IDGenerator sdktrace.IDGenerator
+
+ // Sampler overrides the default head sampler. When nil, the SDK
+ // uses AlwaysSample — every span emitted reaches the collector.
+ // Callers wanting a head-sampling strategy (e.g. drop noisy
+ // `coding_agent.tool.requested` events) can pass a
+ // ParentBasedSampler or a custom span-name aware sampler here.
+ // See cli/internal/otlp/sampler.go for an example.
+ Sampler sdktrace.Sampler
+
+ // ExtraResourceAttributes are merged into the OTel Resource set on
+ // every span/metric this SDK emits. Callers use this to attach
+ // stable identity (e.g. `gen_ai.user.name`, `host.name`) once at
+ // startup rather than tagging each span individually.
+ ExtraResourceAttributes map[string]string
}
// ModelPricing represents pricing information for a model
diff --git a/sdk/go/openlit.go b/sdk/go/openlit.go
index 5e473f86..7312bb76 100644
--- a/sdk/go/openlit.go
+++ b/sdk/go/openlit.go
@@ -184,6 +184,23 @@ func newResource(cfg Config) (*resource.Resource, error) {
))
}
+ // Caller-supplied extras (e.g. `gen_ai.user.name`, `host.name`)
+ // attach once at SDK init and then ride along on every span. Empty
+ // keys/values are skipped so a missing field doesn't pollute the
+ // resource map.
+ if len(cfg.ExtraResourceAttributes) > 0 {
+ extras := make([]attribute.KeyValue, 0, len(cfg.ExtraResourceAttributes))
+ for k, v := range cfg.ExtraResourceAttributes {
+ if k == "" || v == "" {
+ continue
+ }
+ extras = append(extras, attribute.String(k, v))
+ }
+ if len(extras) > 0 {
+ attrs = append(attrs, resource.WithAttributes(extras...))
+ }
+ }
+
return resource.New(
context.Background(),
append(attrs, resource.WithTelemetrySDK())...,
@@ -215,11 +232,23 @@ func newTracerProvider(res *resource.Resource, cfg Config) (*trace.TracerProvide
spanProcessor = trace.NewBatchSpanProcessor(exporter)
}
- tp := trace.NewTracerProvider(
+ sampler := cfg.Sampler
+ if sampler == nil {
+ // Default beta posture: keep every span. Production
+ // callers should set Config.Sampler to a head sampler
+ // matching their volume budget. See D8 in the
+ // coding-agents plan.
+ sampler = trace.AlwaysSample()
+ }
+ tpOpts := []trace.TracerProviderOption{
trace.WithResource(res),
trace.WithSpanProcessor(spanProcessor),
- trace.WithSampler(trace.AlwaysSample()),
- )
+ trace.WithSampler(sampler),
+ }
+ if cfg.IDGenerator != nil {
+ tpOpts = append(tpOpts, trace.WithIDGenerator(cfg.IDGenerator))
+ }
+ tp := trace.NewTracerProvider(tpOpts...)
return tp, nil
}
diff --git a/sdk/go/semconv/coding_agent.go b/sdk/go/semconv/coding_agent.go
new file mode 100644
index 00000000..b0ed0e67
--- /dev/null
+++ b/sdk/go/semconv/coding_agent.go
@@ -0,0 +1,336 @@
+// Coding Agent semantic conventions.
+//
+// These attributes extend OTel GenAI conventions for first-class observability
+// of AI coding assistants (Claude Code, Cursor, Codex, etc.).
+// They are namespaced under `coding_agent.*` so they coexist cleanly with
+// OTel's standard `gen_ai.*`, `vcs.*`, and `server.*` semconvs.
+//
+// Reuse OTel's existing attributes wherever sensible:
+// - gen_ai.conversation.id → session linkage
+// - gen_ai.agent.name → vendor identifier (e.g. "claude-code")
+// - gen_ai.tool.name → invoked tool
+// - gen_ai.usage.* → token/cost rollups
+// - vcs.repository.url.full → repo URL (OTel vcs semconv)
+// - vcs.ref.head.revision → commit SHA (OTel vcs semconv)
+// - vcs.ref.head.name → branch (OTel vcs semconv)
+//
+// Anything OTel doesn't define lives here.
+
+package semconv
+
+// Vendor identifiers (used as `gen_ai.agent.name` value).
+const (
+ CodingAgentVendorClaudeCode = "claude-code"
+ CodingAgentVendorCursor = "cursor"
+ CodingAgentVendorCodex = "codex"
+ CodingAgentVendorWindsurf = "windsurf"
+)
+
+// Session structure attributes.
+const (
+ // CodingAgentSessionID identifies a single coding-agent session.
+ // Used as the join key across all spans/events emitted for that session.
+ CodingAgentSessionID = "coding_agent.session.id"
+ // CodingAgentClient is the vendor identifier; mirror of gen_ai.agent.name.
+ // Carried separately so dashboard widgets can filter without
+ // pulling in the full gen_ai.* attribute set.
+ CodingAgentClient = "coding_agent.client"
+ // CodingAgentClientVersion is the vendor's client version.
+ CodingAgentClientVersion = "coding_agent.client.version"
+ // CodingAgentSessionOutcome captures how the session ended.
+ // One of: merged | committed | abandoned_no_change | abandoned_with_change | cancelled.
+ CodingAgentSessionOutcome = "coding_agent.session.outcome"
+ // CodingAgentSessionDurationMs is wall-clock duration in milliseconds.
+ CodingAgentSessionDurationMs = "coding_agent.session.duration_ms"
+ // CodingAgentSessionToolCallCount totals tool invocations during the session.
+ CodingAgentSessionToolCallCount = "coding_agent.session.tool_call_count"
+ // CodingAgentSessionSubagentCount totals child/subagent spawns.
+ CodingAgentSessionSubagentCount = "coding_agent.session.subagent_count"
+ // CodingAgentSessionCostUSD is the realized USD cost.
+ CodingAgentSessionCostUSD = "coding_agent.session.cost_usd"
+
+ // Per-session code-change rollups stamped on the
+ // `coding_agent.session` root span at SessionEnd. They aggregate
+ // edit / accept / reject / line counts the adapter observed
+ // across the session so dashboards don't have to fan out into
+ // every `coding_agent.edit.decision` span.
+ //
+ // Mirrors Claude Code's native `claude_code.lines_of_code.count`
+ // metric shape — when the operator ships both paths (hook + native
+ // OTel exporter), the query layer coalesces.
+ CodingAgentSessionLinesAdded = "coding_agent.session.lines.added"
+ CodingAgentSessionLinesRemoved = "coding_agent.session.lines.removed"
+ CodingAgentSessionLinesAccepted = "coding_agent.session.lines.accepted"
+ CodingAgentSessionLinesRejected = "coding_agent.session.lines.rejected"
+ CodingAgentSessionEditAcceptCount = "coding_agent.session.edit.accept_count"
+ CodingAgentSessionEditRejectCount = "coding_agent.session.edit.reject_count"
+ CodingAgentSessionCommitCount = "coding_agent.session.commit_count"
+ CodingAgentSessionPRCount = "coding_agent.session.pr_count"
+)
+
+// Session outcome values.
+const (
+ // CodingAgentSessionOutcomeCompleted — the agent reported a
+ // successful end of the session (Cursor's reason="completed",
+ // Claude Code's "stop", etc). The user may or may not have
+ // merged anything; we stay agnostic on downstream VCS state.
+ CodingAgentSessionOutcomeCompleted = "completed"
+ CodingAgentSessionOutcomeMerged = "merged"
+ CodingAgentSessionOutcomeCommitted = "committed"
+ CodingAgentSessionOutcomeAbandonedNoChange = "abandoned_no_change"
+ CodingAgentSessionOutcomeAbandonedWithChange = "abandoned_with_change"
+ CodingAgentSessionOutcomeCancelled = "cancelled"
+)
+
+// Subagent linkage attributes.
+const (
+ // CodingAgentAgentID is a stable id for this agent instance within the
+ // session (root or subagent). Use parent_id to walk the tree.
+ CodingAgentAgentID = "coding_agent.agent.id"
+ // CodingAgentAgentParentID points at the spawning agent's id.
+ CodingAgentAgentParentID = "coding_agent.agent.parent_id"
+ // CodingAgentAgentType is one of: main | subagent | task_tool.
+ CodingAgentAgentType = "coding_agent.agent.type"
+ // CodingAgentSubagentType is the vendor-specific subagent kind
+ // (e.g. Claude Code's named subagents, Codex spawn types).
+ CodingAgentSubagentType = "coding_agent.subagent.type"
+ // CodingAgentLinkageConfidence reports how reliable the parent_id
+ // linkage is for this vendor: high | medium | low.
+ // Codex subagent linkage is often medium because parent is
+ // inferred via process metadata rather than carried by the protocol.
+ CodingAgentLinkageConfidence = "coding_agent.linkage_confidence"
+)
+
+const (
+ CodingAgentAgentTypeMain = "main"
+ CodingAgentAgentTypeSubagent = "subagent"
+ CodingAgentAgentTypeTaskTool = "task_tool"
+
+ CodingAgentLinkageConfidenceHigh = "high"
+ CodingAgentLinkageConfidenceMedium = "medium"
+ CodingAgentLinkageConfidenceLow = "low"
+)
+
+// Edit decision attributes — captured per file/edit so dashboards can
+// distinguish auto-applied agent edits from user-reviewed ones.
+// OTel has no standard for this; this is the major gap we fill.
+const (
+ // CodingAgentEditDecision is one of: accept | reject | modify | auto_accepted.
+ CodingAgentEditDecision = "coding_agent.edit.decision"
+ // CodingAgentEditDecisionSource is the trigger:
+ // user_interactive | user_permanent_rule | hook | config | policy.
+ CodingAgentEditDecisionSource = "coding_agent.edit.decision.source"
+ // CodingAgentEditLinesAdded is the count of added lines.
+ CodingAgentEditLinesAdded = "coding_agent.edit.lines.added"
+ // CodingAgentEditLinesRemoved is the count of removed lines.
+ CodingAgentEditLinesRemoved = "coding_agent.edit.lines.removed"
+ // CodingAgentEditLanguage is the detected programming language.
+ CodingAgentEditLanguage = "coding_agent.edit.language"
+ // CodingAgentEditToolName is the tool that produced the edit
+ // (e.g. "Edit", "Write", "Apply Patch").
+ CodingAgentEditToolName = "coding_agent.edit.tool.name"
+)
+
+const (
+ CodingAgentEditDecisionAccept = "accept"
+ CodingAgentEditDecisionReject = "reject"
+ CodingAgentEditDecisionModify = "modify"
+ CodingAgentEditDecisionAutoAccepted = "auto_accepted"
+
+ CodingAgentEditDecisionSourceUserInteractive = "user_interactive"
+ CodingAgentEditDecisionSourceUserPermanentRule = "user_permanent_rule"
+ CodingAgentEditDecisionSourceHook = "hook"
+ CodingAgentEditDecisionSourceConfig = "config"
+ CodingAgentEditDecisionSourcePolicy = "policy"
+)
+
+// Tool causality attributes — link tool invocations back to the model
+// turn that triggered them. OTel typed span links (PR #3575) will replace
+// these once they ship; until then, this is the explicit join key.
+const (
+ // CodingAgentToolTriggeringLLMRequestID is the LLM response id
+ // whose tool_calls produced this invocation.
+ CodingAgentToolTriggeringLLMRequestID = "coding_agent.tool.triggering_llm_request_id"
+ // CodingAgentToolIteration is the loop index for retried/iterated tools.
+ CodingAgentToolIteration = "coding_agent.tool.iteration"
+ // CodingAgentToolGroupID groups tools fired in the same model turn.
+ CodingAgentToolGroupID = "coding_agent.tool.group.id"
+ // CodingAgentToolGroupType describes the group's intent
+ // (e.g. "file_edit", "search", "bash").
+ CodingAgentToolGroupType = "coding_agent.tool.group.type"
+)
+
+// MCP server attribution.
+const (
+ // CodingAgentMCPServerName is the MCP server identifier.
+ CodingAgentMCPServerName = "coding_agent.mcp.server.name"
+ // CodingAgentMCPScope is one of: user | project | local | enterprise.
+ CodingAgentMCPScope = "coding_agent.mcp.scope"
+ // CodingAgentMCPTransport is one of: stdio | sse | streamable_http.
+ CodingAgentMCPTransport = "coding_agent.mcp.transport"
+ // CodingAgentMCPSource is one of: builtin | plugin | marketplace.
+ CodingAgentMCPSource = "coding_agent.mcp.source"
+)
+
+const (
+ CodingAgentMCPScopeUser = "user"
+ CodingAgentMCPScopeProject = "project"
+ CodingAgentMCPScopeLocal = "local"
+ CodingAgentMCPScopeEnterprise = "enterprise"
+
+ CodingAgentMCPTransportStdio = "stdio"
+ CodingAgentMCPTransportSSE = "sse"
+ CodingAgentMCPTransportStreamableHTTP = "streamable_http"
+
+ CodingAgentMCPSourceBuiltin = "builtin"
+ CodingAgentMCPSourcePlugin = "plugin"
+ CodingAgentMCPSourceMarketplace = "marketplace"
+)
+
+// VCS bridging — repo / branch / commit live under OTel's standard
+// `vcs.*` attributes (see Reuse note at top of file), stamped on the
+// session root from local git context by `cli/internal/coding/git`.
+// The constants below cover what OTel doesn't define.
+const (
+ // CodingAgentVCSDirty indicates the working tree has uncommitted changes
+ // when the agent started. Boolean serialized as "true"/"false".
+ CodingAgentVCSDirty = "coding_agent.vcs.dirty"
+)
+
+// Identity & policy attributes.
+const (
+ // CodingAgentUserClassification is one of: personal | work | disputed | unknown.
+ // Stamped at hook-time using API-key allowlist + repo-origin allowlist.
+ CodingAgentUserClassification = "coding_agent.user.classification"
+ // CodingAgentUserClassificationReason explains the classification
+ // (e.g. "api_key_allowlist", "repo_origin_match", "no_signal").
+ CodingAgentUserClassificationReason = "coding_agent.user.classification.reason"
+ // CodingAgentPolicyPermissionMode captures how permissive the run is
+ // (e.g. "interactive", "auto_accept", "dangerously_skip_permissions").
+ CodingAgentPolicyPermissionMode = "coding_agent.policy.permission_mode"
+ // CodingAgentContentCaptureMode is the active capture posture:
+ // minimal | metadata_only | full. See `cli/internal/otlp/attrs.go`
+ // for the per-mode attribute matrix.
+ CodingAgentContentCaptureMode = "coding_agent.content_capture_mode"
+)
+
+const (
+ CodingAgentUserClassificationPersonal = "personal"
+ CodingAgentUserClassificationWork = "work"
+ CodingAgentUserClassificationDisputed = "disputed"
+ CodingAgentUserClassificationUnknown = "unknown"
+
+ // CodingAgentContentCaptureMinimal — only session bookends and
+ // rolled-up counters. No per-event spans. Cheapest tier; for
+ // enterprises that want budget visibility without per-prompt
+ // content. See Phase C of the coding-agents plan.
+ CodingAgentContentCaptureMinimal = "minimal"
+ // CodingAgentContentCaptureMetadataOnly — per-event spans with
+ // counts/timings/cost/repo but redacted bodies (no prompts, no
+ // tool args, no shell flags). Recommended default.
+ CodingAgentContentCaptureMetadataOnly = "metadata_only"
+ // CodingAgentContentCaptureFull — everything metadata mode has
+ // plus prompts, responses, thoughts, tool args, tool results.
+ // Tier-2 PII redaction still runs. For trust+safety reviews.
+ CodingAgentContentCaptureFull = "full"
+)
+
+// Loop detection.
+const (
+ // CodingAgentLoopDetected is true when an in-session loop is detected.
+ CodingAgentLoopDetected = "coding_agent.loop.detected"
+ // CodingAgentLoopPattern names the pattern (e.g. "edit_revert_edit",
+ // "tool_retry").
+ CodingAgentLoopPattern = "coding_agent.loop.pattern"
+)
+
+// Hook plumbing — these are reserved attributes the CLI stamps on every
+// hook invocation so we can debug and version the wire format.
+const (
+ // CodingAgentHookEvent names the originating hook event (e.g. "PreToolUse").
+ CodingAgentHookEvent = "coding_agent.hook.event"
+ // CodingAgentHookCLIVersion identifies the openlit CLI version.
+ CodingAgentHookCLIVersion = "coding_agent.hook.cli.version"
+ // CodingAgentHookSchemaVersion is the wire-format schema version.
+ // Bump when a breaking change is necessary; receivers read this to
+ // stay forward-compatible with the latest CLIs.
+ CodingAgentHookSchemaVersion = "coding_agent.hook.schema.version"
+)
+
+// Span names emitted by the CLI normalizer. Keep these as constants so
+// dashboard SQL can match against a small, stable set.
+const (
+ CodingAgentSpanSession = "coding_agent.session"
+ CodingAgentSpanToolCall = "coding_agent.tool.call"
+ CodingAgentSpanEditDecision = "coding_agent.edit.decision"
+ CodingAgentSpanSubagent = "coding_agent.subagent"
+ CodingAgentSpanLLMTurn = "coding_agent.llm.turn"
+ // CodingAgentSpanGitCommit is emitted when the agent's Bash /
+ // shell tool ran a `git commit` invocation. One span per detected
+ // commit, child of the session-root trace.
+ CodingAgentSpanGitCommit = "coding_agent.git.commit"
+ // CodingAgentSpanGitPullRequest is emitted when the agent's
+ // Bash / shell tool created a pull / merge request (`gh pr
+ // create`, `git push -u origin <branch>` that produced a PR URL,
+ // etc.).
+ CodingAgentSpanGitPullRequest = "coding_agent.git.pull_request"
+)
+
+// Git commit / pull-request attributes — attached to the matching
+// `coding_agent.git.commit` / `coding_agent.git.pull_request` span.
+// The body-bearing values (commit message, PR title) are stamped only
+// under `full` content capture; the SHA / URL / number are always
+// safe to stamp.
+const (
+ CodingAgentGitCommitSHA = "coding_agent.git.commit.sha"
+ CodingAgentGitCommitMessage = "coding_agent.git.commit.message"
+ CodingAgentGitPRURL = "coding_agent.git.pull_request.url"
+ CodingAgentGitPRNumber = "coding_agent.git.pull_request.number"
+ CodingAgentGitPRTitle = "coding_agent.git.pull_request.title"
+)
+
+// Event names — emitted as span events for high-cardinality moments
+// where a separate span would be overkill.
+const (
+ CodingAgentEventSessionStart = "coding_agent.session.start"
+ CodingAgentEventSessionEnd = "coding_agent.session.end"
+ CodingAgentEventEditDecision = "coding_agent.edit.decision"
+ CodingAgentEventLoopDetected = "coding_agent.loop.detected"
+ CodingAgentEventSubagentSpawned = "coding_agent.subagent.spawned"
+ CodingAgentEventSubagentDone = "coding_agent.subagent.completed"
+ CodingAgentEventMCPInvoked = "coding_agent.mcp.tool.invoked"
+)
+
+// Metric names — additions on top of gen_ai.* metrics.
+//
+// The `coding_agent.lines_of_code.count`, `coding_agent.code_edit_tool.decision`,
+// `coding_agent.commit.count`, and `coding_agent.pull_request.count`
+// counters mirror Claude Code's native exporter shape
+// (`claude_code.lines_of_code.count` …) under our canonical namespace.
+// They are emitted alongside the matching span so backends that consume
+// metrics (Prometheus / Mimir) see the same numbers traces backends do.
+const (
+ CodingAgentMetricSessionDuration = "coding_agent.session.duration"
+ CodingAgentMetricSessionCostUSD = "coding_agent.session.cost_usd"
+ CodingAgentMetricSessionToolCalls = "coding_agent.session.tool_call_count"
+ CodingAgentMetricSessionSubagents = "coding_agent.session.subagent_count"
+ CodingAgentMetricToolDuration = "coding_agent.tool.duration"
+ CodingAgentMetricEditDecisions = "coding_agent.edit.decision.count"
+ // CodingAgentMetricLinesOfCode is a counter of added / removed
+ // lines tagged with `type=added|removed`, `decision`, `vendor`, `user`.
+ CodingAgentMetricLinesOfCode = "coding_agent.lines_of_code.count"
+ // CodingAgentMetricEditDecisionCnt is a counter of edit
+ // decisions tagged with `decision`, `vendor`, `tool_name`,
+ // `language`, `user`. Renamed under our namespace from
+ // `claude_code.code_edit_tool.decision`.
+ CodingAgentMetricEditDecisionCnt = "coding_agent.code_edit_tool.decision"
+ // CodingAgentMetricCommit is a counter of agent-attributed
+ // git commits tagged with `vendor`, `user`.
+ CodingAgentMetricCommit = "coding_agent.commit.count"
+ // CodingAgentMetricPullRequest is a counter of agent-attributed
+ // pull / merge requests tagged with `vendor`, `user`.
+ CodingAgentMetricPullRequest = "coding_agent.pull_request.count"
+)
+
+// Schema version of the coding_agent.* wire format. Bump on breaking changes.
+const CodingAgentSchemaVersion = "1"
diff --git a/sdk/go/semconv/genai.go b/sdk/go/semconv/genai.go
index 1f30a1a4..bf8e81b3 100644
--- a/sdk/go/semconv/genai.go
+++ b/sdk/go/semconv/genai.go
@@ -19,10 +19,21 @@ const (
GenAIOperationTypeAudio = "audio"
)
-// System Identifiers
-const (
- // GenAISystem identifies the AI system being used
+// System / Provider Identifiers.
+//
+// OTel GenAI renamed the long-standing `gen_ai.system` attribute to
+// `gen_ai.provider.name` (see GenAI semconv 1.36+). The constant for
+// the legacy key is preserved so we can dual-stamp during the
+// transition window without breaking existing dashboards.
+const (
+ // GenAISystem is the legacy attribute name. Treat as deprecated;
+ // emit GenAIProviderName alongside it for new code paths.
GenAISystem = "gen_ai.system"
+ // GenAIProviderName is the OTel 1.36+ canonical attribute name
+ // for the AI provider (anthropic, openai, …). Stamp this on
+ // every span the CLI emits, and continue stamping
+ // GenAISystem until the downstream consumers are cut over.
+ GenAIProviderName = "gen_ai.provider.name"
// GenAISystemOpenAI represents OpenAI system
GenAISystemOpenAI = "openai"
@@ -84,18 +95,41 @@ const (
GenAITokenType = "gen_ai.token.type"
)
-// Token Details (OpenAI specific)
+// Token Details (OpenAI specific - legacy).
+//
+// OTel GenAI introduced first-class cache / reasoning token
+// attributes in 1.36+. The new shape lives below in
+// `GenAIUsageCache*` and `GenAIUsageReasoningTokens`; the
+// `*_details.*` constants here are kept only to interoperate with
+// older receivers still keying off the OpenAI-shaped names.
const (
// GenAIUsageCompletionTokensDetailsAudio tracks audio output tokens
GenAIUsageCompletionTokensDetailsAudio = "gen_ai.usage.completion_tokens_details.audio"
// GenAIUsageCompletionTokensDetailsReasoning tracks reasoning tokens
+ // (legacy; prefer GenAIUsageReasoningTokens)
GenAIUsageCompletionTokensDetailsReasoning = "gen_ai.usage.completion_tokens_details.reasoning"
// GenAIUsagePromptTokensDetailsCacheRead tracks cached tokens read
+ // (legacy; prefer GenAIUsageCacheReadInputTokens)
GenAIUsagePromptTokensDetailsCacheRead = "gen_ai.usage.prompt_tokens_details.cache_read"
// GenAIUsagePromptTokensDetailsCacheWrite tracks cached tokens written
+ // (legacy; prefer GenAIUsageCacheCreationInputTokens)
GenAIUsagePromptTokensDetailsCacheWrite = "gen_ai.usage.prompt_tokens_details.cache_write"
)
+// Token Details (OTel 1.36+ canonical names).
+const (
+ // GenAIUsageCacheReadInputTokens is the cumulative count of input
+ // tokens that hit the provider's prompt cache for the request.
+ GenAIUsageCacheReadInputTokens = "gen_ai.usage.cache.read_input_tokens"
+ // GenAIUsageCacheCreationInputTokens is the count of input tokens
+ // the provider stored into a fresh cache entry on this request.
+ GenAIUsageCacheCreationInputTokens = "gen_ai.usage.cache.creation_input_tokens"
+ // GenAIUsageReasoningTokens is the count of reasoning / thinking
+ // tokens the model spent on the response (Anthropic's "thinking"
+ // budget, OpenAI's o*-series reasoning).
+ GenAIUsageReasoningTokens = "gen_ai.usage.reasoning_tokens"
+)
+
// Message Attributes
const (
// GenAIPrompt is the legacy prompt attribute
diff --git a/src/client/prisma/seed.js b/src/client/prisma/seed.js
index 86fa9bc2..6a21c505 100644
--- a/src/client/prisma/seed.js
+++ b/src/client/prisma/seed.js
@@ -29,7 +29,11 @@ async function main() {
},
});
- // Link user to default organisation
+ // Link user to default organisation as the owner. The `role` column
+ // defaults to `member` at the schema level; the seed user is the
+ // org creator and must have elevated permissions or downstream
+ // privacy gates (e.g. coding-agents COHORT_K_FLOOR) silently
+ // suppress their own data. Existing rows are upgraded too.
await prisma.organisationUser.upsert({
where: {
organisationId_userId: {
@@ -37,10 +41,14 @@ async function main() {
userId: user.id,
},
},
- update: {},
+ update: {
+ role: "owner",
+ isCurrent: true,
+ },
create: {
organisationId: defaultOrg.id,
userId: user.id,
+ role: "owner",
isCurrent: true,
},
});
diff --git a/src/client/public/images/codex.svg b/src/client/public/images/codex.svg
new file mode 100644
index 00000000..036e99bc
--- /dev/null
+++ b/src/client/public/images/codex.svg
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1280" height="1280">
+<path d="M0 0 C1.66466285 0.69156157 3.3462088 1.34217717 5.02978516 1.98632812 C28.89052201 11.25643656 49.85183247 26.89008295 69.10791016 43.43554688 C70.02443359 44.21027344 70.94095703 44.985 71.88525391 45.78320312 C72.50948242 46.33049072 73.13371094 46.87777832 73.77685547 47.44165039 C76.34640411 49.07662837 77.41862149 49.01671524 80.39697266 48.59570312 C81.27659668 48.47710937 82.1562207 48.35851562 83.0625 48.23632812 C83.99400879 48.08679688 84.92551758 47.93726563 85.88525391 47.78320312 C86.82578613 47.63367188 87.76631836 47.48414063 88.73535156 47.33007812 C92.72941483 46.66740698 96.71481794 45.95970952 100.69970703 45.24414062 C122.85500405 41.40102114 146.67528561 41.05817267 168.88525391 44.78320312 C169.74376953 44.92322754 170.60228516 45.06325195 171.48681641 45.20751953 C217.68836069 53.04063346 260.2067991 74.14434049 293.88525391 106.78320312 C294.7220166 107.58129395 294.7220166 107.58129395 295.57568359 108.39550781 C304.17492941 116.61530538 311.83959518 125.19859522 318.88525391 134.78320312 C319.52978516 135.65589844 320.17431641 136.52859375 320.83837891 137.42773438 C349.5619902 177.47258885 364.14559629 223.32975054 364.07275391 272.47070312 C364.07184753 273.60262589 364.07184753 273.60262589 364.07092285 274.75741577 C364.03659403 290.54637004 362.41636149 305.3009048 359.11865234 320.74536133 C357.78428639 326.79235129 357.78428639 326.79235129 358.88525391 332.78320312 C360.06974149 334.59242095 360.06974149 334.59242095 361.69775391 336.22070312 C365.22448677 340.06206154 368.67031472 343.95676582 372.07275391 347.90820312 C372.58362549 348.49400146 373.09449707 349.0797998 373.62084961 349.68334961 C376.67724963 353.22593836 379.34344831 356.84366329 381.88525391 360.78320312 C382.59681641 361.79253906 383.30837891 362.801875 384.04150391 363.84179688 C405.38740681 394.35095276 417.87395183 429.87922404 421.88525391 466.78320312 C421.9795166 467.61948242 422.0737793 468.45576172 422.17089844 469.31738281 C424.306312 490.0755891 423.49408204 511.25725682 419.88525391 531.78320312 C419.75135254 532.5854834 419.61745117 533.38776367 419.47949219 534.21435547 C414.06961108 565.93265236 400.50308285 596.62592279 381.88525391 622.78320312 C381.24072266 623.70101562 380.59619141 624.61882813 379.93212891 625.56445312 C375.19406062 632.20521025 370.13177105 638.53870718 364.88525391 644.78320312 C364.27681641 645.51667969 363.66837891 646.25015625 363.04150391 647.00585938 C359.60202978 651.06287544 355.96066903 654.58144473 351.90087891 658.01367188 C349.88296167 659.78521549 348.0505758 661.65335412 346.19775391 663.59570312 C336.16251607 673.7087335 323.92125658 681.30223003 311.88525391 688.78320312 C310.77923828 689.48316406 309.67322266 690.183125 308.53369141 690.90429688 C294.34009019 699.48607279 270.86044221 712.78320312 253.88525391 712.78320312 C253.71002197 713.31397461 253.53479004 713.84474609 253.35424805 714.39160156 C242.04199143 748.50969316 227.46033167 777.5156433 203.88525391 804.78320312 C203.25619141 805.52570312 202.62712891 806.26820313 201.97900391 807.03320312 C195.52138997 814.58739301 188.69702649 821.76759032 180.57275391 827.53320312 C178.68292008 828.86891551 178.68292008 828.86891551 176.51025391 831.15820312 C175.97400391 831.69445313 175.43775391 832.23070312 174.88525391 832.78320312 C174.22525391 832.78320312 173.56525391 832.78320312 172.88525391 832.78320312 C172.88525391 833.44320312 172.88525391 834.10320313 172.88525391 834.78320312 C170.48172105 836.60168533 168.07684084 838.30065856 165.57275391 839.97070312 C164.47060547 840.71380737 164.47060547 840.71380737 163.34619141 841.47192383 C161.86866316 842.46475941 160.38870501 843.45398911 158.90625 844.43945312 C157.24348112 845.54501968 155.58863816 846.66249751 153.93603516 847.78320312 C135.69745856 859.84915272 114.79796074 867.74272367 93.88525391 873.78320312 C92.78310547 874.12996094 91.68095703 874.47671875 90.54541016 874.83398438 C71.54862111 880.46991606 51.91950036 882.16129936 32.19775391 882.15820312 C31.45756012 882.16001587 30.71736633 882.16182861 29.95474243 882.16369629 C15.67237074 882.15972527 1.60463209 880.7437753 -12.42724609 878.03320312 C-13.29478516 877.86618896 -14.16232422 877.6991748 -15.05615234 877.52709961 C-33.05913721 873.89951117 -50.40655344 867.9207132 -66.72802734 859.51757812 C-68.81164468 858.45053534 -70.91073378 857.41238155 -73.03271484 856.42382812 C-91.41633871 847.80254245 -107.53901135 834.67627231 -122.53662109 821.15039062 C-123.05740234 820.69921875 -123.57818359 820.24804688 -124.11474609 819.78320312 C-124.65615234 819.20828125 -125.19755859 818.63335938 -125.75537109 818.04101562 C-132.22676167 814.59103588 -143.0940536 818.89159108 -149.94677734 820.32226562 C-202.86465141 830.8900676 -264.2079329 817.94887866 -309.21240234 788.77148438 C-310.17017578 788.11535156 -311.12794922 787.45921875 -312.11474609 786.78320312 C-312.67661621 786.3995459 -313.23848633 786.01588867 -313.81738281 785.62060547 C-330.86045245 773.9136453 -348.56627148 760.37957277 -361.11474609 743.78320312 C-361.11474609 743.12320313 -361.11474609 742.46320312 -361.11474609 741.78320312 C-361.77474609 741.78320312 -362.43474609 741.78320312 -363.11474609 741.78320312 C-365.72647422 739.03486153 -367.86685787 735.82958363 -370.11474609 732.78320312 C-370.59975586 732.13399902 -371.08476562 731.48479492 -371.58447266 730.81591797 C-381.28587142 717.80870395 -389.81236786 704.81037206 -396.11474609 689.78320312 C-396.56205078 688.73648438 -397.00935547 687.68976562 -397.47021484 686.61132812 C-399.09369637 682.69408047 -400.62917927 678.75449549 -402.11474609 674.78320312 C-402.43378906 673.93097168 -402.75283203 673.07874023 -403.08154297 672.20068359 C-412.21512175 647.38136659 -416.33933659 622.39903033 -416.36474609 596.03320312 C-416.36608551 595.21261414 -416.36742493 594.39202515 -416.36880493 593.54656982 C-416.36268913 576.24223648 -414.51106656 559.73218079 -410.56787109 542.87695312 C-410.06710215 539.45790999 -410.15700228 537.10338167 -411.11474609 533.78320312 C-412.77021089 531.63565877 -412.77021089 531.63565877 -414.98974609 529.78320312 C-421.10716883 523.9954038 -426.06479062 517.49418548 -431.11474609 510.78320312 C-431.75911621 509.93798096 -431.75911621 509.93798096 -432.41650391 509.07568359 C-468.89915534 461.00789458 -480.7003644 398.72256462 -472.9465332 339.7512207 C-467.10193894 297.20353398 -448.44994177 255.77107051 -419.22412109 224.07617188 C-417.34686136 222.03552102 -415.5375841 219.9560225 -413.73974609 217.84570312 C-405.93900936 208.93057542 -397.42668915 201.08969342 -388.11474609 193.78320312 C-387.16470703 193.00460937 -386.21466797 192.22601563 -385.23583984 191.42382812 C-366.13690416 176.10565238 -344.46248843 165.209489 -321.33203125 157.53076172 C-317.52603518 156.24756859 -313.77106044 154.82872226 -310.01318359 153.41210938 C-308.11474609 152.78320312 -308.11474609 152.78320312 -306.11474609 152.78320312 C-305.90849609 151.62820313 -305.70224609 150.47320312 -305.48974609 149.28320312 C-299.50847288 122.55569556 -284.46215062 97.35357805 -268.86474609 75.22070312 C-268.26460693 74.36303345 -268.26460693 74.36303345 -267.65234375 73.48803711 C-265.08448602 69.90016627 -262.27581254 66.8510083 -259.11474609 63.78320312 C-257.43954566 61.95766419 -255.77334257 60.12384068 -254.11474609 58.28320312 C-239.62070747 42.4099611 -224.29552562 29.28328569 -206.11474609 17.78320312 C-205.47230957 17.37215332 -204.82987305 16.96110352 -204.16796875 16.53759766 C-144.63731206 -21.22757742 -64.783728 -27.22187757 0 0 Z " fill="#788CFE" transform="translate(666.11474609375,207.216796875)"/>
+<path d="M0 0 C9.8902204 6.35799883 15.28332103 19.50733612 20.77001953 29.52807617 C24.26506602 35.90431768 27.91067554 42.18392156 31.59375 48.453125 C37.08586725 57.81524992 42.43830111 67.24717404 47.72460938 76.72680664 C54.99465953 89.76117244 62.36547921 102.73498453 69.96875 115.578125 C73.52898992 121.59606036 76.99996087 127.65916888 80.40625 133.765625 C80.83631348 134.53350342 81.26637695 135.30138184 81.70947266 136.0925293 C82.10569824 136.80707275 82.50192383 137.52161621 82.91015625 138.2578125 C83.4352478 139.20309814 83.4352478 139.20309814 83.97094727 140.16748047 C87.59701811 147.32630788 87.13467269 157.70608693 84.80859375 165.24609375 C83.01978568 168.9289339 80.98035162 172.40430117 78.84375 175.890625 C77.76112064 177.71632245 76.68056473 179.5432503 75.6015625 181.37109375 C73.06937223 185.63760453 70.51195895 189.88777448 67.9375 194.12890625 C63.88120249 200.81424964 59.88632952 207.53469446 55.90625 214.265625 C55.2452832 215.38243652 54.58431641 216.49924805 53.90332031 217.64990234 C52.55967447 219.92027917 51.21625059 222.19078736 49.87304688 224.46142578 C47.8283724 227.91661078 45.78183073 231.37068153 43.734375 234.82421875 C43.39616226 235.39474472 43.05794952 235.96527069 42.70948792 236.55308533 C41.0219555 239.39969528 39.33420576 242.24617615 37.64624023 245.0925293 C34.5227741 250.36152333 31.4043008 255.63329122 28.30078125 260.9140625 C23.36702717 269.30557608 18.41794597 277.68375711 13.28125 285.953125 C12.88760254 286.59016357 12.49395508 287.22720215 12.08837891 287.88354492 C7.25783943 295.58910561 1.78589918 301.97641178 -6.88671875 305.3828125 C-16.16498566 307.45884468 -25.91743908 306.72286018 -34.15625 301.890625 C-41.02522434 297.32930216 -45.58834312 290.69439396 -48.15625 282.890625 C-49.86507762 269.82229575 -46.85509689 260.97602645 -40.15625 249.890625 C-39.46242147 248.70377916 -38.76968638 247.51629331 -38.078125 246.328125 C-36.63247862 243.87123829 -35.15912485 241.43342227 -33.66796875 239.00390625 C-30.81588555 234.35349878 -28.04952891 229.65374928 -25.28125 224.953125 C-19.75678995 215.58870422 -14.20956784 206.23794586 -8.65625 196.890625 C-2.44964804 186.4433326 3.74824293 175.99106095 9.92382812 165.52539062 C10.40271484 164.71392578 10.88160156 163.90246094 11.375 163.06640625 C11.80425781 162.3285791 12.23351562 161.59075195 12.67578125 160.83056641 C13.6486498 159.2146773 14.71968586 157.65840571 15.8125 156.12109375 C17.1396334 153.91507869 17.1396334 153.91507869 16.09472656 151.59814453 C14.78911632 148.77237998 13.37079094 146.06126742 11.859375 143.33984375 C10.96206665 141.72215088 10.96206665 141.72215088 10.04663086 140.07177734 C9.39590348 138.9070964 8.74493697 137.74254904 8.09375 136.578125 C7.76150421 135.98171204 7.42925842 135.38529907 7.08694458 134.77081299 C1.85626873 125.38254857 -3.50818058 116.07850007 -8.95410156 106.81323242 C-13.71511803 98.69689026 -18.3166843 90.49800222 -22.88891602 82.27416992 C-27.58872159 73.84412912 -32.43081922 65.50304861 -37.36328125 57.20703125 C-52.24442365 31.99077563 -52.24442365 31.99077563 -48.54296875 16.2890625 C-45.59935769 8.94948603 -40.09880768 2.10875828 -33.03125 -1.546875 C-31.74921819 -2.09099315 -30.45803317 -2.61436922 -29.15625 -3.109375 C-28.2075 -3.521875 -27.25875 -3.934375 -26.28125 -4.359375 C-16.65662052 -6.66928607 -8.65259171 -4.45169573 0 0 Z " fill="#FDFEFE" transform="translate(454.15625,491.109375)"/>
+<path d="M0 0 C1.86376254 -0.00870589 3.72751793 -0.01907606 5.59126282 -0.03097534 C10.63065322 -0.05765292 15.66974269 -0.05892427 20.70918989 -0.05384874 C24.92618691 -0.05170236 29.14312391 -0.06149378 33.36010802 -0.07105958 C43.31384857 -0.09321445 53.26743815 -0.09414469 63.22119141 -0.08203125 C73.46763123 -0.0699528 83.71352171 -0.09457846 93.95986784 -0.13717139 C102.77805388 -0.17247097 111.59606559 -0.18439554 120.41431963 -0.1778959 C125.67184631 -0.17428064 130.92898105 -0.17943735 136.18644333 -0.20732498 C141.13289674 -0.23258354 146.07849739 -0.22849952 151.02493858 -0.2025032 C152.83242399 -0.19779448 154.63997039 -0.20315895 156.44738579 -0.21974945 C169.03528462 -0.32689743 178.53804648 1.1887383 188.45947266 9.73681641 C195.37655022 17.51852866 197.31331795 25.6845328 196.94775391 35.95166016 C196.11253784 43.0088528 193.67755562 49.52940668 188.52197266 54.54931641 C180.96286844 60.40152612 175.33534564 63.85774492 165.61627197 63.81674194 C164.43107519 63.82353861 164.43107519 63.82353861 163.22193503 63.83047259 C160.57742178 63.84312091 157.93311436 63.84149594 155.28857422 63.83984375 C153.39113093 63.8458288 151.49369009 63.85263429 149.59625244 63.86019897 C144.44320299 63.87787026 139.29021996 63.88255488 134.13714314 63.88383055 C130.91632967 63.88525226 127.69553309 63.88952228 124.47472382 63.89482498 C113.23427763 63.91333018 101.99387888 63.92149513 90.75341797 63.91992188 C80.28277627 63.91872089 69.81234085 63.93981362 59.34175134 63.9714092 C50.34709462 63.99758188 41.35250523 64.00828873 32.35781074 64.00701106 C26.98804204 64.00650164 21.61845659 64.01217332 16.24872589 64.03336716 C11.1958206 64.0527657 6.14327301 64.05286284 1.09035492 64.03833389 C-0.76031518 64.03624659 -2.61100776 64.04094197 -4.4616394 64.05305481 C-22.37855356 64.16269442 -22.37855356 64.16269442 -29.47802734 59.54931641 C-30.27595703 59.05431641 -31.07388672 58.55931641 -31.89599609 58.04931641 C-38.65689025 52.31822732 -43.13674427 45.28988264 -44.02099609 36.34619141 C-44.56159568 26.13033255 -42.8235066 18.54661756 -35.97802734 10.67431641 C-35.15302734 9.97306641 -34.32802734 9.27181641 -33.47802734 8.54931641 C-32.75615234 7.86869141 -32.03427734 7.18806641 -31.29052734 6.48681641 C-21.4981295 -0.25905766 -11.44299592 -0.03539535 0 0 Z " fill="#FEFEFE" transform="translate(681.47802734375,734.45068359375)"/>
+<path d="M0 0 C3.18844653 4.7826698 1.52653597 9.32644222 0.46875 14.78955078 C-5.79471184 44.32568803 -18.60220563 72.41600088 -36 97 C-36.68964844 97.98484375 -37.37929687 98.9696875 -38.08984375 99.984375 C-42.77860533 106.55792589 -47.80718586 112.8194223 -53 119 C-53.6084375 119.73347656 -54.216875 120.46695313 -54.84375 121.22265625 C-58.28322412 125.27967232 -61.92458488 128.7982416 -65.984375 132.23046875 C-68.00229224 134.00201237 -69.8346781 135.870151 -71.6875 137.8125 C-81.72273783 147.92553037 -93.96399732 155.51902691 -106 163 C-107.10601563 163.69996094 -108.21203125 164.39992188 -109.3515625 165.12109375 C-123.54516372 173.70286967 -147.0248117 187 -164 187 C-164.17523193 187.53077148 -164.35046387 188.06154297 -164.53100586 188.60839844 C-175.84326248 222.72649003 -190.42492223 251.73244017 -214 279 C-214.6290625 279.7425 -215.258125 280.485 -215.90625 281.25 C-222.36386393 288.80418989 -229.18822742 295.9843872 -237.3125 301.75 C-239.20233383 303.08571238 -239.20233383 303.08571238 -241.375 305.375 C-241.91125 305.91125 -242.4475 306.4475 -243 307 C-243.66 307 -244.32 307 -245 307 C-245 307.66 -245 308.32 -245 309 C-247.40353286 310.8184822 -249.80841306 312.51745544 -252.3125 314.1875 C-253.04726563 314.68290283 -253.78203125 315.17830566 -254.5390625 315.6887207 C-256.01659074 316.68155629 -257.49654889 317.67078598 -258.97900391 318.65625 C-260.64177278 319.76181655 -262.29661575 320.87929439 -263.94921875 322 C-282.18779534 334.0659496 -303.08729317 341.95952055 -324 348 C-325.10214844 348.34675781 -326.20429687 348.69351562 -327.33984375 349.05078125 C-346.3366328 354.68671294 -365.96575355 356.37809624 -385.6875 356.375 C-386.42769379 356.37681274 -387.16788757 356.37862549 -387.93051147 356.38049316 C-402.21288317 356.37652214 -416.28062182 354.96057218 -430.3125 352.25 C-431.18003906 352.08298584 -432.04757812 351.91597168 -432.94140625 351.74389648 C-450.94439112 348.11630804 -468.29180735 342.13751008 -484.61328125 333.734375 C-486.69689858 332.66733221 -488.79598769 331.62917843 -490.91796875 330.640625 C-509.30159262 322.01933932 -525.42426526 308.89306918 -540.421875 295.3671875 C-540.94265625 294.91601562 -541.4634375 294.46484375 -542 294 C-542.54140625 293.42507813 -543.0828125 292.85015625 -543.640625 292.2578125 C-550.11201557 288.80783276 -560.97930751 293.10838795 -567.83203125 294.5390625 C-620.74990532 305.10686448 -682.09318681 292.16567553 -727.09765625 262.98828125 C-728.05542969 262.33214844 -729.01320313 261.67601562 -730 261 C-730.84280518 260.42451416 -730.84280518 260.42451416 -731.70263672 259.83740234 C-748.74570636 248.13044217 -766.45152539 234.59636965 -779 218 C-779 217.34 -779 216.68 -779 216 C-779.66 216 -780.32 216 -781 216 C-783.61172812 213.25165841 -785.75211177 210.04638051 -788 207 C-788.72751465 206.02619385 -788.72751465 206.02619385 -789.46972656 205.03271484 C-799.17112532 192.02550082 -807.69762177 179.02716894 -814 164 C-814.44730469 162.95328125 -814.89460938 161.9065625 -815.35546875 160.828125 C-816.97895028 156.91087734 -818.51443317 152.97129236 -820 149 C-820.31904297 148.14776855 -820.63808594 147.29553711 -820.96679688 146.41748047 C-826.79541378 130.57896917 -830.56844063 114.6986777 -833 98 C-833.1134375 97.22245361 -833.226875 96.44490723 -833.34375 95.64379883 C-834.30367229 87.77767504 -834.1506506 79.84323055 -834.13037109 71.93188477 C-834.12500442 69.43955423 -834.1303464 66.94740325 -834.13671875 64.45507812 C-834.13605797 62.84374961 -834.13477681 61.2324212 -834.1328125 59.62109375 C-834.13483673 58.88958603 -834.13686096 58.15807831 -834.13894653 57.40440369 C-834.11579654 52.2061199 -833.64042364 47.15932151 -833 42 C-832.34 42 -831.68 42 -831 42 C-830.67 38.04 -830.34 34.08 -830 30 C-829.67 30 -829.34 30 -829 30 C-828.97193841 31.43737706 -828.95315002 32.87493423 -828.9375 34.3125 C-828.92589844 35.11300781 -828.91429687 35.91351562 -828.90234375 36.73828125 C-828.98242295 39.41292668 -829.20437283 41.96950241 -829.4921875 44.625 C-830.22956194 52.41831904 -830.186027 60.21944927 -830.18530273 68.04077148 C-830.18748109 70.66471796 -830.20567244 73.2882373 -830.22460938 75.91210938 C-830.27195153 89.79431627 -829.25772437 103.27861943 -825.9375 116.8125 C-825.72907471 117.67012939 -825.52064941 118.52775879 -825.3059082 119.41137695 C-819.13601815 143.79466132 -810.65506661 168.41707111 -796.13671875 189.15234375 C-795 191 -795 191 -795 193 C-794.34 193 -793.68 193 -793 193 C-791.98432193 194.65715896 -790.98994188 196.32733959 -790 198 C-788.17375337 200.36433715 -786.30863654 202.69225933 -784.42578125 205.01171875 C-783 207 -783 207 -783 209 C-782.34 209 -781.68 209 -781 209 C-779.80859375 210.3984375 -779.80859375 210.3984375 -778.4375 212.375 C-773.23279038 219.53464933 -767.39638025 226.09647224 -760.54296875 231.7109375 C-758.21487104 233.65593052 -756.14429198 235.85570802 -754 238 C-749.20434787 242.4886457 -744.28213661 246.28888537 -738.6875 249.73828125 C-738.130625 250.15464844 -737.57375 250.57101562 -737 251 C-737 251.66 -737 252.32 -737 253 C-736.21625 253.309375 -735.4325 253.61875 -734.625 253.9375 C-732 255 -732 255 -730 256 C-730 256.66 -730 257.32 -730 258 C-729.14664063 258.24621094 -728.29328125 258.49242187 -727.4140625 258.74609375 C-723.73109903 260.09876111 -720.65254879 261.95736747 -717.375 264.0625 C-711.28777662 267.84369787 -705.03637567 271.00451092 -698.5 273.9375 C-697.66388184 274.31463135 -696.82776367 274.6917627 -695.96630859 275.08032227 C-692.33795645 276.67768483 -688.80696452 278.12147265 -684.96875 279.12890625 C-683.9890625 279.41636719 -683.009375 279.70382812 -682 280 C-681.67 280.66 -681.34 281.32 -681 282 C-679.00832659 282.37993174 -677.00574636 282.70319591 -675 283 C-672.63782431 283.63770772 -670.2836373 284.30560463 -667.9375 285 C-663.96816051 286.17226964 -660.06479677 287.2285314 -656 288 C-655.04867187 288.22558594 -654.09734375 288.45117188 -653.1171875 288.68359375 C-636.52887592 292.54087584 -620.27246892 293.18209848 -603.3125 293.1875 C-602.47017822 293.18849701 -601.62785645 293.18949402 -600.76000977 293.19052124 C-598.31518037 293.19019401 -595.87057286 293.18107865 -593.42578125 293.16796875 C-592.69611649 293.16676025 -591.96645172 293.16555176 -591.2146759 293.16430664 C-586.39963804 293.12104939 -581.76961123 292.66792874 -577 292 C-575.87078125 291.85820313 -574.7415625 291.71640625 -573.578125 291.5703125 C-567.78364569 290.79499485 -562.20373738 289.86260161 -556.5625 288.3125 C-548.58848315 286.3005618 -548.58848315 286.3005618 -544 288 C-541.40225807 290.04013464 -539.02292407 292.22001907 -536.63671875 294.50390625 C-529.84376128 300.96714119 -529.84376128 300.96714119 -522 306 C-522 306.66 -522 307.32 -522 308 C-521.29746094 308.24492188 -520.59492187 308.48984375 -519.87109375 308.7421875 C-516.58185869 310.18318572 -513.97131232 312.01950407 -511.0625 314.125 C-485.3417339 332.32993394 -455.48736021 344.59438697 -424.37109375 349.45703125 C-421 350 -421 350 -418.92578125 350.5390625 C-408.09867975 353.13053913 -395.95440241 352.10566394 -384.875 352.125 C-384.19739624 352.1275882 -383.51979248 352.13017639 -382.82165527 352.13284302 C-368.44612104 352.17602256 -354.66845087 351.28340486 -340.5625 348.4375 C-339.92024475 348.30916779 -339.2779895 348.18083557 -338.61627197 348.0486145 C-325.98673557 345.49641597 -313.99708124 341.6861984 -302 337 C-300.85015625 336.56945313 -299.7003125 336.13890625 -298.515625 335.6953125 C-290.29043693 332.47192799 -282.57187152 328.19184043 -274.82421875 323.97387695 C-273.51474467 323.27480145 -272.18011705 322.62209674 -270.83203125 322.00073242 C-268.82853167 321.13253528 -268.82853167 321.13253528 -268 319 C-265.4375 318.375 -265.4375 318.375 -263 318 C-263 317.34 -263 316.68 -263 316 C-262.44022461 315.70939697 -261.88044922 315.41879395 -261.30371094 315.11938477 C-255.81923175 312.18605437 -251.01951595 308.91702526 -246.25 304.9375 C-245.56752197 304.37530762 -244.88504395 303.81311523 -244.18188477 303.23388672 C-237.55978984 297.72894791 -231.23162769 291.93993448 -225 286 C-224.02353516 285.1028125 -224.02353516 285.1028125 -223.02734375 284.1875 C-216.84227373 278.33873402 -209.81429509 270.62859017 -206 263 C-205.34 263 -204.68 263 -204 263 C-203.71785645 262.4131543 -203.43571289 261.82630859 -203.14501953 261.22167969 C-202.09644607 259.18713416 -200.96228316 257.34571674 -199.6796875 255.453125 C-186.79247988 236.17552825 -176.8660027 215.0960732 -169.97265625 192.93359375 C-169.15375304 190.46372906 -168.24220762 188.27830904 -167 186 C-166.34 186 -165.68 186 -165 186 C-165 185.34 -165 184.68 -165 184 C-164.4016333 183.81937012 -163.8032666 183.63874023 -163.18676758 183.45263672 C-151.72921588 179.96904806 -140.74717664 176.33108536 -130 171 C-128.36005346 170.2469738 -126.71793001 169.49867899 -125.07421875 168.75390625 C-110.39807204 162.04868932 -97.54706448 154.17142543 -85 144 C-84.13375 143.31808594 -83.2675 142.63617187 -82.375 141.93359375 C-77.41668718 138.0583073 -77.41668718 138.0583073 -72.83203125 133.76171875 C-71 132 -71 132 -69 132 C-69 131.34 -69 130.68 -69 130 C-67.59755268 128.8369949 -66.19157175 127.67802702 -64.76953125 126.5390625 C-62.20238209 124.3062661 -60.06836383 121.77119882 -57.8671875 119.18359375 C-55.24616426 116.11842221 -52.51771766 113.15238313 -49.796875 110.17578125 C-47.89634524 107.99499959 -47.89634524 107.99499959 -46.390625 105.23046875 C-45.93171875 104.49441406 -45.4728125 103.75835938 -45 103 C-44.34 103 -43.68 103 -43 103 C-43 102.01 -43 101.02 -43 100 C-42.34 100 -41.68 100 -41 100 C-40.731875 99.2575 -40.46375 98.515 -40.1875 97.75 C-39 95 -39 95 -37.4375 92.9375 C-35.88261296 91.11877107 -35.88261296 91.11877107 -35.5625 89 C-35 87 -35 87 -33.23046875 85.359375 C-30.34088695 82.3027946 -28.65114141 78.97482891 -26.75 75.25 C-26.20472656 74.20392578 -26.20472656 74.20392578 -25.6484375 73.13671875 C-24.75893803 71.42794346 -23.87854133 69.71443502 -23 68 C-22.34 68 -21.68 68 -21 68 C-20.88527344 67.31164062 -20.77054688 66.62328125 -20.65234375 65.9140625 C-19.90740228 62.5863599 -18.79404411 59.55435719 -17.5625 56.375 C-17.13066406 55.24835937 -16.69882813 54.12171875 -16.25390625 52.9609375 C-15 50 -15 50 -13 47 C-12.29774646 45.01221621 -11.63755232 43.00947045 -11 41 C-10.54793983 39.71354858 -10.0919684 38.4284672 -9.6328125 37.14453125 C-5.80470915 26.22767528 -3.20773332 15.34435276 -1 4 C-0.67425799 2.66479177 -0.34299341 1.33088107 0 0 Z " fill="#1F2AF0" transform="translate(1084,733)"/>
+<path d="M0 0 C3.18844653 4.7826698 1.52653597 9.32644222 0.46875 14.78955078 C-5.79471184 44.32568803 -18.60220563 72.41600088 -36 97 C-36.68964844 97.98484375 -37.37929687 98.9696875 -38.08984375 99.984375 C-42.77860533 106.55792589 -47.80718586 112.8194223 -53 119 C-53.6084375 119.73347656 -54.216875 120.46695313 -54.84375 121.22265625 C-58.28322412 125.27967232 -61.92458488 128.7982416 -65.984375 132.23046875 C-68.00229224 134.00201237 -69.8346781 135.870151 -71.6875 137.8125 C-81.72273783 147.92553037 -93.96399732 155.51902691 -106 163 C-107.10601563 163.69996094 -108.21203125 164.39992188 -109.3515625 165.12109375 C-123.54516372 173.70286967 -147.0248117 187 -164 187 C-164.17233154 187.52424561 -164.34466309 188.04849121 -164.5222168 188.58862305 C-174.15543006 217.71088579 -174.15543006 217.71088579 -181 230 C-181.99 230 -182.98 230 -184 230 C-182.6710358 225.8877262 -181.1873666 221.88902778 -179.5390625 217.89453125 C-178.83136719 216.17073242 -178.83136719 216.17073242 -178.109375 214.41210938 C-177.12781067 212.03181588 -176.14604323 209.65160612 -175.1640625 207.27148438 C-172.27585308 200.23539812 -169.52938136 193.17326717 -167 186 C-166.34 186 -165.68 186 -165 186 C-165 185.34 -165 184.68 -165 184 C-164.10244995 183.72905518 -164.10244995 183.72905518 -163.18676758 183.45263672 C-151.72921588 179.96904806 -140.74717664 176.33108536 -130 171 C-128.36005346 170.2469738 -126.71793001 169.49867899 -125.07421875 168.75390625 C-110.39807204 162.04868932 -97.54706448 154.17142543 -85 144 C-84.13375 143.31808594 -83.2675 142.63617187 -82.375 141.93359375 C-77.41668718 138.0583073 -77.41668718 138.0583073 -72.83203125 133.76171875 C-71 132 -71 132 -69 132 C-69 131.34 -69 130.68 -69 130 C-67.59755268 128.8369949 -66.19157175 127.67802702 -64.76953125 126.5390625 C-62.20238209 124.3062661 -60.06836383 121.77119882 -57.8671875 119.18359375 C-55.24616426 116.11842221 -52.51771766 113.15238313 -49.796875 110.17578125 C-47.89634524 107.99499959 -47.89634524 107.99499959 -46.390625 105.23046875 C-45.93171875 104.49441406 -45.4728125 103.75835938 -45 103 C-44.34 103 -43.68 103 -43 103 C-43 102.01 -43 101.02 -43 100 C-42.34 100 -41.68 100 -41 100 C-40.731875 99.2575 -40.46375 98.515 -40.1875 97.75 C-39 95 -39 95 -37.4375 92.9375 C-35.88261296 91.11877107 -35.88261296 91.11877107 -35.5625 89 C-35 87 -35 87 -33.23046875 85.359375 C-30.34088695 82.3027946 -28.65114141 78.97482891 -26.75 75.25 C-26.38648438 74.55261719 -26.02296875 73.85523438 -25.6484375 73.13671875 C-24.75893803 71.42794346 -23.87854133 69.71443502 -23 68 C-22.34 68 -21.68 68 -21 68 C-20.88527344 67.31164062 -20.77054688 66.62328125 -20.65234375 65.9140625 C-19.90740228 62.5863599 -18.79404411 59.55435719 -17.5625 56.375 C-17.13066406 55.24835937 -16.69882813 54.12171875 -16.25390625 52.9609375 C-15 50 -15 50 -13 47 C-12.29774646 45.01221621 -11.63755232 43.00947045 -11 41 C-10.54793983 39.71354858 -10.0919684 38.4284672 -9.6328125 37.14453125 C-5.80470915 26.22767528 -3.20773332 15.34435276 -1 4 C-0.67425799 2.66479177 -0.34299341 1.33088107 0 0 Z " fill="#384AF2" transform="translate(1084,733)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.02806159 1.43737706 1.04684998 2.87493423 1.0625 4.3125 C1.07410156 5.11300781 1.08570313 5.91351562 1.09765625 6.73828125 C1.01757705 9.41292668 0.79562717 11.96950241 0.5078125 14.625 C-0.22956194 22.41831904 -0.186027 30.21944927 -0.18530273 38.04077148 C-0.18748109 40.66471796 -0.20567244 43.2882373 -0.22460938 45.91210938 C-0.27195153 59.79431627 0.74227563 73.27861943 4.0625 86.8125 C4.27092529 87.67012939 4.47935059 88.52775879 4.6940918 89.41137695 C10.86398185 113.79466132 19.34493339 138.41707111 33.86328125 159.15234375 C35 161 35 161 35 163 C35.66 163 36.32 163 37 163 C38.01567807 164.65715896 39.01005812 166.32733959 40 168 C41.82624663 170.36433715 43.69136346 172.69225933 45.57421875 175.01171875 C47 177 47 177 47 179 C47.66 179 48.32 179 49 179 C50.19140625 180.3984375 50.19140625 180.3984375 51.5625 182.375 C56.76720962 189.53464933 62.60361975 196.09647224 69.45703125 201.7109375 C71.78512896 203.65593052 73.85570802 205.85570802 76 208 C80.79565213 212.4886457 85.71786339 216.28888537 91.3125 219.73828125 C91.869375 220.15464844 92.42625 220.57101562 93 221 C93 221.66 93 222.32 93 223 C93.78375 223.309375 94.5675 223.61875 95.375 223.9375 C98 225 98 225 100 226 C100 226.66 100 227.32 100 228 C100.84691406 228.24363281 101.69382812 228.48726562 102.56640625 228.73828125 C106.34838812 230.12801975 109.55731545 232.04145809 112.9375 234.1875 C120.35154479 238.7795512 128.02935661 242.48387221 136 246 C136 246.99 136 247.98 136 249 C129.10117528 246.96852167 122.90104767 244.12568398 116.5625 240.75 C115.63236084 240.25765869 114.70222168 239.76531738 113.74389648 239.25805664 C107.48333511 235.90003406 101.66191534 232.29524612 96 228 C94.8868954 227.20701951 93.77075754 226.41828718 92.65234375 225.6328125 C83.61754779 219.28482699 74.764408 212.8944057 67 205 C66.1028125 204.11441406 65.205625 203.22882813 64.28125 202.31640625 C54.28690427 192.42031954 54.28690427 192.42031954 51 188 C51 187.34 51 186.68 51 186 C50.34 186 49.68 186 49 186 C46.38827188 183.25165841 44.24788823 180.04638051 42 177 C41.27248535 176.02619385 41.27248535 176.02619385 40.53027344 175.03271484 C30.82887468 162.02550082 22.30237823 149.02716894 16 134 C15.55269531 132.95328125 15.10539062 131.9065625 14.64453125 130.828125 C13.02104972 126.91087734 11.48556683 122.97129236 10 119 C9.68095703 118.14776855 9.36191406 117.29553711 9.03320312 116.41748047 C3.20458622 100.57896917 -0.56844063 84.6986777 -3 68 C-3.1134375 67.22245361 -3.226875 66.44490723 -3.34375 65.64379883 C-4.30367229 57.77767504 -4.1506506 49.84323055 -4.13037109 41.93188477 C-4.12500442 39.43955423 -4.1303464 36.94740325 -4.13671875 34.45507812 C-4.13605797 32.84374961 -4.13477681 31.2324212 -4.1328125 29.62109375 C-4.13483673 28.88958603 -4.13686096 28.15807831 -4.13894653 27.40440369 C-4.11579654 22.2061199 -3.64042364 17.15932151 -3 12 C-2.34 12 -1.68 12 -1 12 C-0.67 8.04 -0.34 4.08 0 0 Z " fill="#2C3DF1" transform="translate(254,763)"/>
+<path d="M0 0 C1.66466285 0.69156157 3.3462088 1.34217717 5.02978516 1.98632812 C28.89052201 11.25643656 49.85183247 26.89008295 69.10791016 43.43554688 C70.02443359 44.21027344 70.94095703 44.985 71.88525391 45.78320312 C72.57490234 46.38648438 73.26455078 46.98976562 73.97509766 47.61132812 C76.39970179 49.09881533 77.59260634 48.9913282 80.38525391 48.59570312 C81.24892578 48.4796875 82.11259766 48.36367187 83.00244141 48.24414062 C83.95376953 48.09203125 84.90509766 47.93992187 85.88525391 47.78320312 C86.98095703 47.61046875 88.07666016 47.43773437 89.20556641 47.25976562 C92.10262811 46.78719528 94.99485246 46.29473465 97.88525391 45.78320312 C98.21525391 46.77320313 98.54525391 47.76320312 98.88525391 48.78320312 C95.84751616 49.4888902 92.80466018 50.16941639 89.76025391 50.84570312 C88.90431641 51.04486328 88.04837891 51.24402344 87.16650391 51.44921875 C78.54209072 53.33995549 78.54209072 53.33995549 73.88525391 51.78320312 C71.18212891 49.71679688 71.18212891 49.71679688 68.63525391 47.22070312 C65.74179116 43.91534186 65.74179116 43.91534186 61.88525391 42.78320312 C61.88525391 41.79320312 61.88525391 40.80320313 61.88525391 39.78320312 C61.33224609 39.53441406 60.77923828 39.285625 60.20947266 39.02929688 C57.45705315 37.55362995 55.16119991 35.76712152 52.69775391 33.84570312 C31.46802329 17.67872746 6.82945183 3.60863892 -19.11474609 -3.21679688 C-20.44886803 -3.6060311 -21.78211784 -3.99826031 -23.11474609 -4.39257812 C-47.26354553 -11.45904083 -70.53696198 -12.38787962 -95.56176758 -12.12084961 C-98.57552682 -12.09083727 -101.58916752 -12.07296353 -104.60302734 -12.05664062 C-105.99343987 -12.03645119 -105.99343987 -12.03645119 -107.41194153 -12.01585388 C-108.26430893 -12.01247513 -109.11667633 -12.00909637 -109.99487305 -12.00561523 C-111.11947685 -11.99442909 -111.11947685 -11.99442909 -112.26679993 -11.98301697 C-114.11474609 -12.21679688 -114.11474609 -12.21679688 -116.11474609 -14.21679688 C-81.76290524 -25.66741049 -31.8475869 -13.38223561 0 0 Z " fill="#A199F7" transform="translate(666.11474609375,207.216796875)"/>
+<path d="M0 0 C1.32 0.33 2.64 0.66 4 1 C-3.40373121 15.20553305 -11.83814716 28.61338478 -22 41 C-22.46664062 41.56960449 -22.93328125 42.13920898 -23.4140625 42.72607422 C-32.08680084 53.23365325 -41.16560938 63.954307 -52.3828125 71.8203125 C-54.21634467 73.09399634 -54.21634467 73.09399634 -56.375 75.375 C-56.91125 75.91125 -57.4475 76.4475 -58 77 C-58.66 77 -59.32 77 -60 77 C-60 77.66 -60 78.32 -60 79 C-61.34179688 80.1574707 -61.34179688 80.1574707 -63.21875 81.42578125 C-63.90453125 81.89306641 -64.5903125 82.36035156 -65.296875 82.84179688 C-66.02390625 83.32712891 -66.7509375 83.81246094 -67.5 84.3125 C-68.19609375 84.78623047 -68.8921875 85.25996094 -69.609375 85.74804688 C-71.72870922 87.18252217 -73.861241 88.59467575 -76 90 C-76.72380859 90.48154541 -77.44761719 90.96309082 -78.19335938 91.45922852 C-79.24233398 92.14069946 -79.24233398 92.14069946 -80.3125 92.8359375 C-80.93769531 93.24505371 -81.56289063 93.65416992 -82.20703125 94.07568359 C-84.83634591 95.43115545 -87.1142443 95.36071946 -90 95 C-87.94766315 92.7522025 -86.99332739 91.9977758 -84 91 C-83.505 90.01 -83.505 90.01 -83 89 C-80.4375 88.375 -80.4375 88.375 -78 88 C-78 87.34 -78 86.68 -78 86 C-77.44022461 85.70939697 -76.88044922 85.41879395 -76.30371094 85.11938477 C-70.81923175 82.18605437 -66.01951595 78.91702526 -61.25 74.9375 C-60.22628296 74.09421143 -60.22628296 74.09421143 -59.18188477 73.23388672 C-52.55978984 67.72894791 -46.23162769 61.93993448 -40 56 C-39.34902344 55.401875 -38.69804688 54.80375 -38.02734375 54.1875 C-31.84227373 48.33873402 -24.81429509 40.62859017 -21 33 C-20.34 33 -19.68 33 -19 33 C-18.71930664 32.41605469 -18.43861328 31.83210937 -18.14941406 31.23046875 C-17.07743355 29.15026187 -15.91128793 27.25468128 -14.609375 25.3125 C-14.14958252 24.61890381 -13.68979004 23.92530762 -13.21606445 23.21069336 C-12.73226318 22.48116455 -12.24846191 21.75163574 -11.75 21 C-7.28897318 14.2065915 -3.3806024 7.40309132 0 0 Z " fill="#1F2AF1" transform="translate(899,963)"/>
+<path d="M0 0 C3.18844653 4.7826698 1.52653597 9.32644222 0.46875 14.78955078 C-5.79294044 44.31733475 -18.59251685 72.42945436 -36 97 C-36.70125 97.99644531 -37.4025 98.99289062 -38.125 100.01953125 C-42.53929603 106.18402668 -47.20846523 112.12527253 -52 118 C-52.66 117.01 -53.32 116.02 -54 115 C-53.43410156 114.30132813 -52.86820313 113.60265625 -52.28515625 112.8828125 C-51.18494141 111.51769531 -51.18494141 111.51769531 -50.0625 110.125 C-49.33160156 109.22007812 -48.60070313 108.31515625 -47.84765625 107.3828125 C-45.9963748 105.15497253 -45.9963748 105.15497253 -45 103 C-44.34 103 -43.68 103 -43 103 C-43 102.01 -43 101.02 -43 100 C-42.34 100 -41.68 100 -41 100 C-40.731875 99.2575 -40.46375 98.515 -40.1875 97.75 C-39 95 -39 95 -37.4375 92.9375 C-35.88261296 91.11877107 -35.88261296 91.11877107 -35.5625 89 C-35 87 -35 87 -33.23046875 85.359375 C-30.34088695 82.3027946 -28.65114141 78.97482891 -26.75 75.25 C-26.38648438 74.55261719 -26.02296875 73.85523438 -25.6484375 73.13671875 C-24.75893803 71.42794346 -23.87854133 69.71443502 -23 68 C-22.34 68 -21.68 68 -21 68 C-20.88527344 67.31164062 -20.77054688 66.62328125 -20.65234375 65.9140625 C-19.90740228 62.5863599 -18.79404411 59.55435719 -17.5625 56.375 C-17.13066406 55.24835937 -16.69882813 54.12171875 -16.25390625 52.9609375 C-15 50 -15 50 -13 47 C-12.29774646 45.01221621 -11.63755232 43.00947045 -11 41 C-10.54793983 39.71354858 -10.0919684 38.4284672 -9.6328125 37.14453125 C-5.80470915 26.22767528 -3.20773332 15.34435276 -1 4 C-0.67425799 2.66479177 -0.34299341 1.33088107 0 0 Z " fill="#4A61F4" transform="translate(1084,733)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.02806159 1.43737706 1.04684998 2.87493423 1.0625 4.3125 C1.07410156 5.11300781 1.08570313 5.91351562 1.09765625 6.73828125 C1.01757705 9.41292668 0.79562717 11.96950241 0.5078125 14.625 C-0.22956194 22.41831904 -0.186027 30.21944927 -0.18530273 38.04077148 C-0.18748109 40.66471796 -0.20567244 43.2882373 -0.22460938 45.91210938 C-0.27196224 59.79745884 0.75059763 73.27422203 4.0625 86.8125 C4.26367432 87.65997803 4.46484863 88.50745605 4.67211914 89.38061523 C6.93691013 98.47639996 10.02817278 107.3103159 13.22875977 116.11450195 C13.61604248 117.21238037 14.0033252 118.31025879 14.40234375 119.44140625 C14.75804443 120.41795166 15.11374512 121.39449707 15.48022461 122.40063477 C16.0827143 125.41364921 15.67329714 126.48578283 14 129 C2.39190472 100.87269221 -4.20846877 72.3989894 -4.13037109 41.93188477 C-4.12500442 39.43955423 -4.1303464 36.94740325 -4.13671875 34.45507812 C-4.13605797 32.84374961 -4.13477681 31.2324212 -4.1328125 29.62109375 C-4.13483673 28.88958603 -4.13686096 28.15807831 -4.13894653 27.40440369 C-4.11579654 22.2061199 -3.64042364 17.15932151 -3 12 C-2.34 12 -1.68 12 -1 12 C-0.67 8.04 -0.34 4.08 0 0 Z " fill="#4257F4" transform="translate(254,763)"/>
+<path d="M0 0 C0.33 0.66 0.66 1.32 1 2 C1.66 2 2.32 2 3 2 C9.928729 19.80830772 13.84773781 38.03818011 16 57 C16.14683228 58.24463013 16.14683228 58.24463013 16.29663086 59.5144043 C17.14794787 67.56859696 17.11380947 75.59706178 17.0625 83.6875 C17.05747028 85.08268067 17.05291 86.47786311 17.04882812 87.87304688 C17.03714751 91.24874437 17.02076833 94.62434826 17 98 C16.34 98 15.68 98 15 98 C15.01160156 98.65226563 15.02320313 99.30453125 15.03515625 99.9765625 C15.08470994 104.7761914 14.99413751 109.27784685 14 114 C13.67 114 13.34 114 13 114 C13.00666183 113.36789612 13.01332367 112.73579224 13.02018738 112.08453369 C13.08748154 105.39885643 13.13218273 98.713278 13.16479492 92.02734375 C13.17971665 89.54488201 13.20006128 87.06244585 13.22631836 84.58007812 C13.38252853 69.41237717 12.8779948 54.90912992 10 40 C9.68544366 38.30892333 9.3709094 36.61784256 9.05639648 34.92675781 C7.37209207 25.92621695 5.00060131 17.32474613 1.93041992 8.69677734 C0.8529062 5.66503453 0 3.24516952 0 0 Z " fill="#5F89F8" transform="translate(1072,617)"/>
+<path d="M0 0 C0.99 0 1.98 0 3 0 C3.27150879 0.61407715 3.54301758 1.2281543 3.82275391 1.86083984 C5.0834946 4.70190805 6.35418506 7.53842452 7.625 10.375 C8.05167969 11.34050781 8.47835937 12.30601562 8.91796875 13.30078125 C11.85611625 19.83487047 15.16289191 25.95180842 19 32 C19.4232959 32.66821777 19.8465918 33.33643555 20.28271484 34.02490234 C21.46350139 35.86162846 22.6626626 37.68396403 23.875 39.5 C24.30135742 40.13873047 24.72771484 40.77746094 25.16699219 41.43554688 C29.83041072 48.34199669 35.00815647 54.73827186 40.5 61 C43 64 43 64 43 66 C43.66 66 44.32 66 45 66 C48.46900051 68.80973344 51.51350066 71.94927016 52.5625 76.37109375 C52.72785582 82.83030527 50.9505399 88.89295246 49 95 C48.34 95 47.68 95 47 95 C47.1440088 93.33317469 47.29031844 91.66654815 47.4375 90 C47.51871094 88.99324219 47.59992188 87.98648438 47.68359375 86.94921875 C48 84 48 84 48.53515625 81.76953125 C49.2062044 78.94436216 49.46078016 76.76238172 47.92578125 74.22265625 C46.03504671 72.05723873 44.0211822 70.04456778 42 68 C39.96473113 65.7384325 37.97948946 63.4354315 36 61.125 C35.47599609 60.51446777 34.95199219 59.90393555 34.41210938 59.27490234 C30.25993842 54.39466879 26.51099825 49.36313035 23 44 C22.29359375 42.95585938 21.5871875 41.91171875 20.859375 40.8359375 C12.34340356 28.09483235 5.53117511 14.28886905 0 0 Z " fill="#5274F5" transform="translate(207,667)"/>
+<path d="M0 0 C0.495 0.99 0.495 0.99 1 2 C1.99 2.33 2.98 2.66 4 3 C3.1181604 3.15033691 3.1181604 3.15033691 2.21850586 3.30371094 C-9.70023419 5.35389694 -21.38105455 7.6069828 -33 11 C-33.89589844 11.24492187 -34.79179688 11.48984375 -35.71484375 11.7421875 C-43.88360137 14.0392473 -51.67143925 17.22160173 -59.1796875 21.171875 C-59.89560059 21.54546143 -60.61151367 21.91904785 -61.34912109 22.30395508 C-62.76359794 23.04940525 -64.17055421 23.80933552 -65.56884766 24.5847168 C-67.53125 25.62109375 -67.53125 25.62109375 -71 27 C-73.46875 26.22265625 -73.46875 26.22265625 -75 25 C-51.04657618 12.74970838 -26.65241585 4.18199499 0 0 Z " fill="#A59CF7" transform="translate(547,193)"/>
+<path d="M0 0 C1.2159082 0.00080566 2.43181641 0.00161133 3.68457031 0.00244141 C16.19139888 0.08692462 28.19763022 0.98378999 40.3125 4.1875 C39.9825 4.8475 39.6525 5.5075 39.3125 6.1875 C36.91635425 6.04584107 34.52067103 5.89931159 32.125 5.75 C31.45146484 5.71068359 30.77792969 5.67136719 30.08398438 5.63085938 C27.37407635 5.45901155 24.74440908 5.28707626 22.09399414 4.67602539 C18.40622522 4.02832719 14.77015927 4.04472813 11.0390625 4.0546875 C10.23826263 4.05373077 9.43746277 4.05277405 8.61239624 4.05178833 C6.91623862 4.05110907 5.22007838 4.05294564 3.52392578 4.05712891 C0.98073148 4.06241022 -1.56228043 4.05721219 -4.10546875 4.05078125 C-13.02951213 4.04925574 -21.82115639 4.29508266 -30.70556641 5.16845703 C-33.73013445 5.18777227 -35.17598215 4.80100196 -37.6875 3.1875 C-25.18445028 0.60671018 -12.74415654 -0.00888714 0 0 Z " fill="#9A97F6" transform="translate(802.6875,249.8125)"/>
+<path d="M0 0 C-2.75491274 2.84100376 -5.57123907 5.5334065 -8.5625 8.125 C-26.95572519 23.76024783 -26.95572519 23.76024783 -42.59765625 42.01171875 C-44.40350543 44.57210102 -46.31602343 47.0351279 -48.25 49.5 C-48.91515625 50.3559375 -49.5803125 51.211875 -50.265625 52.09375 C-50.83796875 52.7228125 -51.4103125 53.351875 -52 54 C-52.66 54 -53.32 54 -54 54 C-52.64936509 50.27411061 -50.96843351 47.23680143 -48.6875 44 C-48.11386719 43.175 -47.54023438 42.35 -46.94921875 41.5 C-44.81672171 38.76493366 -42.47570279 36.42701272 -40 34 C-38.32479957 32.17446107 -36.65859648 30.34063756 -35 28.5 C-8.23291384 -0.86739628 -8.23291384 -0.86739628 0 0 Z " fill="#9B98F8" transform="translate(447,237)"/>
+<path d="M0 0 C0.66 0.99 1.32 1.98 2 3 C1.52433594 3.75216797 1.52433594 3.75216797 1.0390625 4.51953125 C-2.59240053 10.40811909 -5.89590323 16.44725634 -9.125 22.5625 C-9.54442871 23.35309814 -9.96385742 24.14369629 -10.39599609 24.95825195 C-14.1362821 32.08960263 -17.45644208 39.33167446 -20.21484375 46.8984375 C-21.11496981 49.30773013 -22.08813335 51.68231283 -23.0625 54.0625 C-24.65045063 57.99891401 -25.92903426 61.89463134 -27 66 C-28.98 66.495 -28.98 66.495 -31 67 C-23.47014429 43.01997655 -13.45029743 21.2128361 0 0 Z " fill="#979BF8" transform="translate(391,291)"/>
+<path d="M0 0 C0.66 0 1.32 0 2 0 C2.44730469 1.05058594 2.89460938 2.10117187 3.35546875 3.18359375 C7.76313186 13.45426889 12.43400288 22.96997389 18.86328125 32.15234375 C20 34 20 34 20 36 C20.66 36 21.32 36 22 36 C23.01567807 37.65715896 24.01005812 39.32733959 25 41 C26.82624663 43.36433715 28.69136346 45.69225933 30.57421875 48.01171875 C32 50 32 50 32 52 C32.66 52 33.32 52 34 52 C34.33 52.99 34.66 53.98 35 55 C34.34 55.66 33.68 56.32 33 57 C0 18.41666667 0 18.41666667 0 0 Z " fill="#384BF3" transform="translate(269,890)"/>
+<path d="M0 0 C0.66 0 1.32 0 2 0 C0.64602017 7.14341083 -5.64852284 11.70319732 -10.94921875 16.1953125 C-12.97756748 17.98025938 -14.82331959 19.85805401 -16.6875 21.8125 C-25.30732613 30.53353739 -35.73826297 37.38071737 -46 44 C-47.32 43.34 -48.64 42.68 -50 42 C-48.96552734 41.36384766 -48.96552734 41.36384766 -47.91015625 40.71484375 C-41.63461873 36.79801306 -35.75347225 32.64245692 -30 28 C-29.12859375 27.31421875 -28.2571875 26.6284375 -27.359375 25.921875 C-22.40935991 22.05189894 -22.40935991 22.05189894 -17.83203125 17.76171875 C-16 16 -16 16 -14 16 C-14 15.34 -14 14.68 -14 14 C-12.60805907 12.84570752 -11.21218912 11.69582421 -9.796875 10.5703125 C-6.51780094 7.7046869 -3.81094206 4.31427879 -1 1 C-0.67 0.67 -0.34 0.34 0 0 Z " fill="#3F52F2" transform="translate(1029,849)"/>
+<path d="M0 0 C20.12642968 12.83424502 38.46986876 30.05963923 53 49 C52.01 49.66 51.02 50.32 50 51 C49.443125 50.113125 48.88625 49.22625 48.3125 48.3125 C46.78847793 46.00748441 45.3688456 44.3688456 43.375 42.375 C41 40 41 40 39.9375 37.8125 C39.14871604 35.84094622 39.14871604 35.84094622 37.13671875 35.109375 C34.71018575 33.84952971 33.58080056 32.55903587 31.875 30.4375 C25.32138109 22.70759051 15.80946099 12.26982033 6 9 C4.62437146 7.71034824 3.29233607 6.37310707 2 5 C1.4225 4.4225 0.845 3.845 0.25 3.25 C-0.1625 2.8375 -0.575 2.425 -1 2 C-0.67 1.34 -0.34 0.68 0 0 Z " fill="#9496F7" transform="translate(930,290)"/>
+<path d="M0 0 C1.32 0.33 2.64 0.66 4 1 C-3.41347335 15.22422529 -11.88268076 28.55705536 -22 41 C-22.68578125 41.85207031 -23.3715625 42.70414063 -24.078125 43.58203125 C-27.48812293 47.672596 -27.48812293 47.672596 -29 49 C-29.99 49 -30.98 49 -32 49 C-30.4512456 45.51327545 -28.35487655 42.81445969 -25.9375 39.875 C-23.19551253 36.61448977 -23.19551253 36.61448977 -21 33 C-20.34 33 -19.68 33 -19 33 C-18.57895996 32.12408203 -18.57895996 32.12408203 -18.14941406 31.23046875 C-17.07743355 29.15026187 -15.91128793 27.25468128 -14.609375 25.3125 C-14.14958252 24.61890381 -13.68979004 23.92530762 -13.21606445 23.21069336 C-12.73226318 22.48116455 -12.24846191 21.75163574 -11.75 21 C-7.28897318 14.2065915 -3.3806024 7.40309132 0 0 Z " fill="#2C3BF3" transform="translate(899,963)"/>
+<path d="M0 0 C2.25140084 3.67981062 2.68100712 7.48050787 3.125 11.6875 C3.20991699 12.47680908 3.29483398 13.26611816 3.38232422 14.0793457 C4.66041139 27.98015096 4.16222809 42.05711981 4 56 C1 54 1 54 0.60127258 52.19865417 C0.59016953 51.47205093 0.57906647 50.74544769 0.56762695 49.99682617 C0.54783279 49.17224411 0.52803864 48.34766205 0.50764465 47.49809265 C0.50125473 46.60540176 0.49486481 45.71271088 0.48828125 44.79296875 C0.47033005 43.87542313 0.45237885 42.9578775 0.43388367 42.01252747 C0.37960893 39.07089926 0.34586831 36.12943242 0.3125 33.1875 C0.27933356 31.21547182 0.24484453 29.24346541 0.20898438 27.27148438 C0.09154845 20.51492281 -0.02518652 13.75780385 0 7 C-0.33 7 -0.66 7 -1 7 C-1.04254356 5.00045254 -1.04080783 2.99958364 -1 1 C-0.67 0.67 -0.34 0.34 0 0 Z " fill="#8095F7" transform="translate(1026,440)"/>
+<path d="M0 0 C3.17787664 4.76681496 1.53843541 9.29828187 0.48632812 14.74560547 C-2.35739165 27.92778838 -6.64585084 40.63988972 -12 53 C-12.99 53 -13.98 53 -15 53 C-14.20450927 49.60355963 -13.05730322 46.41520938 -11.81591797 43.15478516 C-7.43996109 31.59817372 -4.12187549 20.04477458 -1.76171875 7.9140625 C-1.24089 5.237804 -0.67894573 2.63444136 0 0 Z " fill="#5370F5" transform="translate(1084,733)"/>
+<path d="M0 0 C9.82859071 1.72579109 19.13579608 4.08899479 28.56445312 7.33398438 C30.52420953 8.00833042 32.48812315 8.66923714 34.453125 9.328125 C40.41031165 11.34234764 46.24121466 13.47299971 52 16 C51.505 17.485 51.505 17.485 51 19 C47.13484244 17.74750759 43.38247763 16.3544341 39.625 14.8125 C33.10235421 12.28177369 26.46495673 10.27030431 19.75 8.3125 C18.73244629 8.01512939 17.71489258 7.71775879 16.66650391 7.41137695 C10.81162099 5.72880217 4.96118843 4.2553125 -1 3 C-0.67 2.01 -0.34 1.02 0 0 Z " fill="#9A98F7" transform="translate(844,254)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.02806159 1.43737706 1.04684998 2.87493423 1.0625 4.3125 C1.07410156 5.11300781 1.08570313 5.91351562 1.09765625 6.73828125 C1.01687894 9.43624347 0.80641292 12.03726034 0.53125 14.71875 C-0.24356818 22.85674718 -0.35927695 31.01959228 -0.5625 39.1875 C-0.60579788 40.82357626 -0.6494153 42.45964409 -0.69335938 44.09570312 C-0.79925341 48.06371468 -0.90083523 52.03181481 -1 56 C-1.99 56 -2.98 56 -4 56 C-4.02491316 51.18026089 -4.04295998 46.36056015 -4.05493164 41.54077148 C-4.05992803 39.90469712 -4.06672739 38.26862715 -4.07543945 36.63256836 C-4.16225376 19.89783459 -4.16225376 19.89783459 -3 12 C-2.34 12 -1.68 12 -1 12 C-0.67 8.04 -0.34 4.08 0 0 Z " fill="#5871F7" transform="translate(254,763)"/>
+<path d="M0 0 C0.99 0 1.98 0 3 0 C3.27150879 0.61407715 3.54301758 1.2281543 3.82275391 1.86083984 C5.0834946 4.70190805 6.35418506 7.53842452 7.625 10.375 C8.05167969 11.34050781 8.47835937 12.30601562 8.91796875 13.30078125 C12.42602897 21.1022883 16.40864759 28.44592826 21.4375 35.375 C23 38 23 38 22.59765625 40.1640625 C22.40042969 40.76992188 22.20320313 41.37578125 22 42 C16.21840633 34.48392822 12.03908824 26.48838191 7.96044922 17.98144531 C6.95395277 15.90500272 5.91452301 13.84716321 4.87109375 11.7890625 C2.94053727 7.94110496 1.4476695 4.05347459 0 0 Z " fill="#5689F6" transform="translate(207,667)"/>
+<path d="M0 0 C0.33 0.66 0.66 1.32 1 2 C1.66 2 2.32 2 3 2 C6.1568621 10.11380727 8.70520794 18.23997424 10.8125 26.6875 C11.03123779 27.56051758 11.24997559 28.43353516 11.4753418 29.33300781 C13 35.59361639 13 35.59361639 13 39 C11.515 39.495 11.515 39.495 10 40 C9.67128906 38.25589844 9.67128906 38.25589844 9.3359375 36.4765625 C7.47437732 26.96459049 5.18638623 17.83844364 1.93115234 8.70166016 C0.85444198 5.66817584 0 3.24662371 0 0 Z " fill="#658DF6" transform="translate(1072,617)"/>
+<path d="M0 0 C5.24591589 0.54666859 9.3227521 3.18442977 13.8125 5.75 C14.96588867 6.39582031 14.96588867 6.39582031 16.14257812 7.0546875 C21.1853471 9.89736233 26.11818451 12.88966965 31 16 C30.67 16.99 30.34 17.98 30 19 C29.175 18.5153125 28.35 18.030625 27.5 17.53125 C18.51390473 12.30010582 9.34189313 7.56175561 0 3 C0 2.01 0 1.02 0 0 Z " fill="#9595F5" transform="translate(897,272)"/>
+<path d="M0 0 C0.99 0.33 1.98 0.66 3 1 C-0.00520803 4.1806822 -3.50087013 6.24011371 -7.25 8.4375 C-7.89324219 8.81970703 -8.53648437 9.20191406 -9.19921875 9.59570312 C-13.44060808 12.10896099 -17.71442404 14.56299502 -22 17 C-22 16.01 -22 15.02 -22 14 C-19.67830372 12.21017237 -17.40420522 10.62714902 -14.9375 9.0625 C-14.28072266 8.63259766 -13.62394531 8.20269531 -12.94726562 7.75976562 C-10.97920842 6.48198267 -8.99406764 5.23672677 -7 4 C-6.35562988 3.58991699 -5.71125977 3.17983398 -5.04736328 2.75732422 C-3.41230351 1.75632867 -1.70926503 0.86823132 0 0 Z " fill="#A19AF8" transform="translate(470,219)"/>
+<path d="M0 0 C0.66 0 1.32 0 2 0 C2 8.25 2 16.5 2 25 C1.34 25 0.68 25 0 25 C0.01160156 25.65226563 0.02320313 26.30453125 0.03515625 26.9765625 C0.08470994 31.7761914 -0.00586249 36.27784685 -1 41 C-1.33 41 -1.66 41 -2 41 C-1.35503394 27.33220856 -0.68988521 13.6655985 0 0 Z " fill="#4E70F6" transform="translate(1087,690)"/>
+<path d="M0 0 C3.0625 2.125 3.0625 2.125 4.0625 4.125 C3.45921875 3.92003906 2.8559375 3.71507812 2.234375 3.50390625 C1.43515625 3.23449219 0.6359375 2.96507812 -0.1875 2.6875 C-0.97640625 2.42066406 -1.7653125 2.15382813 -2.578125 1.87890625 C-12.18080073 -1.18949841 -20.89830986 -0.53562255 -29.9375 4.125 C-32.82875352 6.25804169 -35.42374759 8.56082849 -37.9375 11.125 C-37.9375 8.125 -37.9375 8.125 -36.1875 5.75 C-27.14656054 -2.5354292 -11.21005174 -5.33332803 0 0 Z " fill="#96A5ED" transform="translate(449.9375,486.875)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C2.09945892 10.01292948 2.10055982 19.94401799 2 30 C1.34 30 0.68 30 0 30 C-0.9051224 23.83654745 -1.15242331 17.85009125 -1.125 11.625 C-1.12886719 10.72394531 -1.13273438 9.82289063 -1.13671875 8.89453125 C-1.13542969 8.03472656 -1.13414062 7.17492187 -1.1328125 6.2890625 C-1.13168457 5.51256348 -1.13055664 4.73606445 -1.12939453 3.93603516 C-1 2 -1 2 0 0 Z " fill="#638AF8" transform="translate(192,575)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.03758423 1.18758911 1.03758423 1.18758911 1.07592773 2.39916992 C1.19215729 5.99543363 1.31476176 9.5914528 1.4375 13.1875 C1.47681641 14.43337891 1.51613281 15.67925781 1.55664062 16.96289062 C1.59853516 18.16494141 1.64042969 19.36699219 1.68359375 20.60546875 C1.72025146 21.71043701 1.75690918 22.81540527 1.79467773 23.95385742 C1.98183547 26.73051269 2.42436263 29.28363893 3 32 C3.0659735 34.10323534 3.08562245 36.20835724 3.0625 38.3125 C3.05347656 39.38113281 3.04445312 40.44976563 3.03515625 41.55078125 C3.02355469 42.35902344 3.01195312 43.16726563 3 44 C2.67 44 2.34 44 2 44 C2 42.35 2 40.7 2 39 C1.34 39 0.68 39 0 39 C-0.97239095 30.17851796 -0.98082322 21.60691236 -0.5625 12.75 C-0.51029297 11.51636719 -0.45808594 10.28273438 -0.40429688 9.01171875 C-0.27620809 6.00745447 -0.14133763 3.00366508 0 0 Z " fill="#3751EC" transform="translate(251,792)"/>
+<path d="M0 0 C-3.67315779 2.44877186 -6.97488063 2.71614068 -11.25 3.1875 C-11.98863281 3.28224609 -12.72726562 3.37699219 -13.48828125 3.47460938 C-18.22933972 4.02229779 -22.30704001 3.87527428 -27 3 C-24.06850206 1.35603238 -21.67641762 0.66525063 -18.33984375 0.33203125 C-17.46392578 0.24373047 -16.58800781 0.15542969 -15.68554688 0.06445312 C-14.77869141 -0.01869141 -13.87183594 -0.10183594 -12.9375 -0.1875 C-12.02677734 -0.28224609 -11.11605469 -0.37699219 -10.17773438 -0.47460938 C-3.38970536 -1.12990179 -3.38970536 -1.12990179 0 0 Z " fill="#A8A5FA" transform="translate(792,251)"/>
+<path d="M0 0 C0.99 0 1.98 0 3 0 C3.50505263 2.89503383 4.0042022 5.79087953 4.5 8.6875 C4.64308594 9.50412109 4.78617188 10.32074219 4.93359375 11.16210938 C5.61165962 15.14978248 6.19858392 18.93730404 6 23 C5.01 23 4.02 23 3 23 C2.01 15.41 1.02 7.82 0 0 Z " fill="#6396F8" transform="translate(192,606)"/>
+<path d="M0 0 C4.79175781 2.04975756 8.43676522 6.26002805 12.08203125 9.890625 C11.75203125 10.550625 11.42203125 11.210625 11.08203125 11.890625 C8.16449591 10.5742533 6.16276058 9.1308515 3.89453125 6.890625 C0.00654713 3.42524785 -3.842609 2.55813263 -8.91796875 1.890625 C-5.81660292 0.192258 -3.60016318 -0.59610545 0 0 Z " fill="#2331F2" transform="translate(537.91796875,1020.109375)"/>
+<path d="M0 0 C1 3 1 3 -0.36328125 6.21484375 C-1.00295653 7.46094715 -1.65314888 8.7016949 -2.3125 9.9375 C-2.79493164 10.86852539 -2.79493164 10.86852539 -3.28710938 11.81835938 C-4.18471447 13.54905997 -5.09205426 15.27470177 -6 17 C-6.67092309 18.33119661 -7.34004183 19.66333346 -8 21 C-8.66 20.01 -9.32 19.02 -10 18 C-9.52441406 16.11474609 -9.52441406 16.11474609 -8.515625 14.0234375 C-8.15726562 13.270625 -7.79890625 12.5178125 -7.4296875 11.7421875 C-7.04039062 10.96101563 -6.65109375 10.17984375 -6.25 9.375 C-5.68925781 8.19164062 -5.68925781 8.19164062 -5.1171875 6.984375 C-2.28709609 1.14354804 -2.28709609 1.14354804 0 0 Z " fill="#9497F6" transform="translate(380,312)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.36506623 18.69950331 1.36506623 18.69950331 -2 27 C-4.42945561 23.35581659 -4.0828781 22.07076636 -3.625 17.8125 C-3.51414063 16.72582031 -3.40328125 15.63914062 -3.2890625 14.51953125 C-3.19367188 13.68808594 -3.09828125 12.85664062 -3 12 C-2.34 12 -1.68 12 -1 12 C-0.67 8.04 -0.34 4.08 0 0 Z " fill="#516EF5" transform="translate(254,763)"/>
+<path d="M0 0 C1.59780727 0.04237323 3.19533944 0.09604882 4.79248047 0.15869141 C5.63310028 0.18371735 6.47372009 0.20874329 7.33981323 0.23452759 C10.03016855 0.31683536 12.71980144 0.41338226 15.40966797 0.51025391 C17.23125284 0.56848251 19.05286754 0.62578602 20.87451172 0.68212891 C25.34498085 0.82243005 29.81485323 0.97550491 34.28466797 1.13525391 C34.28466797 1.46525391 34.28466797 1.79525391 34.28466797 2.13525391 C30.35637821 2.30527803 26.42781242 2.46552744 22.4987793 2.61743164 C20.5190034 2.69589764 18.5395225 2.78169807 16.56005859 2.86767578 C9.03620659 3.15339168 1.76012154 3.07005114 -5.71533203 2.13525391 C-3.71533203 0.13525391 -3.71533203 0.13525391 0 0 Z " fill="#0B14E8" transform="translate(675.71533203125,1085.86474609375)"/>
+<path d="M0 0 C2.67494525 2.44234132 3.81966416 4.28417302 4.20874023 7.98608398 C4.7175166 19.50134767 4.70398962 28.18344378 -2 38 C-2.66 38 -3.32 38 -4 38 C-2.1883537 33.31991373 -2.1883537 33.31991373 -0.9765625 31.26171875 C1.91648598 25.97831461 2.37372572 21.28509491 2.375 15.375 C2.3764502 14.65860352 2.37790039 13.94220703 2.37939453 13.20410156 C2.28253637 8.48308266 1.47166529 4.48563579 0 0 Z " fill="#8EA7EF" transform="translate(537,629)"/>
+<path d="M0 0 C0.66 0 1.32 0 2 0 C2.10000892 6.14340486 1.73256099 12.13811782 1.125 18.25 C1.04636719 19.13429688 0.96773437 20.01859375 0.88671875 20.9296875 C0.76103516 22.20972656 0.76103516 22.20972656 0.6328125 23.515625 C0.55949707 24.28165039 0.48618164 25.04767578 0.41064453 25.83691406 C-0.03305208 28.17410309 -0.84462578 29.93125165 -2 32 C-1.86019545 27.97893351 -1.71207681 23.9582139 -1.5625 19.9375 C-1.52318359 18.80376953 -1.48386719 17.67003906 -1.44335938 16.50195312 C-1.23227663 10.93261605 -0.94904568 5.49489474 0 0 Z " fill="#6F8EF5" transform="translate(195,536)"/>
+<path d="M0 0 C0 0.99 0 1.98 0 3 C-1.051875 3.5775 -2.10375 4.155 -3.1875 4.75 C-5.61632941 6.12666444 -7.61148969 7.48919175 -9.8125 9.25 C-12 11 -12 11 -14 11 C-14 11.66 -14 12.32 -14 13 C-15.65 13 -17.3 13 -19 13 C-15.53092419 9.338554 -12.04844095 6.48164242 -7.8125 3.6875 C-6.76707031 2.99011719 -5.72164063 2.29273438 -4.64453125 1.57421875 C-2 0 -2 0 0 0 Z " fill="#8D97F7" transform="translate(301,386)"/>
+<path d="M0 0 C0.66 0.99 1.32 1.98 2 3 C-2.33333333 7.33333333 -6.66666667 11.66666667 -11 16 C-11 10.89586543 -8.85748137 9.19822411 -5.5 5.75 C-4.97535156 5.19570313 -4.45070312 4.64140625 -3.91015625 4.0703125 C-2.61558538 2.70512867 -1.30892741 1.35142505 0 0 Z " fill="#8592F7" transform="translate(257,420)"/>
+<path d="M0 0 C1 3 1 3 -0.1875 5.875 C-2 9 -2 9 -4 11.4375 C-5.73782281 13.66408548 -6.56459088 15.18469437 -7.5625 17.75 C-8.036875 18.8225 -8.51125 19.895 -9 21 C-9.99 21.33 -10.98 21.66 -12 22 C-10.2657267 17.02642312 -7.56672043 12.68501047 -4.875 8.1875 C-4.40707031 7.39923828 -3.93914063 6.61097656 -3.45703125 5.79882812 C-2.30784603 3.86397546 -1.15542997 1.93112772 0 0 Z " fill="#829CEE" transform="translate(532,667)"/>
+<path d="M0 0 C3.29098541 1.35617531 4.61395119 2.48929751 6.140625 5.6953125 C6.48867187 6.41074219 6.83671875 7.12617187 7.1953125 7.86328125 C7.54335937 8.60964844 7.89140625 9.35601563 8.25 10.125 C8.61351562 10.87910156 8.97703125 11.63320313 9.3515625 12.41015625 C10.24531269 14.26821586 11.12412375 16.13344818 12 18 C11.01 18 10.02 18 9 18 C7.49480613 15.37785672 5.99568681 12.75255792 4.5 10.125 C3.85611328 9.00544922 3.85611328 9.00544922 3.19921875 7.86328125 C2.79316406 7.14785156 2.38710937 6.43242188 1.96875 5.6953125 C1.59169922 5.03547363 1.21464844 4.37563477 0.82617188 3.69580078 C0 2 0 2 0 0 Z " fill="#678DF7" transform="translate(1054,581)"/>
+<path d="M0 0 C0.66 0.66 1.32 1.32 2 2 C-1.63 5.63 -5.26 9.26 -9 13 C-9.99 12.34 -10.98 11.68 -12 11 C-10.56564079 9.5385774 -9.12739414 8.08096951 -7.6875 6.625 C-6.88699219 5.81289063 -6.08648437 5.00078125 -5.26171875 4.1640625 C-3 2 -3 2 0 0 Z " fill="#8591F8" transform="translate(270,408)"/>
+<path d="M0 0 C-0.99 0.33 -1.98 0.66 -3 1 C-3 1.66 -3 2.32 -3 3 C-6.67387495 3.85298376 -10.0447393 4.10789471 -13.8125 4.0625 C-15.27623047 4.04896484 -15.27623047 4.04896484 -16.76953125 4.03515625 C-17.87361328 4.01775391 -17.87361328 4.01775391 -19 4 C-12.49119488 0.69702427 -7.24442569 -0.28977703 0 0 Z " fill="#161FEB" transform="translate(753,1081)"/>
+<path d="M0 0 C1.49848359 2.99696718 0.46148783 5.03666664 -0.3125 8.25 C-0.70888672 9.92835938 -0.70888672 9.92835938 -1.11328125 11.640625 C-1.95103805 14.81450537 -2.92427782 17.89966534 -4 21 C-4.33 21 -4.66 21 -5 21 C-5.34684531 13.94747877 -4.58052884 7.62888142 -2 1 C-1.34 0.67 -0.68 0.34 0 0 Z " fill="#6F8CF5" transform="translate(203,510)"/>
+<path d="M0 0 C2.74320403 2.57826454 4.98488989 5.43500692 7.25 8.4375 C7.97703125 9.38496094 8.7040625 10.33242188 9.453125 11.30859375 C11 14 11 14 10.734375 16.34765625 C10.49203125 16.89292969 10.2496875 17.43820312 10 18 C8.50630115 16.13513962 7.03067763 14.25979253 5.5625 12.375 C5.14162109 11.85292969 4.72074219 11.33085938 4.28710938 10.79296875 C1.53985483 7.23252685 0.36973699 4.47717888 0 0 Z " fill="#698EF6" transform="translate(1042,561)"/>
+<path d="M0 0 C1 2 1 2 0.375 4.75 C-1.25172204 8.59497936 -3.2108368 10.91724067 -6 14 C-6.99 13.34 -7.98 12.68 -9 12 C-6.03 8.04 -3.06 4.08 0 0 Z " fill="#93A1F8" transform="translate(239,440)"/>
+<path d="M0 0 C4.87305969 4.29975855 7.8200442 9.37224317 11 15 C10.01 15.33 9.02 15.66 8 16 C6.84448547 14.27728773 5.70095881 12.54653083 4.5625 10.8125 C3.92441406 9.84957031 3.28632812 8.88664062 2.62890625 7.89453125 C1.08453813 5.15022243 0.40183359 3.09581657 0 0 Z " fill="#9196F9" transform="translate(983,341)"/>
+<path d="M0 0 C1.32 0.66 2.64 1.32 4 2 C1.36 4.31 -1.28 6.62 -4 9 C-4.99 8.34 -5.98 7.68 -7 7 C-4.69 4.69 -2.38 2.38 0 0 Z " fill="#9C9AF9" transform="translate(429,248)"/>
+<path d="M0 0 C1.8133922 3.20010388 2.52213974 6.13283843 3.125 9.75 C3.29257813 10.73484375 3.46015625 11.7196875 3.6328125 12.734375 C3.81457031 13.85585938 3.81457031 13.85585938 4 15 C3.01 15.33 2.02 15.66 1 16 C0.63409254 14.27327966 0.28277805 12.54346345 -0.0625 10.8125 C-0.35833984 9.36810547 -0.35833984 9.36810547 -0.66015625 7.89453125 C-1.00423947 4.96389138 -0.74164697 2.83692932 0 0 Z " fill="#5798F7" transform="translate(1081,641)"/>
+<path d="M0 0 C0.99 0 1.98 0 3 0 C3.66 4.95 4.32 9.9 5 15 C4.01 15.33 3.02 15.66 2 16 C0.80911014 10.61972975 -0.2919519 5.54708616 0 0 Z " fill="#5468F6" transform="translate(252,831)"/>
+<path d="M0 0 C2.79033346 2.38275666 3.72983292 4.5022843 4.75 8 C5.01296875 8.86625 5.2759375 9.7325 5.546875 10.625 C6 13 6 13 5 16 C3 15 3 15 2.1484375 13.14453125 C0.6483429 8.62151874 -0.37173481 4.83255247 0 0 Z " fill="#5B8DF5" transform="translate(202,648)"/>
+<path d="M0 0 C3.9252025 3.70090521 6.94580156 7.54959656 10 12 C9.01 12.33 8.02 12.66 7 13 C6.401875 12.071875 5.80375 11.14375 5.1875 10.1875 C3.24693632 7.11025486 3.24693632 7.11025486 1.25 5.375 C0 4 0 4 0 0 Z " fill="#9CA0F9" transform="translate(973,328)"/>
+<path d="M0 0 C3.67990594 3.3203749 5.4938408 7.32599508 7 12 C6.75 15.0625 6.75 15.0625 6 17 C3.97774806 13.9666221 3.00652476 11.38655511 1.875 7.9375 C1.52179687 6.87402344 1.16859375 5.81054688 0.8046875 4.71484375 C0 2 0 2 0 0 Z " fill="#9099FA" transform="translate(1007,381)"/>
+<path d="M0 0 C0 0.66 0 1.32 0 2 C-3.85756507 4.15305957 -6.55129785 5.39253254 -11 5 C-10 2 -10 2 -7.75 0.8125 C-5.00208853 0.00061706 -2.84552111 -0.16260121 0 0 Z " fill="#3040EF" transform="translate(959,904)"/>
+<path d="M0 0 C0.33 0.66 0.66 1.32 1 2 C0.109375 3.953125 0.109375 3.953125 -1.25 6.25 C-3.29715927 9.77978159 -5.21183685 13.32955984 -7 17 C-7.99 16.67 -8.98 16.34 -10 16 C-6.7 10.72 -3.4 5.44 0 0 Z " fill="#7F94EC" transform="translate(497,726)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.33 7.59 1.66 15.18 2 23 C1.01 22.34 0.02 21.68 -1 21 C-1.2487793 18.84521484 -1.2487793 18.84521484 -1.07421875 16.2109375 C-1.01943359 15.26992188 -0.96464844 14.32890625 -0.90820312 13.359375 C-0.83537109 12.37453125 -0.76253906 11.3896875 -0.6875 10.375 C-0.62626953 9.38242187 -0.56503906 8.38984375 -0.50195312 7.3671875 C-0.34839342 4.91023215 -0.18051265 2.45509843 0 0 Z " fill="#7F8EF3" transform="translate(1028,473)"/>
+<path d="M0 0 C1.32 0.33 2.64 0.66 4 1 C1.525 5.455 1.525 5.455 -1 10 C-1.66 10 -2.32 10 -3 10 C-2.49287967 6.28111761 -1.88391785 3.26545761 0 0 Z " fill="#2A38F2" transform="translate(899,963)"/>
+<path d="M0 0 C2 1 2 1 3 3 C2.34 3 1.68 3 1 3 C0.01 5.97 -0.98 8.94 -2 12 C-4 9 -4 9 -3.6875 7 C-3.460625 6.34 -3.23375 5.68 -3 5 C-2.67 4.01 -2.34 3.02 -2 2 C-1.34 2 -0.68 2 0 2 C0 1.34 0 0.68 0 0 Z " fill="#4252F4" transform="translate(919,917)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.53067341 2.10170656 2.04922857 4.20647598 2.5625 6.3125 C2.85253906 7.48425781 3.14257812 8.65601563 3.44140625 9.86328125 C4 13 4 13 3 16 C-1.76849603 5.81981544 -1.76849603 5.81981544 -2 2 C-1.34 1.34 -0.68 0.68 0 0 Z " fill="#5895F6" transform="translate(198,631)"/>
+<path d="M0 0 C1.21236328 0.01353516 1.21236328 0.01353516 2.44921875 0.02734375 C3.37154297 0.04474609 3.37154297 0.04474609 4.3125 0.0625 C-0.19082676 3.06471784 -4.26517579 4.38146025 -9.6875 4.0625 C-6.9209694 -0.0872959 -4.6801992 -0.06782897 0 0 Z " fill="#3040F3" transform="translate(929.6875,914.9375)"/>
+<path d="M0 0 C0.66 0.33 1.32 0.66 2 1 C1.71828671 3.77217867 1.42508608 6.54230241 1.125 9.3125 C1.04636719 10.09818359 0.96773437 10.88386719 0.88671875 11.69335938 C0.80292969 12.45068359 0.71914062 13.20800781 0.6328125 13.98828125 C0.55949707 14.68477783 0.48618164 15.38127441 0.41064453 16.09887695 C0 18 0 18 -2 21 C-3.25 13.375 -3.25 13.375 -1 10 C-0.54398739 7.49103314 -0.54398739 7.49103314 -0.375 4.8125 C-0.30023437 3.91144531 -0.22546875 3.01039063 -0.1484375 2.08203125 C-0.09945313 1.39496094 -0.05046875 0.70789063 0 0 Z " fill="#5E8DFC" transform="translate(1087,715)"/>
+<path d="M0 0 C3.96 0.33 7.92 0.66 12 1 C12 1.66 12 2.32 12 3 C7.38 3 2.76 3 -2 3 C-1.34 2.01 -0.68 1.02 0 0 Z " fill="#A094F5" transform="translate(594,191)"/>
+<path d="M0 0 C0.66 0.99 1.32 1.98 2 3 C-0.31 5.31 -2.62 7.62 -5 10 C-5.66 9.01 -6.32 8.02 -7 7 C-5.37660195 5.29115995 -3.70680947 3.62553283 -2 2 C-1.34 2 -0.68 2 0 2 C0 1.34 0 0.68 0 0 Z " fill="#485CF5" transform="translate(1015,863)"/>
+<path d="M0 0 C-4.625 4 -4.625 4 -8 4 C-8.99 4.33 -9.98 4.66 -11 5 C-11.33 4.01 -11.66 3.02 -12 2 C-10.75579353 1.4654744 -9.50429064 0.94791389 -8.25 0.4375 C-7.55390625 0.14746094 -6.8578125 -0.14257812 -6.140625 -0.44140625 C-3.69987216 -1.07831803 -2.3596345 -0.80248831 0 0 Z " fill="#98A1F7" transform="translate(337,370)"/>
+<path d="M0 0 C2.14699969 3.44175522 2.09856795 5.7720292 1.625 9.75 C1.51414062 10.73484375 1.40328125 11.7196875 1.2890625 12.734375 C1.19367188 13.48203125 1.09828125 14.2296875 1 15 C0.34 15 -0.32 15 -1 15 C-1.02685412 12.68756208 -1.04632841 10.3750373 -1.0625 8.0625 C-1.07410156 6.77472656 -1.08570313 5.48695313 -1.09765625 4.16015625 C-1 1 -1 1 0 0 Z " fill="#6691F6" transform="translate(1028,493)"/>
+<path d="M0 0 C0.79921875 0.01804688 1.5984375 0.03609375 2.421875 0.0546875 C3.02515625 0.07789063 3.6284375 0.10109375 4.25 0.125 C4.25 0.785 4.25 1.445 4.25 2.125 C-0.37921525 3.1411692 -4.09462607 2.96296731 -8.75 2.125 C-5.68753253 0.34090198 -3.52920727 -0.10380021 0 0 Z " fill="#9B98F5" transform="translate(773.75,251.875)"/>
+<path d="M0 0 C0.33 0.66 0.66 1.32 1 2 C1.99 2.33 2.98 2.66 4 3 C-6.55808656 4.33257403 -6.55808656 4.33257403 -11 3 C-11 2.67 -11 2.34 -11 2 C-5.555 1.01 -5.555 1.01 0 0 Z " fill="#AEA5F7" transform="translate(547,193)"/>
+<path d="M0 0 C3.48746762 0.0827319 6.82471633 0.50244327 10.25 1.1875 C10.25 1.5175 10.25 1.8475 10.25 2.1875 C4.64436958 3.01372671 -0.17289352 3.25545656 -5.75 2.1875 C-3.75 0.1875 -3.75 0.1875 0 0 Z " fill="#121CEA" transform="translate(449.75,1025.8125)"/>
+<path d="M0 0 C0.99 0.33 1.98 0.66 3 1 C2.07347299 2.17539996 1.13336613 3.34010577 0.1875 4.5 C-0.33457031 5.1496875 -0.85664062 5.799375 -1.39453125 6.46875 C-3 8 -3 8 -6 8 C-4.55746343 4.63408134 -2.66735273 2.48952921 0 0 Z " fill="#3648F1" transform="translate(1022,857)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1 5.61 1 11.22 1 17 C0.67 17 0.34 17 0 17 C-0.33 13.7 -0.66 10.4 -1 7 C-1.33 7 -1.66 7 -2 7 C-2.125 4.625 -2.125 4.625 -2 2 C-1.34 1.34 -0.68 0.68 0 0 Z " fill="#6E8FFA" transform="translate(193,570)"/>
+<path d="M0 0 C-2.92965912 2.92965912 -5.680053 3.94133569 -9.8125 4.125 C-10.534375 4.08375 -11.25625 4.0425 -12 4 C-8.7771058 -0.8343413 -5.44718932 -0.10277716 0 0 Z " fill="#9D93F5" transform="translate(519,201)"/>
+<path d="M0 0 C4.62 2.31 9.24 4.62 14 7 C14 7.33 14 7.66 14 8 C9.15904166 8.56952451 6.82586841 6.82781578 3 4 C2.01 3.34 1.02 2.68 0 2 C0 1.34 0 0.68 0 0 Z " fill="#7083E9" transform="translate(415,789)"/>
+<path d="M0 0 C0 0.66 0 1.32 0 2 C-3.3 2.66 -6.6 3.32 -10 4 C-10.33 3.34 -10.66 2.68 -11 2 C-3.57142857 -1.57142857 -3.57142857 -1.57142857 0 0 Z " fill="#8E94F7" transform="translate(356,363)"/>
+<path d="M0 0 C2.70931419 0.15481795 4.46584039 0.48172081 6.4453125 2.40234375 C7.67679642 3.89771708 8.8429837 5.4462924 10 7 C6.433255 7 5.89456323 6.36308045 3.3125 4.0625 C2.68988281 3.51722656 2.06726563 2.97195313 1.42578125 2.41015625 C0.95527344 1.94480469 0.48476563 1.47945313 0 1 C0 0.67 0 0.34 0 0 Z " fill="#9191F6" transform="translate(937,297)"/>
+<path d="M0 0 C0.66 0 1.32 0 2 0 C2.33 0.99 2.66 1.98 3 3 C1.1875 6.1875 1.1875 6.1875 -1 9 C-1.66 9 -2.32 9 -3 9 C-2.44271087 5.65626525 -1.64826111 2.96687001 0 0 Z " fill="#3F58F2" transform="translate(1055,812)"/>
+<path d="M0 0 C1.32 0.66 2.64 1.32 4 2 C1.03 3.32 -1.94 4.64 -5 6 C-5 5.01 -5 4.02 -5 3 C-2.75 1.1875 -2.75 1.1875 0 0 Z " fill="#8C95F8" transform="translate(311,379)"/>
+<path d="M0 0 C3.2542015 2.83430453 4.5206753 4.68607774 5 9 C4.01 9.495 4.01 9.495 3 10 C2.30289269 8.71349294 1.61757124 7.42059335 0.9375 6.125 C0.36322266 5.04605469 0.36322266 5.04605469 -0.22265625 3.9453125 C-0.47917969 3.30335938 -0.73570312 2.66140625 -1 2 C-0.67 1.34 -0.34 0.68 0 0 Z " fill="#929AF8" transform="translate(994,357)"/>
+<path d="M0 0 C0.99 0.33 1.98 0.66 3 1 C2.34 1 1.68 1 1 1 C1.33 1.99 1.66 2.98 2 4 C-1.4352048 6.29013653 -2.985331 6.17842973 -7 6 C-4.94766315 3.7522025 -3.99332739 2.9977758 -1 2 C-0.67 1.34 -0.34 0.68 0 0 Z " fill="#2833F1" transform="translate(816,1052)"/>
+<path d="M0 0 C1.98 1.65 3.96 3.3 6 5 C5.67 5.66 5.34 6.32 5 7 C1.63279613 5.60667426 0.0140476 4.0210714 -2 1 C-1.34 0.67 -0.68 0.34 0 0 Z " fill="#2D3AF4" transform="translate(544,1025)"/>
+<path d="M0 0 C-1.25125384 3.75376152 -2.5652404 4.24073289 -6 6 C-6.66 6 -7.32 6 -8 6 C-8 5.01 -8 4.02 -8 3 C-5.11165997 0.89229241 -3.61537605 0 0 0 Z " fill="#2D45F1" transform="translate(981,892)"/>
+<path d="M0 0 C2.39073445 3.82517513 2.55966552 7.59665524 3 12 C2.01 12 1.02 12 0 12 C0 10.35 0 8.7 0 7 C-0.33 7 -0.66 7 -1 7 C-1.04254356 5.00045254 -1.04080783 2.99958364 -1 1 C-0.67 0.67 -0.34 0.34 0 0 Z " fill="#93A2FA" transform="translate(1026,440)"/>
+<path d="M0 0 C3.82097239 0.53069061 6.06171403 1.49701566 9 4 C5.18510326 5.46726798 2.70988378 4.43336419 -1 3 C-0.67 2.01 -0.34 1.02 0 0 Z " fill="#A4A2F8" transform="translate(897,272)"/>
+<path d="M0 0 C3.55780196 0.60990891 6.6828589 1.5783681 10 3 C9.67 3.99 9.34 4.98 9 6 C4.64464931 4.83857315 2.35380297 3.92300495 0 0 Z " fill="#A8A8F6" transform="translate(886,267)"/>
+<path d="M0 0 C4.75 0.875 4.75 0.875 7 2 C6.67 3.32 6.34 4.64 6 6 C3.96166576 4.7260411 1.96147874 3.38938077 0 2 C0 1.34 0 0.68 0 0 Z " fill="#1D21F0" transform="translate(580,1054)"/>
+<path d="M0 0 C0.99 1.98 1.98 3.96 3 6 C2.34 6.66 1.68 7.32 1 8 C-0.65 5.69 -2.3 3.38 -4 1 C-2 0 -2 0 0 0 Z " fill="#3950F4" transform="translate(291,926)"/>
+<path d="M0 0 C1 3 1 3 -0.125 5.9375 C-2.07639565 9.12477956 -3.96422279 10.86675115 -7 13 C-5.35821735 8.22390502 -2.73453298 4.20617096 0 0 Z " fill="#7084EA" transform="translate(876,778)"/>
+<path d="M0 0 C1.125 1.625 1.125 1.625 2 4 C1.125 7.25 1.125 7.25 0 10 C-0.66 9.67 -1.32 9.34 -2 9 C-1.125 1.125 -1.125 1.125 0 0 Z " fill="#4863F4" transform="translate(1078,761)"/>
+<path d="M0 0 C0.66 0.33 1.32 0.66 2 1 C0.88424427 4.34726719 0.48655378 4.62079748 -2.4375 6.25 C-4.2009375 7.11625 -4.2009375 7.11625 -6 8 C-6.66 7.67 -7.32 7.34 -8 7 C-5.36 4.69 -2.72 2.38 0 0 Z " fill="#8C98F8" transform="translate(279,400)"/>
+<path d="M0 0 C0.66 0.33 1.32 0.66 2 1 C-0.35277269 3.72426311 -2.62496331 4.8141763 -6 6 C-6.66 5.34 -7.32 4.68 -8 4 C-6.71349294 3.30289269 -5.42059335 2.61757124 -4.125 1.9375 C-3.40570313 1.55464844 -2.68640625 1.17179687 -1.9453125 0.77734375 C-1.30335938 0.52082031 -0.66140625 0.26429688 0 0 Z " fill="#9CA1F9" transform="translate(323,373)"/>
+<path d="M0 0 C5.53846154 0.61538462 5.53846154 0.61538462 7.875 2.5625 C8.431875 3.2740625 8.431875 3.2740625 9 4 C7.3125 4.6875 7.3125 4.6875 5 5 C2.25 3.6875 2.25 3.6875 0 2 C0 1.34 0 0.68 0 0 Z " fill="#9998F6" transform="translate(904,276)"/>
+<path d="M0 0 C0 0.99 0 1.98 0 3 C-4.29 2.67 -8.58 2.34 -13 2 C-13 1.67 -13 1.34 -13 1 C-11.39602723 0.83147753 -9.7918131 0.66525114 -8.1875 0.5 C-7.29417969 0.4071875 -6.40085937 0.314375 -5.48046875 0.21875 C-3 0 -3 0 0 0 Z " fill="#2B36F1" transform="translate(520,1024)"/>
+<path d="M0 0 C3.14624993 -0.26218749 4.61837017 -0.24754367 7.3125 1.5 C8.1478125 2.2425 8.1478125 2.2425 9 3 C5.18510326 4.46726798 2.70988378 3.43336419 -1 2 C-0.67 1.34 -0.34 0.68 0 0 Z " fill="#1825EF" transform="translate(404,1016)"/>
+<path d="M0 0 C0.33 0.99 0.66 1.98 1 3 C-0.25 5.1875 -0.25 5.1875 -2 7 C-2.99 7 -3.98 7 -5 7 C-3.75023244 3.34683329 -3.32901247 2.21934164 0 0 Z " fill="#2A37F0" transform="translate(890,982)"/>
+<path d="M0 0 C0 3.96 0 7.92 0 12 C-0.33 12 -0.66 12 -1 12 C-1 10.35 -1 8.7 -1 7 C-1.66 7 -2.32 7 -3 7 C-3 5.02 -3 3.04 -3 1 C-1 0 -1 0 0 0 Z " fill="#4258F4" transform="translate(254,824)"/>
+<path d="M0 0 C2.23551759 3.35327639 2.17283528 3.90743657 1.625 7.6875 C1.51414062 8.49574219 1.40328125 9.30398438 1.2890625 10.13671875 C1.19367188 10.75160156 1.09828125 11.36648438 1 12 C0.34 11.34 -0.32 10.68 -1 10 C-0.9765625 7.6171875 -0.9765625 7.6171875 -0.625 4.875 C-0.51414062 3.96492187 -0.40328125 3.05484375 -0.2890625 2.1171875 C-0.19367188 1.41851563 -0.09828125 0.71984375 0 0 Z " fill="#4660F3" transform="translate(1084,733)"/>
+<path d="M0 0 C2.32472205 2.85306797 3.7508258 5.54074837 5 9 C4.01 9 3.02 9 2 9 C0.4375 6.1875 0.4375 6.1875 -1 3 C-0.67 2.01 -0.34 1.02 0 0 Z " fill="#5D9AF8" transform="translate(1061,590)"/>
+<path d="M0 0 C0.66 0.33 1.32 0.66 2 1 C1.01 3.97 0.02 6.94 -1 10 C-1.66 9.01 -2.32 8.02 -3 7 C-1.625 3.3125 -1.625 3.3125 0 0 Z " fill="#8B8FF8" transform="translate(373,323)"/>
+<path d="M0 0 C2.97 0 5.94 0 9 0 C9 0.66 9 1.32 9 2 C4.545 2.495 4.545 2.495 0 3 C0 2.01 0 1.02 0 0 Z " fill="#131DE9" transform="translate(506,1026)"/>
+<path d="M0 0 C0.66 0 1.32 0 2 0 C1.42655063 2.86724686 1.1385485 3.8614515 -1 6 C-1.99 6 -2.98 6 -4 6 C-2.84826645 3.53199953 -1.95216435 1.95216435 0 0 Z " fill="#2735EE" transform="translate(871,1006)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.36923077 6.52307692 1.36923077 6.52307692 -0.5 8.9375 C-0.995 9.288125 -1.49 9.63875 -2 10 C-3.39195915 5.82412255 -1.82323219 3.86525224 0 0 Z " fill="#7FA0FA" transform="translate(208,493)"/>
+<path d="M0 0 C0.99 0 1.98 0 3 0 C3.99 2.97 4.98 5.94 6 9 C3 8 3 8 2.05078125 6.15234375 C1.80714844 5.42144531 1.56351563 4.69054687 1.3125 3.9375 C1.06113281 3.20402344 0.80976562 2.47054688 0.55078125 1.71484375 C0.36902344 1.14894531 0.18726563 0.58304687 0 0 Z " fill="#949EF8" transform="translate(1013,399)"/>
+<path d="M0 0 C0.66 0 1.32 0 2 0 C1.67 1.98 1.34 3.96 1 6 C-0.32 6.33 -1.64 6.66 -3 7 C-1.125 1.125 -1.125 1.125 0 0 Z " fill="#A5A6F9" transform="translate(382,306)"/>
+<path d="M0 0 C0.33 0.99 0.66 1.98 1 3 C-0.9375 5.6875 -0.9375 5.6875 -3 8 C-3.75 6.25 -3.75 6.25 -4 4 C-2.0625 1.75 -2.0625 1.75 0 0 Z " fill="#3D56F1" transform="translate(1041,835)"/>
+<path d="M0 0 C1 3 1 3 0.22265625 4.82421875 C-0.8515625 6.54947917 -1.92578125 8.27473958 -3 10 C-3.66 10 -4.32 10 -5 10 C-3.66511872 6.40608886 -2.03977277 3.24509304 0 0 Z " fill="#839DED" transform="translate(538,657)"/>
+<path d="M0 0 C1.99097846 2.98646769 2.94124926 5.59687262 4 9 C3.01 9 2.02 9 1 9 C-1.125 3.375 -1.125 3.375 0 0 Z " fill="#53A5F8" transform="translate(1069,606)"/>
+<path d="M0 0 C2.91488977 2.6234008 4.88503898 5.71816394 7 9 C4.625 8.4375 4.625 8.4375 2 7 C0.6875 3.375 0.6875 3.375 0 0 Z " fill="#5DA3F7" transform="translate(1042,561)"/>
+<path d="M0 0 C2.97069541 2.54631035 4.4775751 5.42230149 6 9 C5.67 9.66 5.34 10.32 5 11 C1.19015156 8.22920113 0.93159248 4.37131855 0 0 Z " fill="#A4AEFC" transform="translate(1001,369)"/>
+<path d="M0 0 C0.721875 0.144375 1.44375 0.28875 2.1875 0.4375 C3.5796875 0.7159375 3.5796875 0.7159375 5 1 C6.66666667 1.33333333 8.33333333 1.66666667 10 2 C7 4 7 4 3.8125 3.625 C2.884375 3.41875 1.95625 3.2125 1 3 C0.67 2.01 0.34 1.02 0 0 Z " fill="#2E3AEF" transform="translate(410,1017)"/>
+<path d="M0 0 C1.32 0 2.64 0 4 0 C4.33 1.98 4.66 3.96 5 6 C4.01 5.67 3.02 5.34 2 5 C0.8125 2.4375 0.8125 2.4375 0 0 Z " fill="#3040F5" transform="translate(271,899)"/>
+<path d="M0 0 C-5.41538462 4.06153846 -5.41538462 4.06153846 -8.375 3.75 C-8.91125 3.5025 -9.4475 3.255 -10 3 C-3.375 -1.125 -3.375 -1.125 0 0 Z " fill="#7184EC" transform="translate(868,793)"/>
+<path d="M0 0 C0.33 0 0.66 0 1 0 C1.05416188 1.60379341 1.09286638 3.20811406 1.125 4.8125 C1.14820313 5.70582031 1.17140625 6.59914063 1.1953125 7.51953125 C1 10 1 10 -1 13 C-1.33 11.02 -1.66 9.04 -2 7 C-1.67 7 -1.34 7 -1 7 C-0.67 4.69 -0.34 2.38 0 0 Z " fill="#324BF0" transform="translate(252,777)"/>
+<path d="M0 0 C1.9451 2.91765 2.45276317 4.62537285 3 8 C2.01 8.33 1.02 8.66 0 9 C-1.125 3.375 -1.125 3.375 0 0 Z " fill="#95A1F9" transform="translate(1022,420)"/>
+<path d="M0 0 C-3.53411321 2.12046792 -6.94393835 2.53199289 -11 3 C-8.21756596 -1.17365106 -4.53441502 -0.22300402 0 0 Z " fill="#9895F9" transform="translate(800,250)"/>
+<path d="M0 0 C1.32 0.66 2.64 1.32 4 2 C2.35 2.66 0.7 3.32 -1 4 C-1 1 -1 1 0 0 Z " fill="#A7A5F9" transform="translate(429,248)"/>
+<path d="M0 0 C0.66 0.99 1.32 1.98 2 3 C1.01 3.99 0.02 4.98 -1 6 C-1.99 5.67 -2.98 5.34 -4 5 C-2.68 3.35 -1.36 1.7 0 0 Z " fill="#2B35EF" transform="translate(848,1029)"/>
+<path d="M0 0 C0.66 0 1.32 0 2 0 C2 1.98 2 3.96 2 6 C1.01 6.33 0.02 6.66 -1 7 C-0.67 4.69 -0.34 2.38 0 0 Z " fill="#2B3BEF" transform="translate(907,945)"/>
+<path d="M0 0 C0.33 0.99 0.66 1.98 1 3 C-0.9375 6.1875 -0.9375 6.1875 -3 9 C-3.66 8.67 -4.32 8.34 -5 8 C-3.35 5.36 -1.7 2.72 0 0 Z " fill="#7488E9" transform="translate(468,775)"/>
+<path d="M0 0 C4.875 4.75 4.875 4.75 6 7 C4.125 6.75 4.125 6.75 2 6 C0.61504198 3.85331506 0 2.56128588 0 0 Z " fill="#58A3F7" transform="translate(1032,549)"/>
+<path d="M0 0 C4 1 4 1 5.75 3.5625 C6.1625 4.366875 6.575 5.17125 7 6 C6.01 6.495 6.01 6.495 5 7 C3.35 4.69 1.7 2.38 0 0 Z " fill="#7186F5" transform="translate(1026,545)"/>
+<path d="M0 0 C0.66 0.99 1.32 1.98 2 3 C0.625 5 0.625 5 -1 7 C-1.66 7 -2.32 7 -3 7 C-1.125 1.125 -1.125 1.125 0 0 Z " fill="#8194F7" transform="translate(223,464)"/>
+<path d="M0 0 C1.64826111 2.96687001 2.44271087 5.65626525 3 9 C2.01 9 1.02 9 0 9 C-0.84454356 5.62182575 -1.10844919 3.32534757 0 0 Z " fill="#A2AAFB" transform="translate(1019,409)"/>
+<path d="M0 0 C0.66 0.99 1.32 1.98 2 3 C-0.625 6.875 -0.625 6.875 -4 8 C-2.66666667 5.33333333 -1.33333333 2.66666667 0 0 Z " fill="#A6A4FA" transform="translate(391,291)"/>
+<path d="M0 0 C2.64 0.99 5.28 1.98 8 3 C7.01 4.485 7.01 4.485 6 6 C3.96166576 4.7260411 1.96147874 3.38938077 0 2 C0 1.34 0 0.68 0 0 Z " fill="#AAA3F8" transform="translate(649,201)"/>
+<path d="M0 0 C0.66 0.66 1.32 1.32 2 2 C-1.375 2.125 -1.375 2.125 -5 2 C-5.66 1.34 -6.32 0.68 -7 0 C-3.85179059 -1.04940314 -3.00659136 -1.066855 0 0 Z " fill="#B1AAF9" transform="translate(557,193)"/>
+<path d="" fill="#0000FF" transform="translate(0,0)"/>
+<path d="" fill="#FFFFFF" transform="translate(0,0)"/>
+<path d="" fill="#FFFFFF" transform="translate(0,0)"/>
+</svg>
diff --git a/src/client/src/__tests__/helpers/client/observability.test.ts b/src/client/src/__tests__/helpers/client/observability.test.ts
index 080529ad..bfc09b82 100644
--- a/src/client/src/__tests__/helpers/client/observability.test.ts
+++ b/src/client/src/__tests__/helpers/client/observability.test.ts
@@ -1,5 +1,5 @@
import { prepareObservabilitySignalChange } from "@/helpers/client/observability";
-import { filterStoreSlice } from "@/store/filter";
+import { DEFAULT_SORTING, filterStoreSlice } from "@/store/filter";
import { withLenses } from "@dhmk/zustand-lens";
import { create } from "zustand";
@@ -45,4 +45,24 @@ describe("prepareObservabilitySignalChange", () => {
});
expect(store.getState().filter.details.groupBy).toBeNull();
});
+
+ // E3: sort key applied on the previous tab gets reset so the
+ // new tab doesn't try to ORDER BY a column it doesn't have.
+ it("resets sorting and offset when changing signal", () => {
+ const store = createStore();
+
+ store.getState().filter.updateFilter("sorting", {
+ type: "Tokens",
+ direction: "asc",
+ });
+ store.getState().filter.updateFilter("offset", 50);
+
+ prepareObservabilitySignalChange(
+ store.getState().filter.updateConfig,
+ store.getState().filter.updateFilter
+ );
+
+ expect(store.getState().filter.details.sorting).toEqual(DEFAULT_SORTING);
+ expect(store.getState().filter.details.offset).toBe(0);
+ });
});
diff --git a/src/client/src/__tests__/helpers/client/trace.test.ts b/src/client/src/__tests__/helpers/client/trace.test.ts
index bb90cfd9..635ff336 100644
--- a/src/client/src/__tests__/helpers/client/trace.test.ts
+++ b/src/client/src/__tests__/helpers/client/trace.test.ts
@@ -11,6 +11,8 @@ import {
getSpanCostFormatted,
getSpanTooltipText,
ensureTraceRowShape,
+ isSyntheticSpanId,
+ SYNTHETIC_SPAN_ID_PREFIX,
} from '@/helpers/client/trace';
import { TraceMapping } from '@/constants/traces';
@@ -373,6 +375,44 @@ describe('getSpanDurationDisplay', () => {
const result = getSpanDurationDisplay(makeSpan('0'));
expect(result).toMatch(/0\.00/);
});
+
+ // Regression: a falsy numeric Duration (the synthetic session root
+ // and point-in-time coding spans carry `Duration: 0` as a number)
+ // used to render the literal "NaNs" instead of "0.00s".
+ it('returns "0.00s" (never "NaN") for numeric-zero duration', () => {
+ const result = getSpanDurationDisplay({
+ Duration: 0,
+ SpanId: 's',
+ SpanName: 'coding_agent.session',
+ Cost: 0,
+ children: [],
+ } as any);
+ expect(result).toBe('0.00s');
+ expect(result).not.toContain('NaN');
+ });
+
+ it('returns "0.00s" (never "NaN") for missing duration', () => {
+ const result = getSpanDurationDisplay({
+ SpanId: 's',
+ SpanName: 'test',
+ Cost: 0,
+ children: [],
+ } as any);
+ expect(result).not.toContain('NaN');
+ });
+});
+
+describe('isSyntheticSpanId', () => {
+ it('detects synthetic session-root ids', () => {
+ expect(isSyntheticSpanId(`${SYNTHETIC_SPAN_ID_PREFIX}abc-123`)).toBe(true);
+ });
+
+ it('returns false for real span ids and empty/nullish values', () => {
+ expect(isSyntheticSpanId('b38ad6b13f2eaf71')).toBe(false);
+ expect(isSyntheticSpanId('')).toBe(false);
+ expect(isSyntheticSpanId(null)).toBe(false);
+ expect(isSyntheticSpanId(undefined)).toBe(false);
+ });
});
describe('getSpanCostFormatted', () => {
diff --git a/src/client/src/__tests__/lib/platform/agents/materialize.test.ts b/src/client/src/__tests__/lib/platform/agents/materialize.test.ts
index 980f9278..70f1b05b 100644
--- a/src/client/src/__tests__/lib/platform/agents/materialize.test.ts
+++ b/src/client/src/__tests__/lib/platform/agents/materialize.test.ts
@@ -67,14 +67,21 @@ function captureInsertedRows(): RecordedInsert[] {
function queueDiscovery(
sdkRows: Array<Record<string, unknown>>,
ctrlRows: Array<Record<string, unknown>>,
- requestCountRows: Array<Record<string, unknown>> = []
+ requestCountRows: Array<Record<string, unknown>> = [],
+ codingRows: Array<Record<string, unknown>> = []
) {
+ // `materializeAgents` fires `Promise.all([discoverAgents(),
+ // discoverCodingAgents()])`. Inside `discoverAgents` two queries run
+ // sequentially (SDK then controller); `discoverCodingAgents` fires
+ // one. The microtask order under `Promise.all` is therefore:
+ // 1) SDK discovery (kicked off first inside discoverAgents)
+ // 2) Coding-agent discovery (kicked off by the second Promise.all entry)
+ // 3) Controller discovery (resumes after SDK resolves)
+ // 4) Request-count rollup (after both discovery functions resolve)
mockedDC
- // 1: SDK discovery query
.mockResolvedValueOnce({ data: sdkRows } as any)
- // 2: Controller discovery query
+ .mockResolvedValueOnce({ data: codingRows } as any)
.mockResolvedValueOnce({ data: ctrlRows } as any)
- // 3: Request-count query
.mockResolvedValueOnce({ data: requestCountRows } as any);
}
@@ -120,7 +127,15 @@ describe("materializeAgents — workload_key dedup", () => {
const inserts: RecordedInsert[] = [];
// First three calls are the queued discovery queries; capture the
// insert that follows.
- mockedDC.mockImplementationOnce(async (c: any, op: string) => {
+ // `mockImplementation` (not `Once`) intentionally: the materializer
+ // now runs an extra conflict-resolution SELECT before the final
+ // summary INSERT when summaryRows contain any non-coding source.
+ // That probe must be covered too, otherwise the unmocked call
+ // returns `undefined` and the production code blows up reading
+ // `res.err`. The implementation here short-circuits every non-
+ // insert call with `{ data: [] }` so the conflict query sees
+ // "no conflicting coding rows" and proceeds to the insert.
+ mockedDC.mockImplementation(async (c: any, op: string) => {
if (op === "insert") {
inserts.push({
table: String(c.table),
@@ -177,7 +192,15 @@ describe("materializeAgents — workload_key dedup", () => {
]
);
const inserts: RecordedInsert[] = [];
- mockedDC.mockImplementationOnce(async (c: any, op: string) => {
+ // `mockImplementation` (not `Once`) intentionally: the materializer
+ // now runs an extra conflict-resolution SELECT before the final
+ // summary INSERT when summaryRows contain any non-coding source.
+ // That probe must be covered too, otherwise the unmocked call
+ // returns `undefined` and the production code blows up reading
+ // `res.err`. The implementation here short-circuits every non-
+ // insert call with `{ data: [] }` so the conflict query sees
+ // "no conflicting coding rows" and proceeds to the insert.
+ mockedDC.mockImplementation(async (c: any, op: string) => {
if (op === "insert") {
inserts.push({
table: String(c.table),
@@ -265,7 +288,15 @@ describe("materializeAgents — workload_key dedup", () => {
]
);
const inserts: RecordedInsert[] = [];
- mockedDC.mockImplementationOnce(async (c: any, op: string) => {
+ // `mockImplementation` (not `Once`) intentionally: the materializer
+ // now runs an extra conflict-resolution SELECT before the final
+ // summary INSERT when summaryRows contain any non-coding source.
+ // That probe must be covered too, otherwise the unmocked call
+ // returns `undefined` and the production code blows up reading
+ // `res.err`. The implementation here short-circuits every non-
+ // insert call with `{ data: [] }` so the conflict query sees
+ // "no conflicting coding rows" and proceeds to the insert.
+ mockedDC.mockImplementation(async (c: any, op: string) => {
if (op === "insert") {
inserts.push({
table: String(c.table),
@@ -312,7 +343,15 @@ describe("materializeAgents — workload_key dedup", () => {
]
);
const inserts: RecordedInsert[] = [];
- mockedDC.mockImplementationOnce(async (c: any, op: string) => {
+ // `mockImplementation` (not `Once`) intentionally: the materializer
+ // now runs an extra conflict-resolution SELECT before the final
+ // summary INSERT when summaryRows contain any non-coding source.
+ // That probe must be covered too, otherwise the unmocked call
+ // returns `undefined` and the production code blows up reading
+ // `res.err`. The implementation here short-circuits every non-
+ // insert call with `{ data: [] }` so the conflict query sees
+ // "no conflicting coding rows" and proceeds to the insert.
+ mockedDC.mockImplementation(async (c: any, op: string) => {
if (op === "insert") {
inserts.push({
table: String(c.table),
@@ -350,10 +389,16 @@ describe("materializeAgents — workload_key dedup", () => {
await materializeAgents();
- // SDK discovery is queries[0]; controller discovery is queries[1].
+ // Discovery now fires three concurrent queries (SDK, coding-agent,
+ // controller) so positional indexing is unstable. Find the
+ // controller query by its distinctive
+ // `openlit_controller_services` source table.
expect(queries.length).toBeGreaterThanOrEqual(2);
- const ctrlQuery = queries[1];
- expect(ctrlQuery).toMatch(/argMax\(s\.llm_providers,\s*s\.last_seen\)/);
- expect(ctrlQuery).toMatch(/latest\.llm_providers\s+AS\s+llm_providers/);
+ const ctrlQuery = queries.find((q) =>
+ q.includes("openlit_controller_services")
+ );
+ expect(ctrlQuery).toBeDefined();
+ expect(ctrlQuery!).toMatch(/argMax\(s\.llm_providers,\s*s\.last_seen\)/);
+ expect(ctrlQuery!).toMatch(/latest\.llm_providers\s+AS\s+llm_providers/);
});
});
diff --git a/src/client/src/__tests__/lib/platform/coding-agents/queries.test.ts b/src/client/src/__tests__/lib/platform/coding-agents/queries.test.ts
new file mode 100644
index 00000000..a9b2b9d7
--- /dev/null
+++ b/src/client/src/__tests__/lib/platform/coding-agents/queries.test.ts
@@ -0,0 +1,73 @@
+/**
+ * Unit coverage for the SQL building blocks in the coding-agents
+ * queries layer. We test pure helpers that build clauses around the
+ * `coding_agent.session.is_subagent` filter and the `CHAT_ID_EXPR`
+ * coalesce contract. These are the regression-prone bits — the rest
+ * of the file is a series of templated strings around them.
+ *
+ * Integration coverage (hitting a real ClickHouse) lives in the
+ * playground / CI smoke layer; this file is only the *shape* of the
+ * SQL the function builds, which is enough to catch the two
+ * historical regressions:
+ *
+ * 1. is_subagent filter accidentally dropped (returns to "every
+ * subagent gets its own session row" behavior).
+ * 2. CHAT_ID_EXPR loses one of the fallback attributes, causing
+ * pre-Cursor-1.99 transcripts to fold into the wrong session.
+ */
+
+import { buildSessionsHaving, escape } from "@/lib/platform/coding-agents/query-builders";
+
+describe("buildSessionsHaving", () => {
+ it("hides subagent rows by default", () => {
+ const out = buildSessionsHaving({});
+ expect(out).toContain("HAVING");
+ expect(out).toContain("is_subagent = 0");
+ });
+
+ it("includes subagent rows when explicitly opted in", () => {
+ const out = buildSessionsHaving({ includeSubagents: true });
+ // When the operator opts in AND no other filters apply,
+ // HAVING should be empty — anything else means a stray
+ // implicit filter snuck in.
+ expect(out).toBe("");
+ });
+
+ it("composes vendor + user + classification filters with AND", () => {
+ const out = buildSessionsHaving({
+ vendor: "cursor",
+ classification: "work",
+ });
+ expect(out).toMatch(/HAVING /);
+ expect(out).toContain("vendor = 'cursor'");
+ expect(out).toContain("user = '[email protected]'");
+ expect(out).toContain("classification = 'work'");
+ expect(out).toContain("is_subagent = 0");
+ // AND-joined; verify there's no stray OR or stray comma in
+ // case a future refactor swaps the join.
+ expect(out).not.toMatch(/\bOR\b/);
+ expect(out).not.toContain(",");
+ });
+
+ it("escapes single quotes in user input to defang SQL injection", () => {
+ // escape() is the same util used everywhere in queries.ts;
+ // confirm it survives the buildSessionsHaving pass-through.
+ // We use backslash-escaping (matching the existing helper),
+ // so o'malley should render as o\'malley inside the literal.
+ const out = buildSessionsHaving({ user: "o'malley" });
+ expect(out).toContain("user = 'o\\'malley'");
+ // Also confirm escape() directly: backslash-escape both
+ // backslashes and apostrophes.
+ expect(escape("a'b\\c")).toBe("a\\'b\\\\c");
+ });
+
+ it("preserves the is_subagent guard when only includeSubagents is set false explicitly", () => {
+ const out = buildSessionsHaving({
+ includeSubagents: false,
+ vendor: "claude-code",
+ });
+ expect(out).toContain("vendor = 'claude-code'");
+ expect(out).toContain("is_subagent = 0");
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/controller/health.test.ts b/src/client/src/__tests__/lib/platform/controller/health.test.ts
new file mode 100644
index 00000000..22b74513
--- /dev/null
+++ b/src/client/src/__tests__/lib/platform/controller/health.test.ts
@@ -0,0 +1,34 @@
+import {
+ isControllerStale,
+ resolveControllerHealth,
+} from "@/lib/platform/controller/health";
+
+describe("resolveControllerHealth", () => {
+ it("prefers computed_status over stored status", () => {
+ expect(
+ resolveControllerHealth({
+ computed_status: "active",
+ status: "healthy",
+ })
+ ).toBe("active");
+ });
+
+ it("falls back to stored status", () => {
+ expect(
+ resolveControllerHealth({
+ status: "healthy",
+ })
+ ).toBe("healthy");
+ });
+});
+
+describe("isControllerStale", () => {
+ it("returns true only for inactive", () => {
+ expect(
+ isControllerStale({ computed_status: "inactive", status: "healthy" })
+ ).toBe(true);
+ expect(
+ isControllerStale({ computed_status: "degraded", status: "healthy" })
+ ).toBe(false);
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/request/request.test.ts b/src/client/src/__tests__/lib/platform/request/request.test.ts
index b82e98b4..12801ff5 100644
--- a/src/client/src/__tests__/lib/platform/request/request.test.ts
+++ b/src/client/src/__tests__/lib/platform/request/request.test.ts
@@ -209,6 +209,69 @@ describe('getHeirarchyViaSpanId', () => {
expect(result).toEqual({ err: 'Error building hierarchy', record: {} });
});
+
+ it('unions spans across subagent sessions when source span is a subagent', async () => {
+ // Source span belongs to subagent 'sub-1' whose parent chat is 'parent-1'.
+ // Expectation: step 2 query unions trace + parent's session_id + any
+ // subagent whose parent_id is 'parent-1' (resource OR span attr).
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({
+ data: [{ TraceId: 't1', CodingSessionId: 'sub-1', CodingParentId: 'parent-1' }],
+ err: null,
+ })
+ .mockResolvedValueOnce({
+ data: [
+ {
+ SpanId: 'root',
+ ParentSpanId: '',
+ SpanName: 'coding_agent.session',
+ SpanAttributes: { 'coding_agent.session.id': 'parent-1' },
+ Timestamp: 1,
+ },
+ {
+ SpanId: 'sub-tool',
+ ParentSpanId: '',
+ SpanName: 'coding_agent.tool.call',
+ SpanAttributes: { 'coding_agent.session.id': 'sub-1' },
+ Timestamp: 2,
+ },
+ ],
+ err: null,
+ });
+
+ const result = await getHeirarchyViaSpanId('any-span-in-sub-1');
+ expect(dataCollector).toHaveBeenCalledTimes(2);
+ const [, secondCall] = (dataCollector as jest.Mock).mock.calls;
+ const allSpansQuery = secondCall[0].query as string;
+ expect(allSpansQuery).toContain("SpanAttributes['coding_agent.session.id'] = 'parent-1'");
+ expect(allSpansQuery).toContain("ResourceAttributes['coding_agent.agent.parent_id'] = 'parent-1'");
+ expect(result.err).toBeNull();
+ });
+
+ it('uses own session_id when no parent_id is set', async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({
+ data: [{ TraceId: 't1', CodingSessionId: 'top-chat', CodingParentId: '' }],
+ err: null,
+ })
+ .mockResolvedValueOnce({
+ data: [
+ {
+ SpanId: 'root',
+ ParentSpanId: '',
+ SpanName: 'coding_agent.session',
+ SpanAttributes: { 'coding_agent.session.id': 'top-chat' },
+ Timestamp: 1,
+ },
+ ],
+ err: null,
+ });
+
+ await getHeirarchyViaSpanId('any-span-in-top-chat');
+ const [, secondCall] = (dataCollector as jest.Mock).mock.calls;
+ const allSpansQuery = secondCall[0].query as string;
+ expect(allSpansQuery).toContain("SpanAttributes['coding_agent.session.id'] = 'top-chat'");
+ });
});
describe('getRequestExist', () => {
diff --git a/src/client/src/app/(playground)/agents/[agentKey]/page.tsx b/src/client/src/app/(playground)/agents/[agentKey]/page.tsx
index 72f04363..cc403397 100644
--- a/src/client/src/app/(playground)/agents/[agentKey]/page.tsx
+++ b/src/client/src/app/(playground)/agents/[agentKey]/page.tsx
@@ -74,13 +74,28 @@ const VersionDrawer = dynamic(
() => import("@/components/(playground)/agents/version-drawer"),
{ loading: () => null, ssr: false }
);
+const CodingAgentDetail = dynamic(
+ () =>
+ import(
+ "@/components/(playground)/coding-agents/coding-agent-detail"
+ ),
+ {
+ loading: () => <TabLoading label={getMessage().AGENTS_LOADING_SERVICE_DETAILS} />,
+ ssr: false,
+ }
+);
type AgentDetailTab =
| "overview"
| "dashboard"
| "monitoring"
| "definition"
- | "configuration";
+ | "configuration"
+ | "sessions"
+ // Coding-agent-only tab (`UnifiedAgent.source === "coding"`). Was
+ // missing from VALID_TABS, so clicks on the Users tab fell back to
+ // "overview" via `coerceTab`.
+ | "users";
const VALID_TABS: AgentDetailTab[] = [
"overview",
@@ -88,6 +103,8 @@ const VALID_TABS: AgentDetailTab[] = [
"monitoring",
"definition",
"configuration",
+ "sessions",
+ "users",
];
function coerceTab(value: string | null): AgentDetailTab {
@@ -314,11 +331,21 @@ export default function AgentDetailPage() {
}
if (error || !agent) {
+ // Even on a 404 we honor `?from=<tab>` so a failed deep-link
+ // from the Coding Agents tab still routes back to Coding
+ // Agents rather than tossing the user back to Applications.
+ const fromParam = searchParams.get("from");
+ const backHref =
+ fromParam === "coding"
+ ? "/agents?tab=coding"
+ : fromParam === "controllers"
+ ? "/agents?tab=controllers"
+ : "/agents";
return (
<div className="flex flex-col items-center justify-center h-full text-stone-500 dark:text-stone-400 text-sm gap-3">
<div>{error || "Agent not found"}</div>
<button
- onClick={() => router.push("/agents")}
+ onClick={() => router.push(backHref)}
className="text-stone-700 dark:text-stone-200 underline"
>
{getMessage().AGENTS_BACK_TO_HUB}
@@ -329,6 +356,7 @@ export default function AgentDetailPage() {
const activeVersion = selectedVersion || latestVersion;
const scopedVersionFilter = urlVersionHash ? versionFilter : null;
+ const isCodingAgent = agent.source === "coding";
// Pulses an attention dot on the Configuration tab when a
// controller-discovered agent has no telemetry yet. Two guards prevent
@@ -352,29 +380,86 @@ export default function AgentDetailPage() {
agent={agent}
onRefresh={fetchAgent}
rightSlot={
- <div className="flex items-center gap-2">
- <LifecycleActions
- agent={agent}
- onRefresh={fetchAgent}
- variant="header"
- />
- <VersionChooser
- versions={versions}
- selectedHash={urlVersionHash}
- onSelectVersion={handleSelectVersion}
- onOpenAllVersions={() => setVersionsOpen(true)}
- />
- </div>
+ isCodingAgent ? null : (
+ <div className="flex items-center gap-2">
+ <LifecycleActions
+ agent={agent}
+ onRefresh={fetchAgent}
+ variant="header"
+ />
+ <VersionChooser
+ versions={versions}
+ selectedHash={urlVersionHash}
+ onSelectVersion={handleSelectVersion}
+ onOpenAllVersions={() => setVersionsOpen(true)}
+ />
+ </div>
+ )
}
/>
- <VersionTimeline
- agentKey={agent.agent_key}
- versions={versions}
- selectedHash={urlVersionHash}
- />
+ {isCodingAgent ? (
+ <CodingAgentDetail
+ agent={agent}
+ tab={urlTab}
+ onTabChange={handleTabChange}
+ />
+ ) : (
+ <>
+ <VersionTimeline
+ agentKey={agent.agent_key}
+ versions={versions}
+ selectedHash={urlVersionHash}
+ />
+ <TraditionalAgentTabs
+ agent={agent}
+ versions={versions}
+ urlTab={urlTab}
+ urlVersionHash={urlVersionHash}
+ handleTabChange={handleTabChange}
+ effectiveVersionHash={effectiveVersionHash}
+ activeVersion={activeVersion}
+ needsInstrumentation={needsInstrumentation}
+ fetchAgent={fetchAgent}
+ versionsOpen={versionsOpen}
+ setVersionsOpen={setVersionsOpen}
+ />
+ </>
+ )}
+ </div>
+ </AgentScopeProvider>
+ );
+}
+
+interface TraditionalAgentTabsProps {
+ agent: UnifiedAgent;
+ versions: AgentVersion[];
+ urlTab: AgentDetailTab;
+ urlVersionHash: string | null;
+ handleTabChange: (value: string) => void;
+ effectiveVersionHash: string | null;
+ activeVersion: AgentVersion | null;
+ needsInstrumentation: boolean;
+ fetchAgent: () => Promise<void>;
+ versionsOpen: boolean;
+ setVersionsOpen: (open: boolean) => void;
+}
- <Tabs
+function TraditionalAgentTabs({
+ agent,
+ versions,
+ urlTab,
+ handleTabChange,
+ effectiveVersionHash,
+ activeVersion,
+ needsInstrumentation,
+ fetchAgent,
+ versionsOpen,
+ setVersionsOpen,
+}: TraditionalAgentTabsProps) {
+ return (
+ <>
+ <Tabs
value={urlTab}
onValueChange={handleTabChange}
className="w-full"
@@ -445,14 +530,13 @@ export default function AgentDetailPage() {
</TabsContent>
</Tabs>
- <VersionDrawer
- agentKey={agent.agent_key}
- open={versionsOpen}
- onClose={() => setVersionsOpen(false)}
- initialVersions={versions}
- />
- </div>
- </AgentScopeProvider>
+ <VersionDrawer
+ agentKey={agent.agent_key}
+ open={versionsOpen}
+ onClose={() => setVersionsOpen(false)}
+ initialVersions={versions}
+ />
+ </>
);
}
diff --git a/src/client/src/app/(playground)/agents/coding-agents-table.tsx b/src/client/src/app/(playground)/agents/coding-agents-table.tsx
new file mode 100644
index 00000000..2516bef7
--- /dev/null
+++ b/src/client/src/app/(playground)/agents/coding-agents-table.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { useMemo } from "react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { Bot } from "lucide-react";
+import type { UnifiedAgent } from "@/types/agents";
+import { Columns } from "@/components/data-table/columns";
+import DataTable from "@/components/data-table/table";
+import {
+ CodingAgentVendorIcon,
+ codingAgentVendorLabel,
+ hasCodingAgentVendorIcon,
+} from "@/components/svg/coding-agents";
+import getMessage from "@/constants/messages";
+
+interface CodingAgentsTableProps {
+ services: UnifiedAgent[];
+ isFetched: boolean;
+ isLoading: boolean;
+}
+
+type CodingColumnKey =
+ | "vendor"
+ | "sessions"
+ | "users"
+ | "cost"
+ | "lines"
+ | "acceptance"
+ | "commits"
+ | "prs";
+
+// Compute acceptance % the same way listSessions / listCodingUsers do:
+// the denominator is total edit decisions (accept + reject), not lines.
+// Mirroring that keeps the hub stats consistent with the per-session
+// list a click away.
+function acceptancePct(row: UnifiedAgent): number {
+ const accepts = row.coding_edit_accept_24h ?? 0;
+ const rejects = row.coding_edit_reject_24h ?? 0;
+ const total = accepts + rejects;
+ if (!total) return 0;
+ return Math.round((accepts * 100) / total);
+}
+
+const columns: Columns<CodingColumnKey, UnifiedAgent> = {
+ vendor: {
+ header: () => getMessage().AGENTS_CODING_COLUMN_VENDOR,
+ cell: ({ row }) => {
+ const vendor = row.coding_agent_vendor;
+ const hasIcon = hasCodingAgentVendorIcon(vendor);
+ return (
+ <Link
+ href={`/agents/${row.agent_key}?from=coding`}
+ className="font-medium text-stone-900 dark:text-stone-100 hover:underline truncate flex items-center gap-2"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {hasIcon ? (
+ <CodingAgentVendorIcon
+ vendor={vendor}
+ className="h-4 w-4 shrink-0"
+ />
+ ) : (
+ <Bot className="h-4 w-4 shrink-0 text-stone-500" />
+ )}
+ <span className="truncate">{codingAgentVendorLabel(vendor)}</span>
+ </Link>
+ );
+ },
+ enableHiding: false,
+ },
+ sessions: {
+ header: () => getMessage().AGENTS_CODING_COLUMN_SESSIONS,
+ cell: ({ row }) => (
+ <span className="text-sm text-stone-700 dark:text-stone-200 tabular-nums">
+ {(row.coding_session_count_24h ?? 0).toLocaleString()}
+ </span>
+ ),
+ },
+ users: {
+ header: () => getMessage().AGENTS_CODING_COLUMN_USERS,
+ cell: ({ row }) => (
+ <span className="text-sm text-stone-700 dark:text-stone-200 tabular-nums">
+ {(row.coding_active_users_24h ?? 0).toLocaleString()}
+ </span>
+ ),
+ },
+ cost: {
+ header: () => getMessage().AGENTS_CODING_COLUMN_COST,
+ cell: ({ row }) => (
+ <span className="text-sm text-stone-700 dark:text-stone-200 tabular-nums">
+ ${(row.coding_cost_usd_24h ?? 0).toFixed(2)}
+ </span>
+ ),
+ },
+ lines: {
+ header: () => getMessage().AGENTS_CODING_COLUMN_LINES,
+ cell: ({ row }) => (
+ <span className="text-sm text-stone-700 dark:text-stone-200 tabular-nums">
+ +{(row.coding_lines_added_24h ?? 0).toLocaleString()}
+ <span className="ml-1 text-stone-400">/</span>
+ <span className="ml-1 text-rose-600 dark:text-rose-400">
+ -{(row.coding_lines_removed_24h ?? 0).toLocaleString()}
+ </span>
+ </span>
+ ),
+ },
+ acceptance: {
+ header: () => getMessage().AGENTS_CODING_COLUMN_ACCEPTANCE,
+ cell: ({ row }) => {
+ const accepts = row.coding_edit_accept_24h ?? 0;
+ const rejects = row.coding_edit_reject_24h ?? 0;
+ const total = accepts + rejects;
+ return (
+ <span className="text-sm text-stone-700 dark:text-stone-200 tabular-nums">
+ {total ? `${acceptancePct(row)}%` : "—"}
+ </span>
+ );
+ },
+ },
+ commits: {
+ header: () => getMessage().AGENTS_CODING_COLUMN_COMMITS,
+ cell: ({ row }) => (
+ <span className="text-sm text-stone-700 dark:text-stone-200 tabular-nums">
+ {(row.coding_commit_count_24h ?? 0).toLocaleString()}
+ </span>
+ ),
+ },
+ prs: {
+ header: () => getMessage().AGENTS_CODING_COLUMN_PRS,
+ cell: ({ row }) => (
+ <span className="text-sm text-stone-700 dark:text-stone-200 tabular-nums">
+ {(row.coding_pr_count_24h ?? 0).toLocaleString()}
+ </span>
+ ),
+ },
+};
+
+// Lines / Acceptance / Commits / PRs default ON. They're the new
+// signal columns the user explicitly asked for; if an installation
+// doesn't have data yet the cells render "0" / "—" which is the
+// signal we want (zero is meaningful for "agents that haven't yet
+// committed anything"). Users can hide them via the column toggle
+// menu the DataTable already ships.
+const VISIBILITY_COLUMNS: Record<CodingColumnKey, boolean> = {
+ vendor: true,
+ sessions: true,
+ users: true,
+ cost: true,
+ lines: true,
+ acceptance: true,
+ commits: true,
+ prs: true,
+};
+
+export default function CodingAgentsTable({
+ services,
+ isFetched,
+ isLoading,
+}: CodingAgentsTableProps) {
+ const router = useRouter();
+
+ // Stable order: most-active first (sessions desc), then by last_seen.
+ const sorted = useMemo(() => {
+ return [...services].sort((a, b) => {
+ const sa = a.coding_session_count_24h ?? 0;
+ const sb = b.coding_session_count_24h ?? 0;
+ if (sb !== sa) return sb - sa;
+ return (b.last_seen || "").localeCompare(a.last_seen || "");
+ });
+ }, [services]);
+
+ if (isFetched && !isLoading && sorted.length === 0) {
+ return (
+ <div className="rounded-lg border border-dashed border-stone-300 dark:border-stone-700 px-6 py-10 text-center">
+ <div className="text-sm font-medium text-stone-900 dark:text-stone-100">
+ {getMessage().AGENTS_CODING_EMPTY_TITLE}
+ </div>
+ <div className="mt-1.5 text-xs text-stone-500 dark:text-stone-400 max-w-md mx-auto">
+ {getMessage().AGENTS_CODING_EMPTY_BODY}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <DataTable
+ columns={columns}
+ data={sorted}
+ isFetched={isFetched}
+ isLoading={isLoading}
+ visibilityColumns={VISIBILITY_COLUMNS}
+ extraFunctions={{}}
+ onClick={(row) =>
+ router.push(`/agents/${row.agent_key}?from=coding`)
+ }
+ />
+ );
+}
diff --git a/src/client/src/app/(playground)/agents/controller-table.tsx b/src/client/src/app/(playground)/agents/controller-table.tsx
index b0b3b539..1e777078 100644
--- a/src/client/src/app/(playground)/agents/controller-table.tsx
+++ b/src/client/src/app/(playground)/agents/controller-table.tsx
@@ -6,6 +6,7 @@ import type {
ControllerInstance,
ControllerHealth,
} from "@/types/controller";
+import { resolveControllerHealth, isControllerStale } from "@/lib/platform/controller/health";
import { Columns } from "@/components/data-table/columns";
import DataTable from "@/components/data-table/table";
import LinuxSvg from "@/components/svg/linux";
@@ -42,7 +43,7 @@ const columns: Columns<ControllerColumnKey, ControllerInstance> = {
controller: {
header: () => getMessage().AGENTS_COLUMN_CONTROLLER,
cell: ({ row }) => {
- const stale = (row.computed_status || row.status) === "inactive";
+ const stale = isControllerStale(row);
return (
<div className={`overflow-hidden ${stale ? "opacity-50" : ""}`}>
<div className="font-medium text-stone-900 dark:text-stone-100 truncate">
@@ -139,7 +140,7 @@ const columns: Columns<ControllerColumnKey, ControllerInstance> = {
status: {
header: () => getMessage().AGENTS_COLUMN_STATUS,
cell: ({ row }) => {
- const health = row.computed_status || row.status;
+ const health = resolveControllerHealth(row);
return (
<Badge
variant="outline"
@@ -169,7 +170,7 @@ export default function ControllerTable({
const router = useRouter();
const handleClick = (row: ControllerInstance) => {
- router.push(`/agents/controller/${row.instance_id}`);
+ router.push(`/agents/controller/${row.instance_id}?from=controllers`);
};
return (
diff --git a/src/client/src/app/(playground)/agents/no-coding-agents.tsx b/src/client/src/app/(playground)/agents/no-coding-agents.tsx
new file mode 100644
index 00000000..80e476d1
--- /dev/null
+++ b/src/client/src/app/(playground)/agents/no-coding-agents.tsx
@@ -0,0 +1,498 @@
+"use client";
+
+/**
+ * Empty-state for the "Coding Agents" tab on /agents. Shown when the
+ * org has no coding-agent telemetry yet.
+ *
+ * The snippet is auto-filled with two values pulled from the running
+ * dashboard:
+ *
+ * - OPENLIT_OTLP_ENDPOINT: derived from `window.location.origin` with
+ * the port replaced by 4318 (the collector's HTTP listener). Uses
+ * the URL Web API rather than string concatenation per the
+ * frontend-security rule.
+ * - OPENLIT_API_KEY: pulled from the first existing API key in this
+ * org; if none exists, an inline "Generate API key" button POSTs to
+ * /api/api-key (same backend the Settings page uses) and the
+ * returned key replaces the placeholder in the snippet.
+ *
+ * Per-vendor descriptions / hook lists are removed — the deep
+ * reference lives at docs.openlit.io/.../coding-agents/onboarding.
+ */
+
+import { ComponentType, useCallback, useEffect, useMemo, useState } from "react";
+import {
+ BotMessageSquare,
+ Check,
+ Copy,
+ KeyRound,
+ Loader2,
+} from "lucide-react";
+import copy from "copy-to-clipboard";
+import { toast } from "sonner";
+import {
+ CodingAgentVendorIcon,
+ hasCodingAgentVendorIcon,
+} from "@/components/svg/coding-agents";
+import LinuxSvg from "@/components/svg/linux";
+import MacSvg from "@/components/svg/mac";
+import WindowsSvg from "@/components/svg/windows";
+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import { getPingStatus } from "@/selectors/database-config";
+import { useRootStore } from "@/store";
+import { ApiKey } from "@/types/api-key";
+
+type OsIconComponent = ComponentType<{ className?: string }>;
+
+type VendorId = "claude-code" | "cursor" | "codex";
+type OsId = "macos" | "linux" | "windows";
+
+interface VendorMeta {
+ id: VendorId;
+ label: string;
+ // Argument passed to `openlit coding install --vendor=<v>`. The
+ // full command is composed at render time using the OS-specific
+ // openlit invocation (see bootstrapForOs.openlitBin) — hardcoding
+ // `openlit coding install …` here would break the Windows
+ // PowerShell path which has to use the `&` call operator.
+ cliFlag: string;
+ // User-facing post-install steps shown under the snippet. The
+ // install command writes hook files (and registers plugins where
+ // the vendor's CLI is available), but the *agent process itself*
+ // generally caches its hook table at process start, so the user
+ // has to bounce the agent before telemetry starts flowing. Codex
+ // additionally requires an in-TUI trust step.
+ postInstall: {
+ // One-line, imperative restart instruction. Renders as the
+ // first step regardless of vendor.
+ restart: string;
+ // Optional follow-up steps. Currently only Codex needs them.
+ extraSteps?: string[];
+ };
+}
+
+interface OsMeta {
+ id: OsId;
+ label: string;
+ icon: OsIconComponent;
+}
+
+const VENDORS: VendorMeta[] = [
+ {
+ id: "claude-code",
+ label: "Claude Code",
+ cliFlag: "claude-code",
+ postInstall: {
+ restart: "Quit and reopen Claude Code.",
+ },
+ },
+ {
+ id: "cursor",
+ label: "Cursor",
+ cliFlag: "cursor",
+ postInstall: {
+ restart: "Fully quit Cursor (⌘Q on macOS, File → Exit on Windows/Linux) and reopen it.",
+ },
+ },
+ {
+ id: "codex",
+ label: "Codex",
+ cliFlag: "codex",
+ postInstall: {
+ restart: "Restart Codex (or open a new `codex` session in a fresh shell).",
+ // Codex's security model requires every plugin hook to
+ // be explicitly trusted in the TUI before it fires —
+ // without this step, the plugin is "installed" but
+ // inert and no telemetry reaches OpenLit. The "send a
+ // prompt" follow-up that used to live here was dropped
+ // because the generic "Start a session in <vendor>"
+ // step rendered below covers it.
+ extraSteps: [
+ "Inside Codex, run `/hooks` and trust each `openlit@openlit` entry.",
+ ],
+ },
+ },
+];
+
+// Use the locally vendored brand SVGs (icons8) so the OS cards
+// match the existing controllers page (which already uses
+// LinuxSvg for the same purpose). All three use `currentColor`
+// so the active-state highlight in dark mode picks them up.
+const OS_OPTIONS: OsMeta[] = [
+ { id: "macos", label: "macOS", icon: MacSvg },
+ { id: "linux", label: "Linux", icon: LinuxSvg },
+ { id: "windows", label: "Windows", icon: WindowsSvg },
+];
+
+const DEFAULT_OTLP_ENDPOINT = "http://localhost:4318";
+const API_KEY_PLACEHOLDER = "$OPENLIT_API_KEY";
+const GENERATED_API_KEY_NAME = "coding-agents";
+
+// OS-specific install bootstrap.
+//
+// Each branch resolves to:
+//
+// install The one-liner that lands the `openlit` binary on disk.
+// openlitBin How subsequent commands in the same chain should
+// invoke openlit. CRITICAL: we cannot rely on bare
+// `openlit` here, because the install step's PATH
+// update (rc-file edit on Unix, registry edit on
+// Windows) only takes effect in NEW shells, not the
+// one currently parsing the `&&` chain. Using an
+// explicit path makes the chain work on first paste
+// without requiring a terminal restart.
+// joiner Shell command separator: bash `&&` short-circuits on
+// failure; PowerShell 5.1 doesn't support `&&` (only
+// PS7+ does), so Windows uses `;`.
+//
+// Per-OS choices:
+// macOS → Homebrew tap (`openlit/openlit/openlit`). Bare
+// `openlit` works in the chain because brew's
+// `/opt/homebrew/bin` (or `/usr/local/bin` on Intel
+// Macs) is already on PATH at shell startup.
+// Linux → cli/scripts/install.sh in this repo, hosted via raw
+// GitHub. Drops the binary at `~/.openlit/bin/openlit`;
+// the chain uses that absolute path because the install
+// dir isn't on PATH yet for the current shell. zsh /
+// bash / dash all tilde-expand on parse so `~/...`
+// works without `eval`.
+// Windows → cli/scripts/install.ps1, same channel. Drops the
+// binary at `$env:USERPROFILE\.openlit\bin\openlit.exe`.
+// The chain uses PowerShell's `&` call operator with
+// an explicit path so backslashes parse correctly.
+//
+// Pinning the install-script URLs to `main` (rather than a release
+// tag) means the snippet auto-tracks whatever is on the default
+// branch. Switch to a tag like `cli-1.2.0` once releases settle.
+const INSTALL_SCRIPTS_BASE =
+ "https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts";
+
+interface OsBootstrap {
+ install: string;
+ // Optional, OS-specific command that makes `openlit` available in the
+ // *current* shell session after install (i.e. before the user opens a
+ // new terminal). Without this, `install.sh` / `install.ps1` can only
+ // update PATH for future shells (rc-file edit / user PATH), and a
+ // chained one-liner would fail at `openlit configure`.
+ activate?: string;
+ joiner: string;
+}
+
+function bootstrapForOs(os: OsId): OsBootstrap {
+ switch (os) {
+ case "macos":
+ return {
+ install: "brew install openlit/openlit/openlit",
+ // brew writes into a directory already on PATH for the
+ // current shell, so no activation step needed.
+ joiner: " && ",
+ };
+ case "windows":
+ return {
+ install: `iwr -useb ${INSTALL_SCRIPTS_BASE}/install.ps1 | iex`,
+ // Update the current PowerShell session PATH (user PATH
+ // updates only apply to new shells). This makes `openlit`
+ // immediately runnable in a chained one-liner.
+ activate: `$env:Path = "$env:USERPROFILE\\.openlit\\bin;$env:Path"`,
+ joiner: "; ",
+ };
+ case "linux":
+ default:
+ return {
+ install: `curl -fsSL ${INSTALL_SCRIPTS_BASE}/install.sh | sh`,
+ // Ensure `openlit` is available in the current shell so the
+ // chained snippet can run `openlit configure` without
+ // requiring a terminal restart.
+ activate: `export PATH="$HOME/.openlit/bin:$PATH"`,
+ joiner: " && ",
+ };
+ }
+}
+
+/**
+ * Replace the port on a URL with 4318 (OpenLit collector's HTTP/OTLP
+ * port). When the input has no explicit port (e.g.
+ * `https://openlit.example.com`), `URL.port = "..."` still appends it.
+ *
+ * Returns the input as-is if it doesn't parse as a URL so a freshly
+ * loaded SSR pass — where the value is the default — still renders
+ * sensibly.
+ */
+function buildOtlpEndpoint(origin: string): string {
+ try {
+ const url = new URL(origin);
+ url.port = "4318";
+ return url.origin;
+ } catch {
+ return DEFAULT_OTLP_ENDPOINT;
+ }
+}
+
+interface NoCodingAgentsProps {
+ /**
+ * If true, render in a compact mode (no large hero, less padding).
+ * Used when this empty state is shown inside the Coding Agents tab
+ * body — the tabs above already supply the page-level context.
+ */
+ compact?: boolean;
+}
+
+function detectOs(): OsId {
+ if (typeof navigator === "undefined") return "macos";
+ const platform =
+ (navigator as Navigator & { userAgentData?: { platform?: string } })
+ .userAgentData?.platform ||
+ navigator.platform ||
+ navigator.userAgent ||
+ "";
+ const p = platform.toLowerCase();
+ if (p.includes("win")) return "windows";
+ if (p.includes("linux") || p.includes("x11")) return "linux";
+ return "macos";
+}
+
+export default function NoCodingAgents({ compact = false }: NoCodingAgentsProps) {
+ const [activeVendor, setActiveVendor] = useState<VendorId>("claude-code");
+ // Initialize from the browser's reported platform so the snippet
+ // matches the user's machine on first paint. They can flip it via
+ // the OS cards if their dev box differs from the browser host.
+ const [activeOs, setActiveOs] = useState<OsId>("macos");
+ const [copied, setCopied] = useState(false);
+ const [otlpEndpoint, setOtlpEndpoint] = useState(DEFAULT_OTLP_ENDPOINT);
+
+ useEffect(() => {
+ setActiveOs(detectOs());
+ }, []);
+
+ const pingStatus = useRootStore(getPingStatus);
+ const { data: apiKeys, fireRequest: fetchKeys } = useFetchWrapper<ApiKey[]>();
+ const { fireRequest: createKey, isLoading: isCreatingKey } =
+ useFetchWrapper<{ apiKey: string }>();
+
+ // Derive the OTLP endpoint from the dashboard origin on mount. We
+ // only run this on the client because window.location isn't defined
+ // during SSR.
+ useEffect(() => {
+ if (typeof window !== "undefined") {
+ setOtlpEndpoint(buildOtlpEndpoint(window.location.origin));
+ }
+ }, []);
+
+ const refreshKeys = useCallback(() => {
+ fetchKeys({ requestType: "GET", url: "/api/api-key" });
+ }, [fetchKeys]);
+
+ useEffect(() => {
+ if (pingStatus !== "pending") refreshKeys();
+ }, [pingStatus, refreshKeys]);
+
+ useEffect(() => {
+ if (!copied) return;
+ const id = window.setTimeout(() => setCopied(false), 1800);
+ return () => window.clearTimeout(id);
+ }, [copied]);
+
+ const firstKey =
+ apiKeys && apiKeys.length > 0 ? apiKeys[0].apiKey : undefined;
+
+ const vendor = useMemo(
+ () => VENDORS.find((v) => v.id === activeVendor) || VENDORS[0],
+ [activeVendor]
+ );
+
+ // Single-line, OS-appropriate-joiner command so the snippet
+ // copy-pastes into one shell invocation — matches the
+ // Lapdog-style brevity the team asked for. The three logical
+ // steps (install the CLI, persist endpoint+API key to
+ // ~/.config/openlit/config.env via `configure`, then wire the
+ // vendor hooks) all still need to run; chaining them keeps the
+ // failure semantics tight without forcing three separate pastes.
+ //
+ // We invoke openlit by its full path on Linux/Windows because
+ // the install step's PATH update doesn't reach the current
+ // shell — only NEW shells pick it up. See bootstrapForOs for
+ // the per-OS reasoning.
+ const snippet = useMemo(() => {
+ const apiKeyValue = firstKey || API_KEY_PLACEHOLDER;
+ const { install, activate, joiner } = bootstrapForOs(activeOs);
+ return [
+ install,
+ activate,
+ `openlit configure --endpoint "${otlpEndpoint}" --api-key "${apiKeyValue}"`,
+ `openlit coding install --vendor=${vendor.cliFlag}`,
+ ]
+ .filter(Boolean)
+ .join(joiner);
+ }, [firstKey, otlpEndpoint, vendor, activeOs]);
+
+ const handleCopy = () => {
+ copy(snippet);
+ setCopied(true);
+ };
+
+ const handleGenerateKey = useCallback(() => {
+ toast.loading("Generating API key…", { id: "coding-agents-api-key" });
+ createKey({
+ requestType: "POST",
+ url: "/api/api-key",
+ body: JSON.stringify({ name: GENERATED_API_KEY_NAME }),
+ successCb: () => {
+ toast.success("API key created — pre-filled into the snippet.", {
+ id: "coding-agents-api-key",
+ });
+ refreshKeys();
+ },
+ failureCb: (err?: string) => {
+ toast.error(err || "Could not generate API key", {
+ id: "coding-agents-api-key",
+ });
+ },
+ });
+ }, [createKey, refreshKeys]);
+
+ return (
+ <div
+ className={`flex flex-col items-center w-full ${compact ? "py-6 px-1" : "justify-center py-12 px-4"}`}
+ >
+ <div className="max-w-2xl w-full">
+ {!compact && (
+ <div className="flex flex-col items-center mb-8">
+ <div className="w-16 h-16 bg-stone-100 dark:bg-stone-800 rounded-full flex items-center justify-center mb-4">
+ <BotMessageSquare className="w-8 h-8 text-stone-500 dark:text-stone-400" />
+ </div>
+ <h2 className="text-2xl font-semibold text-stone-700 dark:text-stone-200 mb-2">
+ Track your coding agents
+ </h2>
+ </div>
+ )}
+
+ {firstKey ? (
+ <div className="flex items-start gap-3 mb-4 p-3 rounded-lg border border-emerald-200 dark:border-emerald-800 bg-emerald-50 dark:bg-emerald-950/30">
+ <KeyRound className="w-4 h-4 text-emerald-600 dark:text-emerald-400 mt-0.5 shrink-0" />
+ <p className="text-sm text-emerald-700 dark:text-emerald-300">
+ Snippet is pre-filled with your API key and this
+ dashboard&apos;s OTLP endpoint. The CLI will
+ authenticate automatically.
+ </p>
+ </div>
+ ) : (
+ <div className="flex items-start justify-between gap-3 mb-4 p-3 rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/30">
+ <div className="flex items-start gap-3">
+ <KeyRound className="w-4 h-4 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />
+ <p className="text-sm text-amber-700 dark:text-amber-300">
+ No API key found. Generate one to pre-fill the
+ snippet — the CLI needs it to authenticate
+ OTLP exports.
+ </p>
+ </div>
+ <button
+ onClick={handleGenerateKey}
+ disabled={isCreatingKey}
+ className="shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md bg-amber-600 hover:bg-amber-700 disabled:opacity-60 disabled:cursor-not-allowed text-white transition-colors"
+ >
+ {isCreatingKey ? (
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ ) : (
+ <KeyRound className="w-3.5 h-3.5" />
+ )}
+ Generate API key
+ </button>
+ </div>
+ )}
+
+ <div className="grid grid-cols-3 gap-2 mb-4">
+ {OS_OPTIONS.map((os) => {
+ const isActive = activeOs === os.id;
+ const Icon = os.icon;
+ return (
+ <button
+ key={os.id}
+ onClick={() => setActiveOs(os.id)}
+ className={`flex flex-col items-center justify-center gap-1.5 rounded-lg border px-3 py-3 transition-colors ${
+ isActive
+ ? "border-stone-900 dark:border-stone-100 bg-stone-100 dark:bg-stone-800 text-stone-900 dark:text-stone-100"
+ : "border-stone-200 dark:border-stone-700 text-stone-500 dark:text-stone-400 hover:border-stone-300 dark:hover:border-stone-600 hover:text-stone-700 dark:hover:text-stone-300"
+ }`}
+ >
+ <Icon className="w-5 h-5" />
+ <span className="text-xs font-medium">{os.label}</span>
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="border dark:border-stone-800 rounded-lg overflow-hidden">
+ <div className="flex flex-wrap border-b border-stone-200 dark:border-stone-700">
+ {VENDORS.map((v) => {
+ const isActive = activeVendor === v.id;
+ const hasIcon = hasCodingAgentVendorIcon(v.id);
+ return (
+ <button
+ key={v.id}
+ onClick={() => setActiveVendor(v.id)}
+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
+ isActive
+ ? "bg-stone-100 dark:bg-stone-800 text-stone-900 dark:text-stone-100 border-b-2 border-stone-900 dark:border-stone-100"
+ : "text-stone-500 dark:text-stone-400 hover:text-stone-700 dark:hover:text-stone-300"
+ }`}
+ >
+ {hasIcon && (
+ <CodingAgentVendorIcon
+ vendor={v.id}
+ className="w-4 h-4"
+ />
+ )}
+ {v.label}
+ </button>
+ );
+ })}
+ </div>
+ <div className="p-4 space-y-3 bg-stone-50 dark:bg-stone-900">
+ <div className="relative rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 p-4">
+ <button
+ onClick={handleCopy}
+ className="absolute top-2.5 right-2.5 p-1.5 rounded-md text-stone-400 hover:text-stone-700 dark:hover:text-stone-200 hover:bg-stone-100 dark:hover:bg-stone-800 transition-colors"
+ title="Copy commands"
+ >
+ {copied ? (
+ <Check className="w-4 h-4 text-emerald-500" />
+ ) : (
+ <Copy className="w-4 h-4" />
+ )}
+ </button>
+ <pre className="text-xs font-mono text-stone-700 dark:text-stone-300 whitespace-pre-wrap break-all pr-8 leading-relaxed">
+ {snippet}
+ </pre>
+ </div>
+ <div className="rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950 p-3 text-xs text-stone-700 dark:text-stone-300">
+ <p className="font-medium text-stone-900 dark:text-stone-100 mb-1.5">
+ After running the snippet
+ </p>
+ <ol className="list-decimal pl-4 space-y-1">
+ <li>{vendor.postInstall.restart}</li>
+ {(vendor.postInstall.extraSteps || []).map((step, i) => (
+ <li key={i}>{step}</li>
+ ))}
+ <li>Send any prompt in {vendor.label}.</li>
+ </ol>
+ </div>
+
+ <p className="text-xs text-stone-500 dark:text-stone-500">
+ Full reference (env vars, content-capture modes,
+ marketplace install):{" "}
+ <a
+ href="https://docs.openlit.io/latest/features/coding-agents/onboarding"
+ target="_blank"
+ rel="noreferrer"
+ className="text-primary hover:underline"
+ >
+ coding-agents onboarding
+ </a>
+ .
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/src/app/(playground)/agents/page.tsx b/src/client/src/app/(playground)/agents/page.tsx
index 6d451c47..e37ee80a 100644
--- a/src/client/src/app/(playground)/agents/page.tsx
+++ b/src/client/src/app/(playground)/agents/page.tsx
@@ -17,6 +17,10 @@ import { getPingStatus } from "@/selectors/database-config";
import { TIME_RANGE_TYPE } from "@/store/filter";
import type { ControllerInstance } from "@/types/controller";
import type { UnifiedAgent } from "@/types/agents";
+import {
+ isControllerStale,
+ resolveControllerHealth,
+} from "@/lib/platform/controller/health";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -29,17 +33,27 @@ import ComboDropdown from "@/components/(playground)/filter/combo-dropdown";
import Filter from "@/components/(playground)/filter";
import getMessage from "@/constants/messages";
import NoController from "./no-controller";
+import NoCodingAgents from "./no-coding-agents";
import ServiceTable from "./service-table";
import ControllerTable from "./controller-table";
+import CodingAgentsTable from "./coding-agents-table";
+
+type Tab = "services" | "controllers" | "coding";
-type Tab = "services" | "controllers";
+function coerceTab(value: string | null): Tab {
+ if (value === "controllers") return "controllers";
+ if (value === "coding") return "coding";
+ return "services";
+}
export default function AgentsPage() {
const searchParams = useSearchParams();
const router = useRouter();
- const initialTab = searchParams.get("tab") === "controllers" ? "controllers" : "services";
+ const initialTab = coerceTab(searchParams.get("tab"));
const [activeTab, setActiveTabState] = useState<Tab>(initialTab);
- const [showSetupModal, setShowSetupModal] = useState(false);
+ const [setupModal, setSetupModal] = useState<null | "controller" | "coding">(
+ null
+ );
const [serviceRows, setServiceRows] = useState<UnifiedAgent[]>([]);
const [controllerRows, setControllerRows] = useState<ControllerInstance[]>([]);
const [nextCursor, setNextCursor] = useState<string | null>(null);
@@ -48,6 +62,9 @@ export default function AgentsPage() {
const [systemFilter, setSystemFilter] = useState<string[]>([]);
const [providerFilter, setProviderFilter] = useState<string[]>([]);
const [statusFilter, setStatusFilter] = useState<string[]>([]);
+ const [controllerHealthFilter, setControllerHealthFilter] = useState<
+ string[]
+ >([]);
const [refreshError, setRefreshError] = useState<string | null>(null);
const setActiveTab = useCallback((tab: Tab) => {
@@ -63,10 +80,21 @@ export default function AgentsPage() {
}, [router]);
useEffect(() => {
- const tab = searchParams.get("tab") === "controllers" ? "controllers" : "services";
- setActiveTabState(tab);
+ setActiveTabState(coerceTab(searchParams.get("tab")));
}, [searchParams]);
+ // Auto-redirect to the Coding Agents tab when it's the only place
+ // with data. Without this, a user with no controllers and no SDK
+ // rows lands on an empty Applications tab and has to discover the
+ // "Coding Agents" tab themselves — a bad first-run experience for
+ // anyone who installed the host plugins before the controller.
+ // Only fires:
+ // - when the URL didn't pin a tab (so we don't fight the user's
+ // navigation),
+ // - while the apps view is empty AND the coding view has rows,
+ // - exactly once after data first lands.
+ const didAutoRouteRef = useRef(false);
+
const pathname = usePathname();
const filter = useRootStore(getFilterDetails);
const updateFilter = useRootStore(getUpdateFilter);
@@ -84,7 +112,7 @@ export default function AgentsPage() {
const [servicesFetched, setServicesFetched] = useState(false);
const fetchAgents = useCallback(
- async (cursor: string | null) => {
+ async (cursor: string | null, source?: "coding") => {
const params = new URLSearchParams();
if (filter.timeLimit.start)
params.set("start", new Date(filter.timeLimit.start).toISOString());
@@ -99,11 +127,23 @@ export default function AgentsPage() {
params.set("end", new Date(filter.timeLimit.end).toISOString());
}
if (cursor) params.set("cursor", cursor);
- if (providerFilter.length > 0) {
- params.set("providers", providerFilter.join(","));
+ // Provider/status filters describe application instrumentation
+ // (discovered vs instrumented vs SDK-only). They apply only to
+ // the Applications tab fetch — not coding-agent rows.
+ if (source !== "coding") {
+ if (providerFilter.length > 0) {
+ params.set("providers", providerFilter.join(","));
+ }
+ if (statusFilter.length > 0) {
+ params.set("statuses", statusFilter.join(","));
+ }
}
- if (statusFilter.length > 0) {
- params.set("statuses", statusFilter.join(","));
+ // `source=coding` is required to fetch coding-agent rows;
+ // without it the API returns only Apps rows. This split is
+ // what keeps coding rows from ever appearing in the Apps
+ // tab, even for one render frame.
+ if (source) {
+ params.set("source", source);
}
const res = await fetch(`/api/agents?${params.toString()}`);
if (!res.ok) {
@@ -124,6 +164,8 @@ export default function AgentsPage() {
]
);
+ const [codingRowsState, setCodingRowsState] = useState<UnifiedAgent[]>([]);
+
const refresh = useCallback(() => {
setRefreshError(null);
fetchInstances({
@@ -136,13 +178,26 @@ export default function AgentsPage() {
failureCb: (err: any) => setRefreshError(String(err)),
});
setServicesLoading(true);
- fetchAgents(null)
- .then((payload) => {
- setServiceRows(payload.data || []);
- setNextCursor(payload.nextCursor || null);
+ // Two parallel reads: Apps (default — server excludes coding)
+ // and Coding Agents (?source=coding). Settling them
+ // independently keeps a slow coding-rollup query from blocking
+ // the Apps tab from rendering, and vice versa.
+ Promise.allSettled([
+ fetchAgents(null),
+ fetchAgents(null, "coding"),
+ ])
+ .then(([apps, coding]) => {
+ if (apps.status === "fulfilled") {
+ setServiceRows(apps.value.data || []);
+ setNextCursor(apps.value.nextCursor || null);
+ } else {
+ setRefreshError(String(apps.reason));
+ }
+ if (coding.status === "fulfilled") {
+ setCodingRowsState(coding.value.data || []);
+ }
setServicesFetched(true);
})
- .catch((err: unknown) => setRefreshError(String(err)))
.finally(() => setServicesLoading(false));
}, [fetchInstances, fetchAgents]);
@@ -350,12 +405,61 @@ export default function AgentsPage() {
const isLoading = instancesLoading || servicesLoading;
const hasControllers = controllerRows.length > 0;
+ // Coding-agent rows live on a dedicated tab and a dedicated fetch
+ // (`?source=coding`). The Apps tab gets the default fetch which
+ // the server filters to controller/sdk/both. We still defensively
+ // strip any coding row that somehow ends up in `serviceRows`
+ // (e.g. an older browser tab whose API filter regressed) by
+ // double-checking both `source` and the synthetic `coding` cluster
+ // id we stamp at materialization time.
+ // Coding-only first-run redirect. We wait for `servicesFetched` so
+ // we don't bounce the tab on the first paint before either fetch
+ // has resolved. Once data lands and the only signal is coding
+ // telemetry, switch the user to that tab and pin it via
+ // `setActiveTab` (which also writes ?tab=coding into the URL so a
+ // browser refresh stays put).
+ useEffect(() => {
+ if (didAutoRouteRef.current) return;
+ if (!servicesFetched) return;
+ if (searchParams.get("tab")) return;
+ const onlyCoding =
+ !hasControllers &&
+ serviceRows.length === 0 &&
+ codingRowsState.length > 0;
+ if (onlyCoding) {
+ didAutoRouteRef.current = true;
+ setActiveTab("coding");
+ }
+ }, [
+ servicesFetched,
+ hasControllers,
+ serviceRows.length,
+ codingRowsState.length,
+ searchParams,
+ setActiveTab,
+ ]);
+
+ const applicationRows = useMemo(
+ () =>
+ serviceRows.filter(
+ (s) => s.source !== "coding" && s.cluster_id !== "coding"
+ ),
+ [serviceRows]
+ );
+ const codingRows = codingRowsState;
+
+ // Legacy controller / service stats. These power the top cards on
+ // the Applications and Controllers tabs — the original surface
+ // the hub was built around. Restored after a brief stint of
+ // "always show coding stats at the top" that turned out to be
+ // the wrong call: when a user is on Applications, they want the
+ // applications-side rollup at a glance, not coding metrics.
const activeControllers = controllerRows.filter(
- (c) => (c.computed_status || c.status) !== "inactive"
+ (c) => !isControllerStale(c)
);
const staleCount = controllerRows.length - activeControllers.length;
- const totalServices = serviceRows.length;
- const instrumentedServices = serviceRows.filter(
+ const totalServices = applicationRows.length;
+ const instrumentedServices = applicationRows.filter(
(s) =>
s.source === "sdk" ||
s.source === "both" ||
@@ -363,6 +467,30 @@ export default function AgentsPage() {
s.desired_agent_status === "enabled"
).length;
+ // Coding-agent rollups for the Coding Agents tab's top stat
+ // cards. We compute these from the same `codingRows` the table
+ // renders so the numbers can never disagree with the per-vendor
+ // breakdown a click away. One row per vendor, so
+ // `codingRows.length` is the unique-vendor count without needing
+ // a set. The users sum can over-count when a single human uses
+ // multiple vendors; the hint copy calls that out instead of
+ // pretending we have a dedup'd identity graph on the client (the
+ // platform-side directory does run a true distinct count, but
+ // that's a separate API hop we don't need for a stat glance).
+ const codingVendorsUsed = codingRows.filter(
+ (r) =>
+ (r.coding_session_count_24h ?? 0) > 0 ||
+ (r.coding_active_users_24h ?? 0) > 0
+ ).length;
+ const codingTotalCost = codingRows.reduce(
+ (sum, r) => sum + (r.coding_cost_usd_24h ?? 0),
+ 0
+ );
+ const codingTotalUsers = codingRows.reduce(
+ (sum, r) => sum + (r.coding_active_users_24h ?? 0),
+ 0
+ );
+
const allProviders = useMemo(() => {
const set = new Set<string>();
for (const svc of serviceRows) {
@@ -379,7 +507,52 @@ export default function AgentsPage() {
return Array.from(set).sort();
}, [controllerRows]);
- const handleStatClick = (stat: "controllers" | "discovered" | "instrumented") => {
+ const filteredControllerRows = useMemo(() => {
+ if (controllerHealthFilter.length === 0) return controllerRows;
+ return controllerRows.filter((row) =>
+ controllerHealthFilter.includes(resolveControllerHealth(row))
+ );
+ }, [controllerRows, controllerHealthFilter]);
+
+ const controllerHealthOptions = useMemo(() => {
+ const options = [
+ {
+ value: "active",
+ label: getMessage().AGENTS_FILTER_CONTROLLER_ACTIVE,
+ },
+ {
+ value: "healthy",
+ label: getMessage().AGENTS_FILTER_CONTROLLER_HEALTHY,
+ },
+ {
+ value: "degraded",
+ label: getMessage().AGENTS_FILTER_CONTROLLER_DEGRADED,
+ },
+ {
+ value: "inactive",
+ label: getMessage().AGENTS_FILTER_CONTROLLER_STALE,
+ },
+ ];
+ const hasError = controllerRows.some(
+ (row) => resolveControllerHealth(row) === "error"
+ );
+ if (hasError) {
+ options.push({
+ value: "error",
+ label: getMessage().AGENTS_FILTER_CONTROLLER_ERROR,
+ });
+ }
+ return options;
+ }, [controllerRows]);
+
+ // Per-stat click targets for the legacy (Applications /
+ // Controllers) stat row. Controllers cards routes to the
+ // controllers tab; the two service-side cards route to
+ // Applications and optionally apply the "instrumented" status
+ // filter so the table reflects what the user just clicked.
+ const handleLegacyStatClick = (
+ stat: "controllers" | "discovered" | "instrumented",
+ ) => {
if (stat === "controllers") {
setActiveTab("controllers");
} else if (stat === "discovered") {
@@ -391,6 +564,11 @@ export default function AgentsPage() {
}
};
+ // All three coding stat cards route to the same Coding Agents
+ // tab — there's no per-stat filter to apply because the table
+ // already shows the per-vendor breakdown.
+ const handleCodingStatClick = () => setActiveTab("coding");
+
const updateFilterValues = useCallback(
(type: string, value: string, operationType?: string) => {
const setter =
@@ -398,7 +576,9 @@ export default function AgentsPage() {
? setSystemFilter
: type === "provider"
? setProviderFilter
- : setStatusFilter;
+ : type === "controllerHealth"
+ ? setControllerHealthFilter
+ : setStatusFilter;
setter((prev) =>
operationType === "delete"
? prev.filter((v) => v !== value)
@@ -414,7 +594,9 @@ export default function AgentsPage() {
? setSystemFilter
: type === "provider"
? setProviderFilter
- : setStatusFilter;
+ : type === "controllerHealth"
+ ? setControllerHealthFilter
+ : setStatusFilter;
setter([]);
}, []);
@@ -424,7 +606,12 @@ export default function AgentsPage() {
<div className="flex items-center w-full gap-4">
<Filter />
<div className="flex items-center gap-2 shrink-0">
- {hasControllers && allSystems.length > 0 && (
+ {/* System / provider / status filters target application
+ instrumentation. Hide them on Coding Agents and
+ Controllers — they either don't apply to those tables
+ or use the wrong semantics (e.g. "Discovered" on a
+ coding vendor row). */}
+ {activeTab === "services" && hasControllers && allSystems.length > 0 && (
<ComboDropdown
title={getMessage().AGENTS_FILTER_SYSTEM}
options={allSystems.map((s) => ({
@@ -442,7 +629,7 @@ export default function AgentsPage() {
clearItem={clearFilterItem}
/>
)}
- {hasControllers && allProviders.length > 0 && (
+ {activeTab === "services" && hasControllers && allProviders.length > 0 && (
<ComboDropdown
title={getMessage().AGENTS_FILTER_PROVIDER}
options={allProviders.map((p) => ({
@@ -455,7 +642,8 @@ export default function AgentsPage() {
clearItem={clearFilterItem}
/>
)}
- {(hasControllers || serviceRows.length > 0) && (
+ {activeTab === "services" &&
+ (hasControllers || serviceRows.length > 0) && (
<ComboDropdown
title={getMessage().AGENTS_FILTER_STATUS}
options={[
@@ -478,6 +666,16 @@ export default function AgentsPage() {
clearItem={clearFilterItem}
/>
)}
+ {activeTab === "controllers" && controllerRows.length > 0 && (
+ <ComboDropdown
+ title={getMessage().AGENTS_FILTER_CONTROLLER_HEALTH}
+ options={controllerHealthOptions}
+ selectedValues={controllerHealthFilter}
+ type="controllerHealth"
+ updateSelectedValues={updateFilterValues}
+ clearItem={clearFilterItem}
+ />
+ )}
<button
onClick={refresh}
disabled={isLoading}
@@ -496,57 +694,130 @@ export default function AgentsPage() {
</div>
)}
- {!hasControllers && serviceRows.length === 0 && !isLoading ? (
- <NoController />
- ) : (
+ {/*
+ * Empty state is now per-tab. Previously a hub-wide
+ * `NoController` swallowed the entire viewport when every
+ * source was empty, which forced a user with only coding
+ * telemetry to discover the Coding Agents tab via the
+ * auto-route effect. The new model:
+ * - Applications tab → NoController (the original
+ * install-the-controller flow) when 0 application rows.
+ * - Coding Agents tab → NoCodingAgents (vendor picker
+ * with `openlit coding install --vendor=<v>` snippets).
+ * - Controllers tab → NoController when 0 controllers.
+ * The stat cards / tab bar always render so the user can
+ * switch tabs and see the right onboarding for whatever
+ * they're actually trying to do.
+ */}
+ {(
<>
- {/* Stat cards */}
- <div className="grid grid-cols-3 gap-4">
- <button
- onClick={() => handleStatClick("controllers")}
- className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
- >
- <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100">
- {activeControllers.length}
- {staleCount > 0 && (
- <span className="text-sm font-normal text-stone-400 dark:text-stone-500 ml-1.5">
- ({staleCount} stale)
- </span>
- )}
- </div>
- <div className="text-sm text-stone-500 dark:text-stone-400">
- {getMessage().AGENTS_STAT_CONTROLLERS}
- </div>
- </button>
- <button
- onClick={() => handleStatClick("discovered")}
- className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
- >
- <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100">
- {totalServices}
- </div>
- <div className="text-sm text-stone-500 dark:text-stone-400">
- {getMessage().AGENTS_STAT_DISCOVERED_SERVICES}
- </div>
- </button>
- <button
- onClick={() => handleStatClick("instrumented")}
- className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
- >
- <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100">
- {instrumentedServices}
- </div>
- <div className="text-sm text-stone-500 dark:text-stone-400">
- {getMessage().AGENTS_STAT_INSTRUMENTED_SERVICES}
- </div>
- </button>
- </div>
+ {/* Top-of-page stat cards. Tab-aware: the Coding
+ Agents tab gets vendor/cost/user rollups
+ derived from `codingRows`, every other tab
+ keeps the legacy controller/service stats so
+ the glance metric matches whatever the user
+ is looking at below. Layout (grid-cols-3) is
+ identical across both modes so the section
+ height doesn't jump on tab switch. */}
+ {activeTab === "coding" ? (
+ /* Layout, padding, and typography match the
+ legacy controller/service stat row exactly
+ so the section doesn't visibly resize on
+ tab switch — number + label only, no
+ subtitle line. Order is Total Coding
+ agents → Total users → Total cost. */
+ <div className="grid grid-cols-3 gap-4">
+ <button
+ onClick={handleCodingStatClick}
+ className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
+ >
+ <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100">
+ {codingVendorsUsed}
+ </div>
+ <div className="text-sm text-stone-500 dark:text-stone-400">
+ {getMessage().AGENTS_STAT_CODING_VENDORS}
+ </div>
+ </button>
+ <button
+ onClick={handleCodingStatClick}
+ className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
+ >
+ <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100 tabular-nums">
+ {codingTotalUsers.toLocaleString()}
+ </div>
+ <div className="text-sm text-stone-500 dark:text-stone-400">
+ {getMessage().AGENTS_STAT_CODING_USERS}
+ </div>
+ </button>
+ <button
+ onClick={handleCodingStatClick}
+ className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
+ >
+ <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100 tabular-nums">
+ ${codingTotalCost.toFixed(2)}
+ </div>
+ <div className="text-sm text-stone-500 dark:text-stone-400">
+ {getMessage().AGENTS_STAT_CODING_COST}
+ </div>
+ </button>
+ </div>
+ ) : (
+ <div className="grid grid-cols-3 gap-4">
+ <button
+ onClick={() => handleLegacyStatClick("controllers")}
+ className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
+ >
+ <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100">
+ {activeControllers.length}
+ {staleCount > 0 && (
+ <span className="text-sm font-normal text-stone-400 dark:text-stone-500 ml-1.5">
+ ({staleCount} stale)
+ </span>
+ )}
+ </div>
+ <div className="text-sm text-stone-500 dark:text-stone-400">
+ {getMessage().AGENTS_STAT_CONTROLLERS}
+ </div>
+ </button>
+ <button
+ onClick={() => handleLegacyStatClick("discovered")}
+ className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
+ >
+ <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100">
+ {totalServices}
+ </div>
+ <div className="text-sm text-stone-500 dark:text-stone-400">
+ {getMessage().AGENTS_STAT_DISCOVERED_SERVICES}
+ </div>
+ </button>
+ <button
+ onClick={() => handleLegacyStatClick("instrumented")}
+ className="border dark:border-stone-800 rounded-lg p-4 text-left transition-colors hover:bg-stone-50 dark:hover:bg-stone-800/50"
+ >
+ <div className="text-2xl font-semibold text-stone-900 dark:text-stone-100">
+ {instrumentedServices}
+ </div>
+ <div className="text-sm text-stone-500 dark:text-stone-400">
+ {getMessage().AGENTS_STAT_INSTRUMENTED_SERVICES}
+ </div>
+ </button>
+ </div>
+ )}
- {/* Tab switcher */}
+ {/* Tab switcher. Ordering reflects expected
+ usage frequency: most teams will spend most
+ of their time on Applications and Coding
+ Agents; Controllers is a setup-time tab. We
+ drop the count badge from Coding Agents
+ intentionally — the tab name carries the
+ affordance and the row count is already on
+ the table itself; the badge was creating
+ visual noise on the most-clicked tab. */}
<div className="flex items-center border-b border-stone-200 dark:border-stone-700">
{(
[
{ id: "services", label: getMessage().AGENTS_TAB_SERVICES },
+ { id: "coding", label: getMessage().AGENTS_TAB_CODING },
{ id: "controllers", label: getMessage().AGENTS_TAB_CONTROLLERS },
] as const
).map((tab) => (
@@ -555,7 +826,7 @@ export default function AgentsPage() {
onClick={() => {
setActiveTab(tab.id);
}}
- className={`px-4 py-2.5 text-sm font-medium transition-colors border-b-2 ${
+ className={`px-4 py-2.5 text-sm font-medium transition-colors border-b-2 inline-flex items-center gap-1.5 ${
activeTab === tab.id
? "border-stone-900 dark:border-stone-100 text-stone-900 dark:text-stone-100"
: "border-transparent text-stone-500 dark:text-stone-400 hover:text-stone-700 dark:hover:text-stone-300"
@@ -569,61 +840,121 @@ export default function AgentsPage() {
variant="outline"
size="default"
className="ml-auto text-xs h-auto py-1.5 px-3"
- onClick={() => setShowSetupModal(true)}
+ onClick={() => setSetupModal("controller")}
>
<Plus className="w-3 h-3 mr-1.5" />
{getMessage().AGENTS_ADD_CONTROLLER}
</Button>
)}
+ {activeTab === "coding" && (
+ <Button
+ variant="outline"
+ size="default"
+ className="ml-auto text-xs h-auto py-1.5 px-3"
+ onClick={() => setSetupModal("coding")}
+ >
+ <Plus className="w-3 h-3 mr-1.5" />
+ {getMessage().AGENTS_ADD_CODING_AGENT}
+ </Button>
+ )}
</div>
- {/* Content */}
+ {/* Content. Each tab owns its own empty state so
+ the install instructions match the tab — a
+ user landing on Coding Agents shouldn't see
+ a Kubernetes/Docker controller picker, and
+ vice versa. */}
{activeTab === "services" && (
<>
- <ServiceTable
- services={serviceRows}
- instances={controllerRows}
- onRefresh={refresh}
- isFetched={servicesFetched && instancesFetched}
- isLoading={isLoading}
- systemFilter={systemFilter}
- />
- {nextCursor && (
- <div className="flex justify-center pt-2">
- <button
- onClick={loadMore}
- disabled={isLoadingMore}
- className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-md border border-stone-200 dark:border-stone-700 text-stone-700 dark:text-stone-200 hover:bg-stone-50 dark:hover:bg-stone-800 transition-colors disabled:opacity-50"
- >
- {isLoadingMore && <RefreshCw className="w-3.5 h-3.5 animate-spin" />}
- {isLoadingMore
- ? getMessage().AGENTS_LOAD_MORE_LOADING
- : getMessage().AGENTS_LOAD_MORE}
- </button>
- </div>
+ {servicesFetched &&
+ !isLoading &&
+ applicationRows.length === 0 ? (
+ <NoController />
+ ) : (
+ <>
+ <ServiceTable
+ services={applicationRows}
+ instances={controllerRows}
+ onRefresh={refresh}
+ isFetched={servicesFetched && instancesFetched}
+ isLoading={isLoading}
+ systemFilter={systemFilter}
+ />
+ {nextCursor && (
+ <div className="flex justify-center pt-2">
+ <button
+ onClick={loadMore}
+ disabled={isLoadingMore}
+ className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-md border border-stone-200 dark:border-stone-700 text-stone-700 dark:text-stone-200 hover:bg-stone-50 dark:hover:bg-stone-800 transition-colors disabled:opacity-50"
+ >
+ {isLoadingMore && <RefreshCw className="w-3.5 h-3.5 animate-spin" />}
+ {isLoadingMore
+ ? getMessage().AGENTS_LOAD_MORE_LOADING
+ : getMessage().AGENTS_LOAD_MORE}
+ </button>
+ </div>
+ )}
+ </>
)}
</>
)}
{activeTab === "controllers" && (
- <ControllerTable
- instances={controllerRows}
- isFetched={instancesFetched}
- isLoading={instancesLoading}
- />
+ <>
+ {instancesFetched &&
+ !instancesLoading &&
+ controllerRows.length === 0 ? (
+ <NoController />
+ ) : (
+ <ControllerTable
+ instances={filteredControllerRows}
+ isFetched={instancesFetched}
+ isLoading={instancesLoading}
+ />
+ )}
+ </>
+ )}
+
+ {activeTab === "coding" && (
+ <>
+ {servicesFetched &&
+ !isLoading &&
+ codingRows.length === 0 ? (
+ <NoCodingAgents />
+ ) : (
+ <CodingAgentsTable
+ services={codingRows}
+ isFetched={servicesFetched}
+ isLoading={isLoading}
+ />
+ )}
+ </>
)}
</>
)}
- <Dialog open={showSetupModal} onOpenChange={setShowSetupModal}>
+ <Dialog
+ open={setupModal !== null}
+ onOpenChange={(open) => !open && setSetupModal(null)}
+ >
<DialogContent className="max-w-2xl">
<DialogHeader>
- <DialogTitle>{getMessage().AGENTS_ADD_CONTROLLER}</DialogTitle>
+ <DialogTitle>
+ {setupModal === "coding"
+ ? getMessage().AGENTS_ADD_CODING_AGENT
+ : getMessage().AGENTS_ADD_CONTROLLER}
+ </DialogTitle>
<DialogDescription>
- {getMessage().AGENTS_NO_CONTROLLERS_DESCRIPTION}
+ {setupModal === "coding"
+ ? getMessage().AGENTS_NO_CODING_AGENTS_DESCRIPTION
+ : getMessage().AGENTS_NO_CONTROLLERS_DESCRIPTION}
</DialogDescription>
</DialogHeader>
- <NoController inModal />
+ {setupModal === "coding" ? (
+ <NoCodingAgents compact />
+ ) : (
+ <NoController inModal />
+ )}
</DialogContent>
</Dialog>
</div>
diff --git a/src/client/src/app/(playground)/agents/service-table.tsx b/src/client/src/app/(playground)/agents/service-table.tsx
index efc7d8b4..da7f8057 100644
--- a/src/client/src/app/(playground)/agents/service-table.tsx
+++ b/src/client/src/app/(playground)/agents/service-table.tsx
@@ -403,7 +403,7 @@ const columns: Columns<ServiceColumnKey, EnrichedAgent> = {
cell: ({ row }) => (
<div className="flex items-center gap-2 overflow-hidden">
<Link
- href={`/agents/${row.agent_key}`}
+ href={`/agents/${row.agent_key}?from=services`}
className="font-medium text-stone-900 dark:text-stone-100 hover:underline truncate"
onClick={(e) => e.stopPropagation()}
>
@@ -482,29 +482,20 @@ const columns: Columns<ServiceColumnKey, EnrichedAgent> = {
</div>
),
cell: ({ row, extraFunctions }) => (
- <ActionsCell
- service={row}
- onRefresh={extraFunctions.onRefresh}
- />
+ <ActionsCell service={row} onRefresh={extraFunctions.onRefresh} />
),
enableHiding: false,
},
aiObservability: {
header: () => getMessage().AGENTS_COLUMN_LLM_OBSERVABILITY,
cell: ({ row, extraFunctions }) => (
- <AIObservabilityCell
- service={row}
- onRefresh={extraFunctions.onRefresh}
- />
+ <AIObservabilityCell service={row} onRefresh={extraFunctions.onRefresh} />
),
},
agentObservability: {
header: () => getMessage().AGENTS_COLUMN_AGENT_OBSERVABILITY,
cell: ({ row, extraFunctions }) => (
- <AgentObservabilityCell
- service={row}
- onRefresh={extraFunctions.onRefresh}
- />
+ <AgentObservabilityCell service={row} onRefresh={extraFunctions.onRefresh} />
),
},
};
@@ -579,7 +570,9 @@ export default function ServiceTable({
isLoading={isLoading}
visibilityColumns={VISIBILITY_COLUMNS}
extraFunctions={{ onRefresh }}
- onClick={(row) => router.push(`/agents/${row.agent_key}`)}
+ onClick={(row) =>
+ router.push(`/agents/${row.agent_key}?from=services`)
+ }
/>
);
}
diff --git a/src/client/src/app/(playground)/coding-agents/users/[userId]/page.tsx b/src/client/src/app/(playground)/coding-agents/users/[userId]/page.tsx
new file mode 100644
index 00000000..5dc8eb89
--- /dev/null
+++ b/src/client/src/app/(playground)/coding-agents/users/[userId]/page.tsx
@@ -0,0 +1,329 @@
+"use client";
+
+/**
+ * Per-user detail page for coding-agent activity.
+ *
+ * Just the seeded "Coding Agents" dashboard, pinned to a single
+ * developer via `pinnedUser`. No tabs, no extra cards — the user
+ * asked for the same overview surface as the main agent page, just
+ * scoped, so we deliberately keep this file thin and route everything
+ * through `<CodingDashboardTab>`.
+ *
+ * Layout mirrors the agent-detail page: a full-bleed
+ * `flex flex-col w-full h-full overflow-y-auto` shell with a header
+ * (Back link + h1 title) above the dashboard. Without this shell the
+ * embedded `<Dashboard>` widgets render at parent width only, which
+ * looked cramped (~400px) on the per-user page.
+ *
+ * Data privacy: the digest request honors `COHORT_K_FLOOR`. If the
+ * user has fewer than the floor's sessions and the caller is a
+ * non-admin viewer, we 404 here (the API returns 404; we render the
+ * "not enough activity yet" empty state).
+ */
+
+import { useEffect, useMemo, useState } from "react";
+import dynamic from "next/dynamic";
+import { useParams, useRouter, useSearchParams } from "next/navigation";
+import { ArrowLeft, Loader2, ShieldCheck } from "lucide-react";
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import getMessage from "@/constants/messages";
+import type { UnifiedAgent } from "@/types/agents";
+import { useDynamicBreadcrumbs } from "@/utils/hooks/useBreadcrumbs";
+import { useFilters } from "@/selectors/filter";
+
+// The dashboard pulls in a heavy widget runtime; lazy-load it so the
+// header breadcrumb paints immediately.
+const CodingDashboardTab = dynamic(
+ () =>
+ import(
+ "@/components/(playground)/coding-agents/coding-dashboard-tab"
+ ),
+ {
+ loading: () => (
+ <div className="flex items-center justify-center py-12 text-sm text-stone-500 dark:text-stone-400 gap-2">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ {getMessage().AGENTS_LOADING_DASHBOARD}
+ </div>
+ ),
+ ssr: false,
+ }
+);
+
+interface UserDigest {
+ user: string;
+ first_seen: string;
+ last_seen: string;
+ session_count: number;
+ tool_call_count: number;
+ cost_usd: number;
+ classification_work: number;
+ classification_personal: number;
+ classification_unknown: number;
+ classification_disputed: number;
+ top_vendors: Array<{ vendor: string; sessions: number }>;
+ // Code-impact rollups returned by getCodingUserDigest. Mirrors
+ // CodingUserDigest from the platform queries module.
+ lines_added: number;
+ lines_removed: number;
+ lines_accepted: number;
+ lines_rejected: number;
+ edit_accept_count: number;
+ edit_reject_count: number;
+ acceptance_pct: number;
+ commit_count: number;
+ pr_count: number;
+}
+
+export default function CodingAgentUserPage() {
+ // F6: Next 15 changed useParams to return string | string[] — it
+ // can't return undefined here because the file is under [userId],
+ // but typing it loose lets the same component compile under both
+ // 14 and 15 conventions without a cast.
+ const params = useParams<{ userId: string | string[] }>();
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const userId = decodeURIComponent(
+ Array.isArray(params?.userId)
+ ? params.userId[0] || ""
+ : params?.userId || ""
+ );
+ // The signal-list row-click handler stamps the originating
+ // pathname+search on `?from=`, so a click from the per-vendor
+ // detail page's Users tab gives us e.g.
+ // `/agents/<key>?tab=users`. We send the user back there if
+ // present; otherwise fall back to the global Coding Agents tab.
+ // The value is already URL-encoded by `getDetailHref`, so we
+ // decode once before passing to `<Link href>` (Next will
+ // re-encode safely).
+ const fromParam = searchParams?.get("from") || "";
+ const decodedFrom = fromParam ? decodeURIComponent(fromParam) : "";
+ const backHref = decodedFrom || "/agents?tab=coding";
+ // Pull the originating agent_key out of the `from` URL so we can
+ // scope the embedded dashboard to whichever vendor's Users tab
+ // the operator clicked through from. Shape: `/agents/<key>?…`.
+ // We don't try to reverse computeAgentKey — it's hashed and
+ // opaque — we resolve key → vendor via the agent API instead.
+ const originAgentKey = useMemo(() => {
+ if (!decodedFrom) return "";
+ const match = decodedFrom.match(/^\/agents\/([^/?#]+)/);
+ return match ? decodeURIComponent(match[1]) : "";
+ }, [decodedFrom]);
+
+ const [digest, setDigest] = useState<UserDigest | null>(null);
+ const [originVendor, setOriginVendor] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ // All coding-agent surfaces in OpenLit follow the global time
+ // range from the filter picker — there is no fixed 24h fallback
+ // on this page. We forward `since`/`until` to the digest API so
+ // the Code Impact stat row above the dashboard moves in lockstep
+ // with the widgets in `<CodingDashboardTab>` (which already reads
+ // from the same store via `useFilters`).
+ const { details: filter } = useFilters();
+ const sinceISO = useMemo(
+ () => filter.timeLimit?.start?.toISOString() ?? "",
+ [filter.timeLimit?.start]
+ );
+ const untilISO = useMemo(
+ () => filter.timeLimit?.end?.toISOString() ?? "",
+ [filter.timeLimit?.end]
+ );
+
+ // F6: register the page in the global breadcrumb trail so the
+ // shell's breadcrumbs read "Coding agents → <user>" instead of
+ // the raw URL segment. Matches the convention used by the
+ // agent detail page (`agents/[agentKey]`).
+ useDynamicBreadcrumbs(
+ {
+ title: digest?.user || userId || "User",
+ },
+ [digest?.user, userId]
+ );
+
+ useEffect(() => {
+ if (!userId) return;
+ let cancelled = false;
+ (async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const qs = new URLSearchParams();
+ if (sinceISO) qs.set("since", sinceISO);
+ if (untilISO) qs.set("until", untilISO);
+ const url = `/api/coding-agents/users/${encodeURIComponent(userId)}${
+ qs.toString() ? `?${qs.toString()}` : ""
+ }`;
+ const res = await fetch(url);
+ if (cancelled) return;
+ if (res.status === 404) {
+ setError("not_found");
+ setDigest(null);
+ return;
+ }
+ if (!res.ok) {
+ setError(`HTTP ${res.status}`);
+ return;
+ }
+ const body = await res.json();
+ setDigest(body.data as UserDigest);
+ } catch (e) {
+ if (!cancelled) setError(String(e));
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [userId, sinceISO, untilISO]);
+
+ // Resolve the origin agent_key into the vendor we should scope
+ // the dashboard to. We deliberately do this on a separate fetch
+ // (not piggybacked on the digest) because the digest is keyed by
+ // user, not vendor — only the originating page knows which
+ // coding tool's Users tab the operator was viewing. A failed
+ // lookup just falls back to the cross-vendor view, which is
+ // what the page did before this scoping was added.
+ useEffect(() => {
+ if (!originAgentKey) {
+ setOriginVendor(null);
+ return;
+ }
+ let cancelled = false;
+ (async () => {
+ try {
+ const res = await fetch(
+ `/api/agents/${encodeURIComponent(originAgentKey)}`,
+ );
+ if (!res.ok) return;
+ const body = (await res.json()) as {
+ data?: { coding_agent_vendor?: string };
+ };
+ if (cancelled) return;
+ const vendor = body?.data?.coding_agent_vendor;
+ if (vendor) setOriginVendor(vendor);
+ } catch {
+ // Best-effort. The dashboard renders cross-vendor when
+ // we can't resolve the originating vendor.
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [originAgentKey]);
+
+ // The dashboard component requires a UnifiedAgent shape but only
+ // uses `coding_agent_vendor` from it — we synthesize the minimum
+ // shape here so the embedded board renders without a real agent.
+ const stubAgent = {
+ coding_agent_vendor: "",
+ service_name: userId,
+ } as unknown as UnifiedAgent;
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-full text-sm text-stone-500 dark:text-stone-400 gap-2">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Loading user…
+ </div>
+ );
+ }
+
+ if (error === "not_found") {
+ return (
+ <div className="p-6 max-w-2xl">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="mb-3"
+ onClick={() => router.push("/agents?tab=coding")}
+ >
+ <ArrowLeft className="w-4 h-4 mr-1" /> All coding agents
+ </Button>
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base flex items-center gap-2">
+ <ShieldCheck className="w-4 h-4 text-stone-500" />
+ No public profile
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="text-sm text-stone-600 dark:text-stone-400">
+ <p>
+ This user&rsquo;s coding-agent activity is below the
+ organisation&rsquo;s privacy cohort floor, so per-user
+ detail is not available. The user will appear in the
+ directory once they accumulate enough sessions.
+ </p>
+ <p className="mt-2">
+ Org admins can always see raw user activity. Switch to an
+ owner/admin role if you need access for incident response.
+ </p>
+ </CardContent>
+ </Card>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="p-6">
+ <div className="rounded border border-red-200 dark:border-red-900/40 p-4 text-sm text-red-700 dark:text-red-400">
+ {error}
+ </div>
+ </div>
+ );
+ }
+
+ if (!digest) return null;
+
+ return (
+ <div className="flex flex-col w-full h-full gap-5 overflow-y-auto p-1 pb-8">
+ <div className="space-y-2">
+ {/* Back button + email styled to match the trace
+ full-view header (see trace-detail-page.tsx).
+ Button is the standard `outline`/`sm` 32×32
+ square; the email below it is plain mono text
+ with no leading icon. Target is the Users tab
+ the user clicked through from — we read it off
+ `?from=` (signal-list stamps the full
+ originating pathname+search there) and fall
+ back to the global Coding Agents tab when the
+ user landed via a deep link without that
+ context. */}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => router.push(backHref)}
+ className="h-8 w-8 p-0"
+ title={getMessage().AGENTS_BACK_TO_HUB}
+ aria-label={getMessage().AGENTS_BACK_TO_HUB}
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ </Button>
+ <h1 className="text-sm font-medium text-stone-900 dark:text-stone-100 font-mono">
+ {digest.user}
+ </h1>
+ </div>
+
+ <CodingDashboardTab
+ agent={stubAgent}
+ pinnedUser={digest.user}
+ /* Scope to the vendor whose Users tab the operator
+ clicked through from (recovered above by parsing
+ `?from=` and resolving the agent_key → vendor).
+ If the page was opened via a deep link with no
+ `from` context — or the agent lookup failed — we
+ pass `null` to keep the legacy cross-vendor view
+ instead of pinning to an arbitrary one. */
+ pinnedVendor={originVendor}
+ />
+ </div>
+ );
+}
diff --git a/src/client/src/app/(playground)/telemetry/page.tsx b/src/client/src/app/(playground)/telemetry/page.tsx
index 1388d141..e2f53ed2 100644
--- a/src/client/src/app/(playground)/telemetry/page.tsx
+++ b/src/client/src/app/(playground)/telemetry/page.tsx
@@ -29,6 +29,22 @@ export default function TelemetryPage() {
});
}, [activeConfig.key, posthog]);
+ // Coding Sessions / Coding Users are no longer first-class
+ // tabs on the Telemetry page — they live under /agents now.
+ // Bounce any deep link that still asks for them so we don't
+ // render a hidden tab with no way to navigate away.
+ useEffect(() => {
+ if (activeTab === "sessions" || activeTab === "coding_users") {
+ const params = new URLSearchParams(searchParams.toString());
+ params.set("tab", "traces");
+ router.replace(`/telemetry?${params.toString()}`, { scroll: false });
+ }
+ // `searchParams` is intentionally not in deps — we react to
+ // `activeTab` only; the URL update inside this effect also
+ // updates `searchParams`, which would otherwise loop.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeTab]);
+
const onTabChange = (value: string) => {
prepareObservabilitySignalChange(updateConfig, updateFilter);
const params = new URLSearchParams(searchParams.toString());
@@ -58,7 +74,20 @@ export default function TelemetryPage() {
</div>
</div>
<div className="grid grid-cols-2 gap-2 md:flex md:flex-wrap md:justify-end">
- {OBSERVABILITY_SIGNALS.map((signal) => {
+ {/* The Coding Sessions + Coding Users signal
+ configs stay registered (the per-vendor
+ detail page still embeds them via
+ <ObservabilitySignalList>), but we hide
+ them from this top nav: the Telemetry
+ page is the cross-signal generic surface,
+ and the dedicated coding-agent hub at
+ /agents is where users go for those
+ drilldowns. */}
+ {OBSERVABILITY_SIGNALS.filter(
+ (signal) =>
+ signal.key !== "sessions" &&
+ signal.key !== "coding_users",
+ ).map((signal) => {
const Icon = signal.icon;
const isActive = signal.key === activeConfig.key;
return (
diff --git a/src/client/src/app/api/agents/route.ts b/src/client/src/app/api/agents/route.ts
index 2853ffa7..8ecf4483 100644
--- a/src/client/src/app/api/agents/route.ts
+++ b/src/client/src/app/api/agents/route.ts
@@ -2,12 +2,17 @@ import { listAgents } from "@/lib/platform/agents";
import type { AgentListCursor, AgentListFilters, AgentSource } from "@/types/agents";
import { withCacheHeaders } from "./_cache";
-const ALLOWED_SOURCES = new Set<AgentSource>(["controller", "sdk", "both"]);
+// "coding" is intentionally allowed here so the Coding Agents tab can
+// pass `?source=coding` and read its rows out of the same endpoint.
+// Default behaviour (no `source` param) excludes coding rows below so
+// they can't leak into the Applications tab even for one render frame.
+const ALLOWED_SOURCES = new Set<AgentSource>(["controller", "sdk", "both", "coding"]);
const ALLOWED_STATUSES = new Set<NonNullable<AgentListFilters["statuses"]>[number]>([
"discovered",
"instrumented",
"sdk",
]);
+const APPLICATION_SOURCES: AgentSource[] = ["controller", "sdk", "both"];
function parseCsv(value: string | null): string[] {
if (!value) return [];
@@ -46,10 +51,17 @@ export async function GET(request: Request) {
return Response.json({ error: "Invalid limit" }, { status: 400 });
}
+ // When the caller doesn't pin a `source`, we exclude coding rows
+ // from the result so the Applications tab is never racy against
+ // the materializer (a brief moment where a freshly inserted coding
+ // row showed up in Apps before the client-side split filtered it
+ // out was the bug that motivated this change). The Coding Agents
+ // tab opts in via ?source=coding.
+ const sourceFilter = parseCsv(sp.get("source")).filter((v): v is AgentSource =>
+ ALLOWED_SOURCES.has(v as AgentSource)
+ );
const filters: AgentListFilters = {
- source: parseCsv(sp.get("source")).filter((v): v is AgentSource =>
- ALLOWED_SOURCES.has(v as AgentSource)
- ),
+ source: sourceFilter.length > 0 ? sourceFilter : APPLICATION_SOURCES,
environments: parseCsv(sp.get("environments")),
providers: parseCsv(sp.get("providers")),
statuses: parseCsv(sp.get("statuses")).filter((v): v is NonNullable<AgentListFilters["statuses"]>[number] =>
diff --git a/src/client/src/app/api/coding-agents/classification/dispute/route.ts b/src/client/src/app/api/coding-agents/classification/dispute/route.ts
new file mode 100644
index 00000000..b739f287
--- /dev/null
+++ b/src/client/src/app/api/coding-agents/classification/dispute/route.ts
@@ -0,0 +1,84 @@
+/**
+ * POST /api/coding-agents/classification/dispute
+ *
+ * User submits a classification dispute on a coding-agent session.
+ * The action is audit-logged regardless of payload validity (the
+ * audit row records "rejected_invalid" when the payload fails
+ * validation, so attempts at probing the API are visible to admins).
+ *
+ * Members can file disputes; only admins resolve them via a separate
+ * endpoint we'll add in v1.1. The API returns 202 (Accepted) so the
+ * UI doesn't claim definitive change of state.
+ */
+
+import {
+ requireCodingAgentAuth,
+ CodingAgentUnauthorizedError,
+} from "@/lib/platform/coding-agents/auth";
+import {
+ DisputeError,
+ submitClassificationDispute,
+ writeAuditLog,
+} from "@/lib/platform/coding-agents/queries";
+import {
+ validateClassificationDispute,
+ type CodingAgentClassificationDispute,
+} from "@/lib/platform/coding-agents/classifier";
+
+export const dynamic = "force-dynamic";
+
+export async function POST(request: Request) {
+ let auth;
+ try {
+ auth = await requireCodingAgentAuth();
+ } catch (err) {
+ if (err instanceof CodingAgentUnauthorizedError) {
+ return Response.json({ error: err.message }, { status: 401 });
+ }
+ throw err;
+ }
+
+ let body: Partial<CodingAgentClassificationDispute>;
+ try {
+ body = (await request.json()) as Partial<CodingAgentClassificationDispute>;
+ } catch {
+ await writeAuditLog(auth, {
+ action: "coding_agent.classification.dispute.rejected_invalid",
+ subject: "",
+ payload: "malformed_json",
+ });
+ return Response.json({ error: "Malformed JSON" }, { status: 400 });
+ }
+
+ const validationError = validateClassificationDispute(body);
+ if (validationError) {
+ await writeAuditLog(auth, {
+ action: "coding_agent.classification.dispute.rejected_invalid",
+ subject: body?.sessionId || "",
+ payload: validationError,
+ });
+ return Response.json({ error: validationError }, { status: 400 });
+ }
+
+ try {
+ const result = await submitClassificationDispute(
+ auth,
+ body as CodingAgentClassificationDispute
+ );
+ return Response.json({ data: result }, { status: 202 });
+ } catch (err) {
+ // E4: surface validation-grade errors with their intended
+ // HTTP status (404 not_found, 409 duplicate, 429
+ // rate_limited). Anything else stays a 500.
+ if (err instanceof DisputeError) {
+ await writeAuditLog(auth, {
+ action: `coding_agent.classification.dispute.rejected_${err.code}`,
+ subject: body?.sessionId || "",
+ payload: err.message,
+ });
+ return Response.json({ error: err.message }, { status: err.status });
+ }
+ console.error("coding_agent.classification.dispute.failed", err);
+ return Response.json({ error: "Internal error" }, { status: 500 });
+ }
+}
diff --git a/src/client/src/app/api/coding-agents/sessions/[sessionId]/digest/route.ts b/src/client/src/app/api/coding-agents/sessions/[sessionId]/digest/route.ts
new file mode 100644
index 00000000..426c1064
--- /dev/null
+++ b/src/client/src/app/api/coding-agents/sessions/[sessionId]/digest/route.ts
@@ -0,0 +1,59 @@
+/**
+ * GET /api/coding-agents/sessions/[sessionId]/digest
+ *
+ * Tiny rollup endpoint consumed by the trace-detail header pills
+ * (Lines added / Lines deleted / Commits / Acceptance / PRs) so the
+ * pills stay populated regardless of which span inside the session
+ * the operator clicked into. The session-rollup attributes only
+ * live on the session-root span at SessionEnd; this endpoint runs a
+ * single grouped query against `otel_traces` to fold them up by
+ * `chat_id` (= parent ?? session_id) so the same totals appear for
+ * every span in the same chat thread.
+ *
+ * Kept narrow on purpose — the full session join (turns, tool
+ * calls, MCP, edit decisions) is overkill when the pill row only
+ * needs the seven counters. Gated through `requireCodingAgentAuth`,
+ * and `getCodingSessionDigest` enforces the same COHORT_K_FLOOR
+ * floor as the per-user page for non-admin viewers — a known
+ * session_id should not become a side channel for low-volume
+ * users' aggregate metrics.
+ */
+
+import {
+ requireCodingAgentAuth,
+ CodingAgentUnauthorizedError,
+} from "@/lib/platform/coding-agents/auth";
+import { getCodingSessionDigest } from "@/lib/platform/coding-agents/queries";
+
+export const dynamic = "force-dynamic";
+
+export async function GET(
+ _request: Request,
+ context: { params: { sessionId: string } },
+) {
+ let auth;
+ try {
+ auth = await requireCodingAgentAuth();
+ } catch (err) {
+ if (err instanceof CodingAgentUnauthorizedError) {
+ return Response.json({ error: err.message }, { status: 401 });
+ }
+ throw err;
+ }
+
+ const sessionId = decodeURIComponent(context.params.sessionId || "").trim();
+ if (!sessionId) {
+ return Response.json({ error: "Missing sessionId" }, { status: 400 });
+ }
+
+ try {
+ const digest = await getCodingSessionDigest(auth, sessionId);
+ if (!digest) {
+ return Response.json({ error: "Not found" }, { status: 404 });
+ }
+ return Response.json({ data: digest });
+ } catch (err) {
+ console.error("coding_agent.session.digest_failed", err);
+ return Response.json({ error: "Internal error" }, { status: 500 });
+ }
+}
diff --git a/src/client/src/app/api/coding-agents/sessions/route.ts b/src/client/src/app/api/coding-agents/sessions/route.ts
new file mode 100644
index 00000000..c86dd8ed
--- /dev/null
+++ b/src/client/src/app/api/coding-agents/sessions/route.ts
@@ -0,0 +1,138 @@
+/**
+ * POST /api/coding-agents/sessions
+ *
+ * Offset/limit listing used by the unified telemetry primitive
+ * `<ObservabilitySignalList>`. Accepts the standard filter body
+ * (timeLimit, selectedConfig, sorting, offset, limit, runFilters)
+ * and returns `{ records, total }` so the table and count badge
+ * render with one round-trip.
+ *
+ * Gates through `requireCodingAgentAuth` so the org-scoped privacy
+ * floor still applies to `gen_ai.user.name`.
+ *
+ * F5: the legacy GET cursor handler (used by the deprecated
+ * `coding-sessions-tab.tsx`) was removed in 1.5 — the tab now
+ * renders via `<ObservabilitySignalList>` and only speaks POST.
+ */
+
+import {
+ listSessions,
+ type ListSessionsOptions,
+} from "@/lib/platform/coding-agents/queries";
+import {
+ requireCodingAgentAuth,
+ CodingAgentUnauthorizedError,
+} from "@/lib/platform/coding-agents/auth";
+import { isCodingAgentClassification } from "@/lib/platform/coding-agents/classifier";
+
+export const dynamic = "force-dynamic";
+
+interface SessionsListBody {
+ timeLimit?: { start?: string | Date; end?: string | Date };
+ selectedConfig?: Record<string, unknown>;
+ sorting?: { type?: string; direction?: string };
+ offset?: number;
+ limit?: number;
+ runFilters?: Record<string, unknown>;
+}
+
+const VALID_SESSIONS_SORT_BY: ReadonlyArray<string> = [
+ "latest",
+ "duration",
+ "cost",
+ "tokens",
+ "tool_calls",
+];
+
+function asSessionsSortBy(
+ value: unknown
+): ListSessionsOptions["sortBy"] | undefined {
+ if (typeof value !== "string") return undefined;
+ return VALID_SESSIONS_SORT_BY.includes(value)
+ ? (value as ListSessionsOptions["sortBy"])
+ : undefined;
+}
+
+function asSortDir(value: unknown): "asc" | "desc" | undefined {
+ if (value === "asc" || value === "desc") return value;
+ return undefined;
+}
+
+function asString(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function asDate(value: unknown): Date | null {
+ if (!value) return null;
+ const date = new Date(value as string | number | Date);
+ return Number.isNaN(date.getTime()) ? null : date;
+}
+
+// Default analysis window when the caller omits one. We refuse to run
+// an unbounded `otel_traces` scan: at 1M spans/day a missed filter
+// can easily timeout the ClickHouse query and (worse) widen the
+// cohort floor's surface area to historical data. 24h matches the
+// hub's materializer window so the Sessions tab and Spend hub
+// agree by default.
+const DEFAULT_WINDOW_HOURS = 24;
+function defaultSince(): Date {
+ return new Date(Date.now() - DEFAULT_WINDOW_HOURS * 60 * 60 * 1000);
+}
+
+export async function POST(request: Request) {
+ let auth;
+ try {
+ auth = await requireCodingAgentAuth();
+ } catch (err) {
+ if (err instanceof CodingAgentUnauthorizedError) {
+ return Response.json({ error: err.message }, { status: 401 });
+ }
+ throw err;
+ }
+
+ let body: SessionsListBody = {};
+ try {
+ body = (await request.json()) as SessionsListBody;
+ } catch {
+ // fall through with defaults — empty body is OK, signals
+ // "give me everything you can" within the cohort floor.
+ }
+
+ const runFilters = (body.runFilters || {}) as Record<string, unknown>;
+ const limitRaw = Number(body.limit);
+ const offsetRaw = Number(body.offset);
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? limitRaw : 25;
+ const offset = Number.isFinite(offsetRaw) && offsetRaw >= 0 ? offsetRaw : 0;
+
+ const opts: ListSessionsOptions = {
+ limit,
+ offset,
+ withTotal: true,
+ vendor: asString(runFilters.vendor),
+ user: asString(runFilters.user),
+ classification: isCodingAgentClassification(
+ asString(runFilters.classification)
+ )
+ ? (asString(runFilters.classification) as ListSessionsOptions["classification"])
+ : null,
+ // Time window defaults to last 24h if the caller didn't send
+ // one. See `defaultSince` for rationale.
+ since: asDate(body.timeLimit?.start) ?? defaultSince(),
+ until: asDate(body.timeLimit?.end),
+ sortBy: asSessionsSortBy(body.sorting?.type),
+ sortDir: asSortDir(body.sorting?.direction),
+ };
+
+ try {
+ const { rows, total } = await listSessions(auth, opts);
+ return Response.json({
+ records: rows,
+ total: total ?? rows.length,
+ });
+ } catch (err) {
+ console.error("coding_agent.sessions.list_failed", err);
+ return Response.json({ error: "Internal error" }, { status: 500 });
+ }
+}
diff --git a/src/client/src/app/api/coding-agents/sessions/summary/route.ts b/src/client/src/app/api/coding-agents/sessions/summary/route.ts
new file mode 100644
index 00000000..6258ca15
--- /dev/null
+++ b/src/client/src/app/api/coding-agents/sessions/summary/route.ts
@@ -0,0 +1,150 @@
+/**
+ * POST /api/coding-agents/sessions/summary
+ *
+ * Time-bucketed roll-up consumed by `<SignalSummary>` (the histogram
+ * above the `<ObservabilitySignalList>`). Mirrors the shape returned by
+ * `/api/telemetry/summary/traces` so the bar chart renders without any
+ * client-side branching: `{ bucket, buckets: [{label, count}], total, peak }`.
+ *
+ * Auth flows through `requireCodingAgentAuth` so org/db scoping stays
+ * consistent with the list route.
+ */
+
+import {
+ requireCodingAgentAuth,
+ CodingAgentUnauthorizedError,
+} from "@/lib/platform/coding-agents/auth";
+import { dataCollector } from "@/lib/platform/common";
+import {
+ CODING_AGENT_ATTR,
+ CODING_AGENT_SPAN_NAMES,
+ GEN_AI_ATTR,
+ OTEL_TRACES_TABLE,
+} from "@/lib/platform/coding-agents/table-details";
+
+export const dynamic = "force-dynamic";
+
+interface SummaryBody {
+ timeLimit?: { start?: string | Date; end?: string | Date };
+ runFilters?: Record<string, unknown>;
+}
+
+function escape(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
+function asString(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function asDate(value: unknown): Date | null {
+ if (!value) return null;
+ const date = new Date(value as string | number | Date);
+ return Number.isNaN(date.getTime()) ? null : date;
+}
+
+function pickBucket(start: Date | null, end: Date | null) {
+ const now = end ?? new Date();
+ const earlier = start ?? new Date(now.getTime() - 24 * 60 * 60 * 1000);
+ const days = Math.max(1, (now.getTime() - earlier.getTime()) / 86400000);
+ if (days <= 2) return { bucket: "hour", label: "%m/%d %H:00" };
+ if (days <= 45) return { bucket: "day", label: "%Y/%m/%d" };
+ if (days <= 370) return { bucket: "week", label: "%Y/%m/%d" };
+ return { bucket: "month", label: "%Y/%m" };
+}
+
+export async function POST(request: Request) {
+ try {
+ await requireCodingAgentAuth();
+ } catch (err) {
+ if (err instanceof CodingAgentUnauthorizedError) {
+ return Response.json({ error: err.message }, { status: 401 });
+ }
+ throw err;
+ }
+
+ let body: SummaryBody = {};
+ try {
+ body = (await request.json()) as SummaryBody;
+ } catch {
+ // empty body is acceptable — bucket the default 24h window.
+ }
+
+ // Default analysis window — match list/users routes. See B1.
+ const DEFAULT_WINDOW_HOURS = 24;
+ const start =
+ asDate(body.timeLimit?.start) ??
+ new Date(Date.now() - DEFAULT_WINDOW_HOURS * 60 * 60 * 1000);
+ const end = asDate(body.timeLimit?.end);
+ const { bucket, label } = pickBucket(start, end);
+ const runFilters = (body.runFilters || {}) as Record<string, unknown>;
+ const vendor = asString(runFilters.vendor);
+ const user = asString(runFilters.user);
+
+ const where: string[] = [
+ `SpanName IN (${CODING_AGENT_SPAN_NAMES.map((name) => `'${name}'`).join(", ")})`,
+ `notEmpty(SpanAttributes['${CODING_AGENT_ATTR.sessionId}'])`,
+ ];
+ where.push(
+ `Timestamp >= parseDateTimeBestEffort('${escape(start.toISOString())}')`
+ );
+ if (end) {
+ where.push(
+ `Timestamp <= parseDateTimeBestEffort('${escape(end.toISOString())}')`
+ );
+ }
+ if (vendor) {
+ where.push(
+ `coalesce(nullIf(SpanAttributes['${CODING_AGENT_ATTR.client}'], ''), SpanAttributes['${GEN_AI_ATTR.agentName}']) = '${escape(vendor)}'`
+ );
+ }
+ if (user) {
+ // E2: user identity falls through multiple keys (span attr ->
+ // resource attr -> service.name) — same coalesce chain
+ // listSessions uses. Filtering only on `gen_ai.user.name` here
+ // would silently drop rows whose identity falls through to
+ // `service.name`, leaving the histogram out of sync with the
+ // table.
+ where.push(`(
+ coalesce(
+ nullIf(SpanAttributes['${GEN_AI_ATTR.userName}'], ''),
+ nullIf(ResourceAttributes['${GEN_AI_ATTR.userName}'], ''),
+ ResourceAttributes['service.name']
+ ) = '${escape(user)}'
+ )`);
+ }
+
+ // `count(distinct chat_id)` per time bucket gives us the number
+ // of chat threads started in that window — same rollup the
+ // Sessions list uses (parent_id wins over session_id) so the
+ // histogram column and table row count line up.
+ const query = `
+ SELECT
+ formatDateTime(DATE_TRUNC('${bucket}', Timestamp), '${label}') AS label,
+ toInt64(uniqExact(
+ coalesce(
+ nullIf(ResourceAttributes['${CODING_AGENT_ATTR.agentParentId}'], ''),
+ nullIf(SpanAttributes['${CODING_AGENT_ATTR.agentParentId}'], ''),
+ SpanAttributes['${CODING_AGENT_ATTR.sessionId}']
+ )
+ )) AS count
+ FROM ${OTEL_TRACES_TABLE}
+ WHERE ${where.join(" AND ")}
+ GROUP BY label
+ ORDER BY min(Timestamp)
+ `;
+
+ const { data, err } = await dataCollector({ query });
+ if (err) {
+ console.error("coding_agent.sessions.summary_failed", err);
+ return Response.json({ error: "Internal error" }, { status: 500 });
+ }
+ const buckets = ((data as Array<{ label: string; count: number | string }>) || [])
+ .map((row) => ({ label: row.label, count: Number(row.count || 0) }));
+ const total = buckets.reduce((sum, row) => sum + row.count, 0);
+ const peak = buckets.reduce((max, row) => Math.max(max, row.count), 0);
+
+ return Response.json({ bucket, buckets, total, peak });
+}
diff --git a/src/client/src/app/api/coding-agents/users/[userId]/route.ts b/src/client/src/app/api/coding-agents/users/[userId]/route.ts
new file mode 100644
index 00000000..859f6b99
--- /dev/null
+++ b/src/client/src/app/api/coding-agents/users/[userId]/route.ts
@@ -0,0 +1,80 @@
+/**
+ * GET /api/coding-agents/users/[userId]
+ *
+ * Header card for the per-user page. Returns a compact digest scoped to
+ * one developer (sessions, tools, cost, work/personal mix, top
+ * vendors). Respects `COHORT_K_FLOOR`: if the requested user has fewer
+ * than the floor's worth of sessions and the caller is not an admin we
+ * 404 — the page is meaningless without enough data and the cohort
+ * floor is the privacy seal we promise viewer-tier callers.
+ */
+
+import {
+ requireCodingAgentAuth,
+ CodingAgentUnauthorizedError,
+} from "@/lib/platform/coding-agents/auth";
+import { getCodingUserDigest } from "@/lib/platform/coding-agents/queries";
+
+export const dynamic = "force-dynamic";
+
+export async function GET(
+ request: Request,
+ context: { params: { userId: string } }
+) {
+ let auth;
+ try {
+ auth = await requireCodingAgentAuth();
+ } catch (err) {
+ if (err instanceof CodingAgentUnauthorizedError) {
+ return Response.json({ error: err.message }, { status: 401 });
+ }
+ throw err;
+ }
+
+ const userId = decodeURIComponent(context.params.userId || "").trim();
+ if (!userId) {
+ return Response.json({ error: "Missing userId" }, { status: 400 });
+ }
+ if (userId === "low_cohort") {
+ // `low_cohort` is the masked sentinel — we reject it explicitly
+ // rather than letting the helper return 0 sessions and 404 (the
+ // 400 makes the failure mode obvious in logs).
+ return Response.json(
+ { error: "Cannot drill into the masked low-cohort bucket." },
+ { status: 400 }
+ );
+ }
+
+ const url = new URL(request.url);
+ const since = url.searchParams.get("since");
+ const until = url.searchParams.get("until");
+
+ // Default 24h window when the caller didn't pass one. Matches
+ // /api/coding-agents/sessions and /api/coding-agents/users so
+ // the per-user header card agrees with the lists by default —
+ // previously this route ran an unbounded all-time aggregation
+ // on cold loads (before the filter store hydrated) and diverged
+ // from every sibling endpoint.
+ const DEFAULT_WINDOW_HOURS = 24;
+ const sinceDate = since
+ ? new Date(since)
+ : new Date(Date.now() - DEFAULT_WINDOW_HOURS * 60 * 60 * 1000);
+ const untilDate = until ? new Date(until) : null;
+
+ try {
+ const digest = await getCodingUserDigest(auth, userId, {
+ since: sinceDate,
+ until: untilDate,
+ });
+ if (!digest) {
+ return Response.json(
+ { error: "Not found or below cohort floor." },
+ { status: 404 }
+ );
+ }
+ return Response.json({ data: digest });
+ } catch (err) {
+ console.error("coding_agent.user.digest_failed", err);
+ return Response.json({ error: "Internal error" }, { status: 500 });
+ }
+}
diff --git a/src/client/src/app/api/coding-agents/users/route.ts b/src/client/src/app/api/coding-agents/users/route.ts
new file mode 100644
index 00000000..a9b29a25
--- /dev/null
+++ b/src/client/src/app/api/coding-agents/users/route.ts
@@ -0,0 +1,159 @@
+/**
+ * /api/coding-agents/users
+ *
+ * Org-wide directory of coding-agent users. Two transports:
+ * - GET: simple paginated read (limit/offset query params).
+ * - POST: the same body shape `<ObservabilitySignalList>` sends,
+ * returning `{ records, total }` — used by the new "Users" tab on
+ * the coding-agent detail page.
+ *
+ * Privacy: rows below `COHORT_K_FLOOR` collapse into a single
+ * `low_cohort` aggregate for non-admin callers. See `listCodingUsers`.
+ */
+
+import {
+ requireCodingAgentAuth,
+ CodingAgentUnauthorizedError,
+} from "@/lib/platform/coding-agents/auth";
+import {
+ listCodingUsers,
+ type CodingUsersSortBy,
+ type ListCodingUsersOptions,
+} from "@/lib/platform/coding-agents/queries";
+
+const VALID_SORT_BY: CodingUsersSortBy[] = [
+ "last_seen",
+ "sessions",
+ "tool_calls",
+ "cost",
+ "tokens",
+ "work",
+];
+
+function asSortBy(value: unknown): CodingUsersSortBy | undefined {
+ if (typeof value !== "string") return undefined;
+ return (VALID_SORT_BY as string[]).includes(value)
+ ? (value as CodingUsersSortBy)
+ : undefined;
+}
+
+function asSortDir(value: unknown): "asc" | "desc" | undefined {
+ if (value === "asc" || value === "desc") return value;
+ return undefined;
+}
+
+export const dynamic = "force-dynamic";
+
+function asString(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function asDate(value: unknown): Date | null {
+ if (!value) return null;
+ const date = new Date(value as string | number | Date);
+ return Number.isNaN(date.getTime()) ? null : date;
+}
+
+// Default analysis window matches the Sessions route — see B1
+// rationale: never let a missing filter trigger an all-time scan.
+const DEFAULT_WINDOW_HOURS = 24;
+function defaultSince(): Date {
+ return new Date(Date.now() - DEFAULT_WINDOW_HOURS * 60 * 60 * 1000);
+}
+
+export async function GET(request: Request) {
+ let auth;
+ try {
+ auth = await requireCodingAgentAuth();
+ } catch (err) {
+ if (err instanceof CodingAgentUnauthorizedError) {
+ return Response.json({ error: err.message }, { status: 401 });
+ }
+ throw err;
+ }
+
+ const url = new URL(request.url);
+ const sp = url.searchParams;
+ const limitRaw = sp.get("limit");
+ const offsetRaw = sp.get("offset");
+ const opts: ListCodingUsersOptions = {
+ limit: limitRaw ? Number(limitRaw) : undefined,
+ offset: offsetRaw ? Number(offsetRaw) : undefined,
+ vendor: sp.get("vendor"),
+ since: sp.get("since") ? new Date(sp.get("since") as string) : defaultSince(),
+ until: sp.get("until") ? new Date(sp.get("until") as string) : null,
+ sortBy: asSortBy(sp.get("sortBy")),
+ sortDir: asSortDir(sp.get("sortDir")),
+ withTotal: true,
+ };
+
+ try {
+ const { rows, total } = await listCodingUsers(auth, opts);
+ return Response.json({ data: rows, total });
+ } catch (err) {
+ console.error("coding_agent.users.list_failed", err);
+ return Response.json({ error: "Internal error" }, { status: 500 });
+ }
+}
+
+interface UsersListBody {
+ timeLimit?: { start?: string | Date; end?: string | Date };
+ selectedConfig?: Record<string, unknown>;
+ sorting?: { type?: string; direction?: string };
+ offset?: number;
+ limit?: number;
+ runFilters?: Record<string, unknown>;
+}
+
+export async function POST(request: Request) {
+ let auth;
+ try {
+ auth = await requireCodingAgentAuth();
+ } catch (err) {
+ if (err instanceof CodingAgentUnauthorizedError) {
+ return Response.json({ error: err.message }, { status: 401 });
+ }
+ throw err;
+ }
+
+ let body: UsersListBody = {};
+ try {
+ body = (await request.json()) as UsersListBody;
+ } catch {
+ // empty body is fine.
+ }
+
+ const runFilters = (body.runFilters || {}) as Record<string, unknown>;
+ const limitRaw = Number(body.limit);
+ const offsetRaw = Number(body.offset);
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? limitRaw : 25;
+ const offset = Number.isFinite(offsetRaw) && offsetRaw >= 0 ? offsetRaw : 0;
+
+ // Sorting is driven by the shared toolbar Sorting dropdown, which
+ // writes to `body.sorting.{type,direction}`. This matches what the
+ // Sessions route accepts.
+ const opts: ListCodingUsersOptions = {
+ limit,
+ offset,
+ withTotal: true,
+ vendor: asString(runFilters.vendor),
+ // Default 24h window — same rationale as Sessions route.
+ since: asDate(body.timeLimit?.start) ?? defaultSince(),
+ until: asDate(body.timeLimit?.end),
+ sortBy: asSortBy(body.sorting?.type),
+ sortDir: asSortDir(body.sorting?.direction),
+ };
+
+ try {
+ const { rows, total } = await listCodingUsers(auth, opts);
+ return Response.json({
+ records: rows,
+ total: total ?? rows.length,
+ });
+ } catch (err) {
+ console.error("coding_agent.users.list_failed", err);
+ return Response.json({ error: "Internal error" }, { status: 500 });
+ }
+}
diff --git a/src/client/src/app/api/coding-agents/users/summary/route.ts b/src/client/src/app/api/coding-agents/users/summary/route.ts
new file mode 100644
index 00000000..d1c642df
--- /dev/null
+++ b/src/client/src/app/api/coding-agents/users/summary/route.ts
@@ -0,0 +1,145 @@
+/**
+ * POST /api/coding-agents/users/summary
+ *
+ * F7: histogram consumed by `<SignalSummary>` above the Users
+ * directory. Counts DISTINCT users active per time bucket — the
+ * sessions histogram (`/api/coding-agents/sessions/summary`)
+ * counts chat threads instead, so the two charts never line up
+ * when both tabs are open. Mirrors the bucket / label envelope
+ * the sessions route returns so `<SignalSummary>` doesn't need
+ * any client-side branching.
+ */
+
+import {
+ requireCodingAgentAuth,
+ CodingAgentUnauthorizedError,
+} from "@/lib/platform/coding-agents/auth";
+import { dataCollector } from "@/lib/platform/common";
+import {
+ CODING_AGENT_ATTR,
+ CODING_AGENT_SPAN_NAMES,
+ GEN_AI_ATTR,
+ OTEL_TRACES_TABLE,
+} from "@/lib/platform/coding-agents/table-details";
+
+export const dynamic = "force-dynamic";
+
+interface SummaryBody {
+ timeLimit?: { start?: string | Date; end?: string | Date };
+ runFilters?: Record<string, unknown>;
+}
+
+function escape(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
+function asString(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function asDate(value: unknown): Date | null {
+ if (!value) return null;
+ const date = new Date(value as string | number | Date);
+ return Number.isNaN(date.getTime()) ? null : date;
+}
+
+function pickBucket(start: Date | null, end: Date | null) {
+ const now = end ?? new Date();
+ const earlier = start ?? new Date(now.getTime() - 24 * 60 * 60 * 1000);
+ const days = Math.max(1, (now.getTime() - earlier.getTime()) / 86400000);
+ if (days <= 2) return { bucket: "hour", label: "%m/%d %H:00" };
+ if (days <= 45) return { bucket: "day", label: "%Y/%m/%d" };
+ if (days <= 370) return { bucket: "week", label: "%Y/%m/%d" };
+ return { bucket: "month", label: "%Y/%m" };
+}
+
+// Same USER_EXPR coalesce chain as queries.ts. Kept inline rather
+// than imported because the queries module is server-only and
+// route handlers may run in an edge runtime.
+const USER_EXPR = `
+ coalesce(
+ nullIf(SpanAttributes['${GEN_AI_ATTR.userName}'], ''),
+ nullIf(ResourceAttributes['${GEN_AI_ATTR.userName}'], ''),
+ ResourceAttributes['service.name'],
+ 'unknown'
+ )
+`;
+
+export async function POST(request: Request) {
+ try {
+ await requireCodingAgentAuth();
+ } catch (err) {
+ if (err instanceof CodingAgentUnauthorizedError) {
+ return Response.json({ error: err.message }, { status: 401 });
+ }
+ throw err;
+ }
+
+ let body: SummaryBody = {};
+ try {
+ body = (await request.json()) as SummaryBody;
+ } catch {
+ // empty body is OK — same default-window posture as the
+ // sessions summary route.
+ }
+
+ const DEFAULT_WINDOW_HOURS = 24;
+ const start =
+ asDate(body.timeLimit?.start) ??
+ new Date(Date.now() - DEFAULT_WINDOW_HOURS * 60 * 60 * 1000);
+ const end = asDate(body.timeLimit?.end);
+ const { bucket, label } = pickBucket(start, end);
+ const runFilters = (body.runFilters || {}) as Record<string, unknown>;
+ const vendor = asString(runFilters.vendor);
+ const user = asString(runFilters.user);
+
+ const where: string[] = [
+ `SpanName IN (${CODING_AGENT_SPAN_NAMES.map((name) => `'${name}'`).join(", ")})`,
+ `notEmpty(SpanAttributes['${CODING_AGENT_ATTR.sessionId}'])`,
+ ];
+ where.push(
+ `Timestamp >= parseDateTimeBestEffort('${escape(start.toISOString())}')`
+ );
+ if (end) {
+ where.push(
+ `Timestamp <= parseDateTimeBestEffort('${escape(end.toISOString())}')`
+ );
+ }
+ if (vendor) {
+ where.push(
+ `coalesce(nullIf(SpanAttributes['${CODING_AGENT_ATTR.client}'], ''), SpanAttributes['${GEN_AI_ATTR.agentName}']) = '${escape(vendor)}'`
+ );
+ }
+ if (user) {
+ where.push(`(${USER_EXPR.trim()}) = '${escape(user)}'`);
+ }
+
+ // `uniqExact(USER_EXPR)` per time bucket = distinct active users.
+ // The "unknown" sentinel is excluded so the histogram doesn't get
+ // dominated by pre-user-emit CLIs in mixed-version deployments —
+ // it falls under "0 users" for those buckets which is what the
+ // directory table also shows.
+ const query = `
+ SELECT
+ formatDateTime(DATE_TRUNC('${bucket}', Timestamp), '${label}') AS label,
+ toInt64(uniqExactIf(${USER_EXPR.trim()}, ${USER_EXPR.trim()} NOT IN ('unknown', ''))) AS count
+ FROM ${OTEL_TRACES_TABLE}
+ WHERE ${where.join(" AND ")}
+ GROUP BY label
+ ORDER BY min(Timestamp)
+ `;
+
+ const { data, err } = await dataCollector({ query });
+ if (err) {
+ console.error("coding_agent.users.summary_failed", err);
+ return Response.json({ error: "Internal error" }, { status: 500 });
+ }
+ const buckets = ((data as Array<{ label: string; count: number | string }>) || [])
+ .map((row) => ({ label: row.label, count: Number(row.count || 0) }));
+ const total = buckets.reduce((sum, row) => sum + row.count, 0);
+ const peak = buckets.reduce((max, row) => Math.max(max, row.count), 0);
+
+ return Response.json({ bucket, buckets, total, peak });
+}
diff --git a/src/client/src/clickhouse/migrations/add-coding-agent-loc-summary-fields-migration.ts b/src/client/src/clickhouse/migrations/add-coding-agent-loc-summary-fields-migration.ts
new file mode 100644
index 00000000..f15b2b6c
--- /dev/null
+++ b/src/client/src/clickhouse/migrations/add-coding-agent-loc-summary-fields-migration.ts
@@ -0,0 +1,67 @@
+import { AGENTS_SUMMARY_TABLE } from "@/lib/platform/agents/table-details";
+import migrationHelper from "./migration-helper";
+
+const MIGRATION_ID = "add-coding-agent-loc-summary-fields";
+
+/**
+ * Extends openlit_agents_summary with the 24h code-change rollups
+ * dashboards now expect for every coding-agent row (Claude Code,
+ * Cursor, Codex). These are populated by the materializer cron
+ * (src/lib/platform/agents/materialize.ts) from `otel_traces`
+ * coding_agent.session.* attributes.
+ *
+ * coding_lines_added_24h — sum of session.lines.added
+ * coding_lines_removed_24h — sum of session.lines.removed
+ * coding_lines_accepted_24h — sum of session.lines.accepted
+ * coding_lines_rejected_24h — sum of session.lines.rejected
+ * coding_edit_accept_24h — sum of session.edit.accept_count
+ * coding_edit_reject_24h — sum of session.edit.reject_count
+ * coding_commit_count_24h — sum of session.commit_count
+ * coding_pr_count_24h — sum of session.pr_count
+ *
+ * Idempotent — IF NOT EXISTS guards every ADD.
+ */
+export default async function AddCodingAgentLOCSummaryFieldsMigration(
+ databaseConfigId?: string
+) {
+ const queries = [
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_lines_added_24h UInt64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_lines_removed_24h UInt64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_lines_accepted_24h UInt64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_lines_rejected_24h UInt64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_edit_accept_24h UInt64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_edit_reject_24h UInt64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_commit_count_24h UInt64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_pr_count_24h UInt64 DEFAULT 0
+ `,
+ ];
+
+ return migrationHelper({
+ clickhouseMigrationId: MIGRATION_ID,
+ databaseConfigId,
+ queries,
+ });
+}
diff --git a/src/client/src/clickhouse/migrations/add-coding-agent-summary-fields-migration.ts b/src/client/src/clickhouse/migrations/add-coding-agent-summary-fields-migration.ts
new file mode 100644
index 00000000..fa4a2813
--- /dev/null
+++ b/src/client/src/clickhouse/migrations/add-coding-agent-summary-fields-migration.ts
@@ -0,0 +1,62 @@
+import { AGENTS_SUMMARY_TABLE } from "@/lib/platform/agents/table-details";
+import migrationHelper from "./migration-helper";
+
+const MIGRATION_ID = "add-coding-agent-summary-fields";
+
+/**
+ * Extends openlit_agents_summary so AI-coding-agent rows (Claude Code,
+ * Cursor, Codex) can co-exist with the existing controller/sdk
+ * rows on the /agents page:
+ *
+ * 1. ALTER source enum to include 'coding'.
+ * 2. ADD coding_agent_vendor — pinned vendor identifier.
+ * 3. ADD coding_session_count_24h — 24h rollup populated by materializer.
+ * 4. ADD coding_cost_usd_24h — 24h $ rollup.
+ * 5. ADD coding_active_users_24h — 24h distinct users (k=5 floor on
+ * per-user breakdowns enforced
+ * server-side at read time).
+ *
+ * Idempotent — IF NOT EXISTS guards every ADD, and the source enum
+ * MODIFY is a no-op when the value already exists.
+ */
+export default async function AddCodingAgentSummaryFieldsMigration(
+ databaseConfigId?: string
+) {
+ const queries = [
+ // Add 'coding' as enum value 3. Existing values (0/1/2) keep
+ // their numeric ids so SELECT-WHERE clauses written before the
+ // migration ran continue to match. ClickHouse only allows enum
+ // extensions when the new value is appended.
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ MODIFY COLUMN source Enum8(
+ 'controller' = 0,
+ 'sdk' = 1,
+ 'both' = 2,
+ 'coding' = 3
+ ) DEFAULT 'sdk'
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_agent_vendor String DEFAULT ''
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_session_count_24h UInt64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_cost_usd_24h Float64 DEFAULT 0
+ `,
+ `
+ ALTER TABLE ${AGENTS_SUMMARY_TABLE}
+ ADD COLUMN IF NOT EXISTS coding_active_users_24h UInt32 DEFAULT 0
+ `,
+ ];
+
+ return migrationHelper({
+ clickhouseMigrationId: MIGRATION_ID,
+ databaseConfigId,
+ queries,
+ });
+}
diff --git a/src/client/src/clickhouse/migrations/create-coding-agents-audit-migration.ts b/src/client/src/clickhouse/migrations/create-coding-agents-audit-migration.ts
new file mode 100644
index 00000000..2064bc5a
--- /dev/null
+++ b/src/client/src/clickhouse/migrations/create-coding-agents-audit-migration.ts
@@ -0,0 +1,68 @@
+import migrationHelper from "./migration-helper";
+
+const MIGRATION_ID = "create-coding-agents-audit";
+
+/**
+ * Persistent audit + dispute log for coding-agent governance actions.
+ *
+ * Two tables:
+ * - openlit_coding_agent_audit_log append-only event log
+ * - openlit_coding_agent_disputes one row per dispute submission
+ *
+ * Audit log captures every governance-grade action (classification
+ * dispute, policy edit). It's kept separate from the dispute table so
+ * we can query "who did what when" without paginating through the
+ * larger trace data.
+ *
+ * organization_id is stamped from the API route (pulled from the
+ * caller's current org via Prisma) — not from a span attribute — so
+ * disputes survive even if the underlying trace is later deleted via
+ * TTL.
+ */
+
+export const CODING_AGENT_AUDIT_LOG_TABLE = "openlit_coding_agent_audit_log";
+export const CODING_AGENT_DISPUTES_TABLE = "openlit_coding_agent_disputes";
+
+export default async function CreateCodingAgentsAuditMigration(databaseConfigId?: string) {
+ const queries = [
+ `
+ CREATE TABLE IF NOT EXISTS ${CODING_AGENT_AUDIT_LOG_TABLE} (
+ id UUID DEFAULT generateUUIDv4(),
+ organization_id String,
+ user_id String,
+ action String,
+ subject String DEFAULT '',
+ payload String DEFAULT '',
+ created_at DateTime DEFAULT now()
+ ) ENGINE = MergeTree()
+ PARTITION BY toYYYYMM(created_at)
+ ORDER BY (organization_id, created_at, id)
+ TTL created_at + INTERVAL 365 DAY DELETE
+ SETTINGS index_granularity = 8192;
+ `,
+ `
+ CREATE TABLE IF NOT EXISTS ${CODING_AGENT_DISPUTES_TABLE} (
+ id UUID DEFAULT generateUUIDv4(),
+ organization_id String,
+ session_id String,
+ user_id String,
+ current_classification String,
+ requested_classification String,
+ rationale String,
+ status Enum8('open' = 0, 'accepted' = 1, 'rejected' = 2, 'withdrawn' = 3) DEFAULT 'open',
+ resolved_by_user_id String DEFAULT '',
+ resolved_at DateTime DEFAULT '1970-01-01 00:00:00',
+ created_at DateTime DEFAULT now()
+ ) ENGINE = ReplacingMergeTree(created_at)
+ ORDER BY (organization_id, session_id, id)
+ TTL created_at + INTERVAL 365 DAY DELETE
+ SETTINGS index_granularity = 8192;
+ `,
+ ];
+
+ return migrationHelper({
+ clickhouseMigrationId: MIGRATION_ID,
+ databaseConfigId,
+ queries,
+ });
+}
diff --git a/src/client/src/clickhouse/migrations/create-custom-dashboards-migration.ts b/src/client/src/clickhouse/migrations/create-custom-dashboards-migration.ts
index f615f2c3..a2b7f315 100644
--- a/src/client/src/clickhouse/migrations/create-custom-dashboards-migration.ts
+++ b/src/client/src/clickhouse/migrations/create-custom-dashboards-migration.ts
@@ -104,9 +104,16 @@ export default async function CreateCustomDashboardsMigration(databaseConfigId?:
queries,
});
- if (!migrationExist) {
- await CreateCustomDashboardsSeed(databaseConfigId);
- }
+ // Always run the seed -- it is idempotent per-title via
+ // `boardExistsByTitle` and exists precisely so that dashboards
+ // added to `SEEDED_DASHBOARDS` after a stack's first boot still
+ // land on every existing deployment without a per-board one-off
+ // migration. Gating this on `!migrationExist` silently broke that
+ // contract (every new built-in board would skip every existing
+ // stack), which is exactly the regression that hid the Coding
+ // Agents dashboard. Cost per boot is N small `SELECT count(*)
+ // FROM openlit_board WHERE title = ?` queries -- negligible.
+ await CreateCustomDashboardsSeed(databaseConfigId);
return { migrationExist, queriesRun };
}
diff --git a/src/client/src/clickhouse/migrations/drop-vcs-migration.ts b/src/client/src/clickhouse/migrations/drop-vcs-migration.ts
new file mode 100644
index 00000000..46584cbf
--- /dev/null
+++ b/src/client/src/clickhouse/migrations/drop-vcs-migration.ts
@@ -0,0 +1,32 @@
+import migrationHelper from "./migration-helper";
+
+const MIGRATION_ID = "drop-vcs-tables";
+
+/**
+ * Drops the v2 GitHub-App VCS tables that earlier deployments created
+ * via the now-removed `create-vcs-migration`. These tables were never
+ * written to (the install / setup / webhook handlers shipped as 501
+ * stubs and were removed alongside this migration), so this cleanup is
+ * safe and irreversible-without-data-loss only in the sense that there
+ * was never any data.
+ *
+ * `DROP TABLE IF EXISTS` keeps fresh installs that never had the
+ * tables a no-op.
+ */
+export default async function DropVcsMigration(databaseConfigId?: string) {
+ const queries = [
+ `DROP TABLE IF EXISTS openlit_vcs_commits`,
+ `DROP TABLE IF EXISTS openlit_vcs_pull_requests`,
+ `DROP TABLE IF EXISTS openlit_vcs_pr_files`,
+ `DROP TABLE IF EXISTS openlit_vcs_line_attributions`,
+ `DROP TABLE IF EXISTS openlit_vcs_security_findings`,
+ ];
+
+ const { migrationExist, queriesRun } = await migrationHelper({
+ clickhouseMigrationId: MIGRATION_ID,
+ databaseConfigId,
+ queries,
+ });
+
+ return { migrationExist, queriesRun };
+}
diff --git a/src/client/src/clickhouse/migrations/index.ts b/src/client/src/clickhouse/migrations/index.ts
index c4873311..c1ec5df4 100644
--- a/src/client/src/clickhouse/migrations/index.ts
+++ b/src/client/src/clickhouse/migrations/index.ts
@@ -29,6 +29,10 @@ import CreateAgentsSummaryMigration from "./create-agents-summary-migration";
import CreateAgentVersionsMigration from "./create-agent-versions-migration";
import AddAgentsSummarySkipIndexesMigration from "./add-agents-summary-skip-indexes-migration";
import OptimizeAgentTablesStorageMigration from "./optimize-agent-tables-storage-migration";
+import AddCodingAgentSummaryFieldsMigration from "./add-coding-agent-summary-fields-migration";
+import AddCodingAgentLOCSummaryFieldsMigration from "./add-coding-agent-loc-summary-fields-migration";
+import CreateCodingAgentsAuditMigration from "./create-coding-agents-audit-migration";
+import DropVcsMigration from "./drop-vcs-migration";
export default async function migrations(databaseConfigId?: string) {
// Group 1: Independent table creations (safe to parallel)
@@ -76,4 +80,30 @@ export default async function migrations(databaseConfigId?: string) {
// agents-summary + agent-versions CREATEs).
await AddAgentsSummarySkipIndexesMigration(databaseConfigId);
await OptimizeAgentTablesStorageMigration(databaseConfigId);
+
+ // Group 5: Coding-agent extensions (sequential — must run after
+ // agents_summary exists; safe to parallel within itself).
+ await Promise.all([
+ AddCodingAgentSummaryFieldsMigration(databaseConfigId),
+ CreateCodingAgentsAuditMigration(databaseConfigId),
+ ]);
+
+ // Group 6: LOC / commit / PR rollup columns. Must run after the
+ // initial coding-agent summary fields migration because both ALTER
+ // the same `openlit_agents_summary` table; ClickHouse serialises
+ // ALTERs on a single table anyway, but ordering the awaits keeps
+ // the dependency explicit.
+ await AddCodingAgentLOCSummaryFieldsMigration(databaseConfigId);
+
+ // Group 7: Drop the never-populated v2 GitHub App VCS tables that
+ // earlier deployments created via the now-removed
+ // `create-vcs-migration`. Runs last so stale deployments still get
+ // the cleanup, and uses IF EXISTS so fresh installs are no-ops.
+ await DropVcsMigration(databaseConfigId);
+
+ // Built-in dashboard seeding (LLM / Vector DB / GPU / Coding
+ // Agents / future) lives inside `create-custom-dashboards-migration`
+ // and runs on every boot via per-title idempotent upsert -- no
+ // per-board one-off migration is needed when a new built-in board
+ // is added to `SEEDED_DASHBOARDS` (see seed/dashboards.ts).
}
diff --git a/src/client/src/clickhouse/seed-data/openlit-dashboard-coding-agents-layout.json b/src/client/src/clickhouse/seed-data/openlit-dashboard-coding-agents-layout.json
new file mode 100644
index 00000000..2d16125a
--- /dev/null
+++ b/src/client/src/clickhouse/seed-data/openlit-dashboard-coding-agents-layout.json
@@ -0,0 +1,521 @@
+{
+ "id": "8f4d7b2e-6a91-4c52-9b3a-1e6c8f3d4a5b",
+ "title": "Coding Agents",
+ "description": "Coding-agent observability across vendors (Claude Code, Cursor, Codex). Sessions, cost, tools, users, classification, and governance — sourced live from otel_traces emitted by the openlit CLI hook.",
+ "parentId": null,
+ "isMainDashboard": false,
+ "isPinned": true,
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 11:00:00",
+ "widgets": {
+ "9a1f1c20-3b27-4f88-9d51-1aaa11111111": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa11111111",
+ "title": "Total sessions",
+ "description": "Distinct coding-agent sessions in the selected window. Optionally vendor- and user-scoped to match what the agents-hub card and the Sessions / Users tabs show.",
+ "type": "STAT_CARD",
+ "properties": {
+ "value": "0.total_sessions",
+ "trend": "0.rate",
+ "trendSuffix": "%",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n (end_time - start_time) AS duration,\n (start_time - duration) AS prev_start_time,\n (end_time - duration) AS prev_end_time,\n per_session_now AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY chat_id, vendor\n ),\n per_session_prev AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= prev_start_time AND Timestamp <= prev_end_time\n GROUP BY chat_id, vendor\n ),\n totals AS (\n SELECT\n (SELECT toInt64(count()) FROM per_session_now WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS now_total,\n (SELECT toInt64(count()) FROM per_session_prev WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS prev_total\n )\n\nSELECT\n CAST(now_total AS INTEGER) AS total_sessions,\n CAST(prev_total AS INTEGER) AS total_sessions_previous,\n if(prev_total > 0, round((now_total - prev_total) * 100.0 / prev_total, 1), NULL) AS rate\nFROM totals\n"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:30:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa11111112": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa11111112",
+ "title": "Active users",
+ "description": "Distinct users in the selected window, optionally vendor-scoped (gen_ai.user.name → service.name).",
+ "type": "STAT_CARD",
+ "properties": {
+ "value": "0.active_users",
+ "trend": "0.rate",
+ "trendSuffix": "%",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n (end_time - start_time) AS duration,\n (start_time - duration) AS prev_start_time,\n (end_time - duration) AS prev_end_time,\n -- Group by chat_id (= parent_id ?? session_id) so subagent\n -- spawns don't inflate the user count. Matches the\n -- CHAT_ID_EXPR used by the Total Sessions / Total Cost\n -- widgets and the Users tab so all surfaces agree.\n per_session_now AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY chat_id, vendor\n ),\n per_session_prev AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= prev_start_time AND Timestamp <= prev_end_time\n GROUP BY chat_id, vendor\n ),\n totals AS (\n SELECT\n (SELECT uniqExact(user) FROM per_session_now WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS now_total,\n (SELECT uniqExact(user) FROM per_session_prev WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS prev_total\n )\n\nSELECT\n CAST(now_total AS INTEGER) AS active_users,\n if(prev_total > 0, round((now_total - prev_total) * 100.0 / prev_total, 1), NULL) AS rate\nFROM totals\n"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:30:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa11111113": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa11111113",
+ "title": "Total cost (USD)",
+ "description": "Per-session cost rolled up: greatest of the authoritative coding_agent.session.cost_usd and the sum of per-turn gen_ai.usage.cost. Matches the Sessions list, the Users tab, and the agents-hub Coding Agents card.",
+ "type": "STAT_CARD",
+ "properties": {
+ "value": "0.total_cost",
+ "trend": "0.rate",
+ "trendSuffix": "%",
+ "color": "#F36C06",
+ "prefix": "$"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n (end_time - start_time) AS duration,\n (start_time - duration) AS prev_start_time,\n (end_time - duration) AS prev_end_time,\n -- Canonical per-session cost. Same formula listSessions /\n -- listCodingUsers / the agents-hub materializer use. Without\n -- the greatest() this widget silently under-counts: sessions\n -- whose only cost signal is the session-end stamp\n -- (coding_agent.session.cost_usd, set on Stop / SessionEnd by\n -- Claude Code and Codex) would report $0 because no per-turn\n -- gen_ai.usage.cost was ever emitted.\n cost_now AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user,\n greatest(\n toFloat64OrZero(any(SpanAttributes['coding_agent.session.cost_usd'])),\n sumOrNull(toFloat64OrZero(SpanAttributes['gen_ai.usage.cost']))\n ) AS session_cost\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY chat_id, vendor\n ),\n cost_prev AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user,\n greatest(\n toFloat64OrZero(any(SpanAttributes['coding_agent.session.cost_usd'])),\n sumOrNull(toFloat64OrZero(SpanAttributes['gen_ai.usage.cost']))\n ) AS session_cost\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= prev_start_time AND Timestamp <= prev_end_time\n GROUP BY chat_id, vendor\n ),\n totals AS (\n SELECT\n (SELECT round(sumOrNull(session_cost), 4) FROM cost_now WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS now_total,\n (SELECT round(sumOrNull(session_cost), 4) FROM cost_prev WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS prev_total\n )\n\nSELECT\n coalesce(now_total, 0) AS total_cost,\n coalesce(prev_total, 0) AS total_cost_previous,\n if(coalesce(prev_total, 0) > 0, round((coalesce(now_total, 0) - coalesce(prev_total, 0)) * 100.0 / coalesce(prev_total, 0), 1), NULL) AS rate\nFROM totals\n"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:30:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa11111114": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa11111114",
+ "title": "Total tool calls",
+ "description": "Distinct tool invocations across the selected window, optionally vendor- and user-scoped.",
+ "type": "STAT_CARD",
+ "properties": {
+ "value": "0.total_tools",
+ "trend": "0.rate",
+ "trendSuffix": "%",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n (end_time - start_time) AS duration,\n (start_time - duration) AS prev_start_time,\n (end_time - duration) AS prev_end_time\n\nSELECT\n CAST(countIf(\n SpanName IN ('coding_agent.tool.call', 'claude_code.tool')\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(nullIf(SpanAttributes['gen_ai.user.name'], ''), nullIf(ResourceAttributes['gen_ai.user.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown') = '{{filter.user}}'{{/filter.user}}\n ) AS INTEGER) AS total_tools,\n\n CAST(countIf(\n SpanName IN ('coding_agent.tool.call', 'claude_code.tool')\n AND Timestamp >= prev_start_time AND Timestamp <= prev_end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(nullIf(SpanAttributes['gen_ai.user.name'], ''), nullIf(ResourceAttributes['gen_ai.user.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown') = '{{filter.user}}'{{/filter.user}}\n ) AS INTEGER) AS total_tools_previous,\n\n if(total_tools_previous > 0, round((total_tools - total_tools_previous) * 100.0 / total_tools_previous, 1), NULL) AS rate\nFROM otel_traces\nWHERE\n SpanName IN ('coding_agent.tool.call', 'claude_code.tool')\n AND Timestamp >= prev_start_time AND Timestamp <= end_time\n"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:35:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa22222221": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa22222221",
+ "title": "Sessions over time",
+ "description": "Distinct coding-agent sessions bucketed across the window. Optionally vendor- and user-scoped.",
+ "type": "AREA_CHART",
+ "properties": {
+ "xAxis": "request_time",
+ "yAxes": [
+ {
+ "key": "sessions",
+ "color": "#F36C06"
+ }
+ ]
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n dateDiff('day', start_time, end_time) AS days_diff,\n dateDiff('year', start_time, end_time) AS years_diff,\n multiIf(\n years_diff >= 1, 'month',\n days_diff <= 1, 'hour',\n 'day'\n ) AS date_granularity\n\nSELECT\n CAST(uniq(coalesce(\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], ''),\n nullIf(SpanAttributes['session.id'], ''),\n nullIf(ResourceAttributes['session.id'], '')\n )) AS INTEGER) AS sessions,\n formatDateTime(DATE_TRUNC(date_granularity, Timestamp), '%Y/%m/%d %R') AS request_time\nFROM otel_traces\nWHERE\n (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\nGROUP BY request_time\nORDER BY request_time"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:35:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa22222222": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa22222222",
+ "title": "Sessions by vendor",
+ "description": "Sessions broken down by coding-agent vendor. Honours filter.vendor: scoped to the active vendor on per-vendor detail pages, cross-vendor on the per-user page.",
+ "type": "PIE_CHART",
+ "properties": {
+ "labelPath": "vendor",
+ "valuePath": "sessions",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n per_session AS (\n SELECT\n coalesce(\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], ''),\n nullIf(SpanAttributes['session.id'], ''),\n nullIf(ResourceAttributes['session.id'], '')\n ) AS sid,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY sid, vendor\n )\n\nSELECT vendor, CAST(count() AS INTEGER) AS sessions\nFROM per_session\nWHERE 1=1{{#filter.vendor}}\n AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}}\n AND user = '{{filter.user}}'{{/filter.user}}\nGROUP BY vendor\nORDER BY sessions DESC"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:30:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa33333331": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa33333331",
+ "title": "Top tools",
+ "description": "Top tools invoked across coding-agent sessions, optionally vendor- and user-scoped.",
+ "type": "BAR_CHART",
+ "properties": {
+ "xAxis": "tool",
+ "yAxis": "calls",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time\n\nSELECT\n coalesce(\n nullIf(SpanAttributes['gen_ai.tool.name'], ''),\n nullIf(SpanAttributes['coding_agent.tool.name'], ''),\n 'unknown'\n ) AS tool,\n CAST(COUNT(*) AS INTEGER) AS calls\nFROM otel_traces\nWHERE\n SpanName IN ('coding_agent.tool.call', 'coding_agent.tool.requested')\n AND (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\nGROUP BY tool\nORDER BY calls DESC\nLIMIT 10"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:35:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa33333332": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa33333332",
+ "title": "Top users",
+ "description": "Top users by session count, optionally vendor-scoped (gen_ai.user.name → service.name).",
+ "type": "BAR_CHART",
+ "properties": {
+ "xAxis": "user",
+ "yAxis": "sessions",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n per_session AS (\n SELECT\n coalesce(\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], ''),\n nullIf(SpanAttributes['session.id'], ''),\n nullIf(ResourceAttributes['session.id'], '')\n ) AS sid,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY sid, vendor\n )\n\nSELECT user, CAST(count() AS INTEGER) AS sessions\nFROM per_session\nWHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}\nGROUP BY user\nORDER BY sessions DESC\nLIMIT 10"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:30:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa33333333": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa33333333",
+ "title": "Top repositories",
+ "description": "Repositories where coding-agent sessions ran (vcs.repository.url.full), optionally vendor- and user-scoped.",
+ "type": "BAR_CHART",
+ "properties": {
+ "xAxis": "repo",
+ "yAxis": "sessions",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time\n\nSELECT\n SpanAttributes['vcs.repository.url.full'] AS repo,\n CAST(uniq(coalesce(\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], ''),\n nullIf(SpanAttributes['session.id'], ''),\n nullIf(ResourceAttributes['session.id'], '')\n )) AS INTEGER) AS sessions\nFROM otel_traces\nWHERE\n notEmpty(SpanAttributes['vcs.repository.url.full'])\n AND (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\nGROUP BY repo\nORDER BY sessions DESC\nLIMIT 10"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:35:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa44444441": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa44444441",
+ "title": "Personal vs work classification",
+ "description": "Sessions broken down by coding_agent.user.classification (personal | work | disputed | unknown), optionally vendor-scoped.",
+ "type": "PIE_CHART",
+ "properties": {
+ "labelPath": "classification",
+ "valuePath": "sessions",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n per_session AS (\n SELECT\n coalesce(\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], ''),\n nullIf(SpanAttributes['session.id'], ''),\n nullIf(ResourceAttributes['session.id'], '')\n ) AS sid,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['coding_agent.user.classification']), ''),\n 'unknown'\n ) AS classification,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY sid, vendor\n )\n\nSELECT classification, CAST(count() AS INTEGER) AS sessions\nFROM per_session\nWHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}}\n AND user = '{{filter.user}}'{{/filter.user}}\nGROUP BY classification\nORDER BY sessions DESC"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:30:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa44444442": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa44444442",
+ "title": "Top models",
+ "description": "Top LLM models behind coding-agent activity, optionally vendor- and user-scoped.",
+ "type": "BAR_CHART",
+ "properties": {
+ "xAxis": "model",
+ "yAxis": "calls",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time\n\nSELECT\n SpanAttributes['gen_ai.request.model'] AS model,\n CAST(COUNT(*) AS INTEGER) AS calls\nFROM otel_traces\nWHERE\n (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND notEmpty(SpanAttributes['gen_ai.request.model'])\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\nGROUP BY model\nORDER BY calls DESC\nLIMIT 10"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:35:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa55555551": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa55555551",
+ "title": "Session outcomes",
+ "description": "Distribution of session outcomes — merged, committed, abandoned, cancelled — optionally vendor-scoped.",
+ "type": "PIE_CHART",
+ "properties": {
+ "labelPath": "outcome",
+ "valuePath": "sessions",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n per_session AS (\n SELECT\n coalesce(\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], ''),\n nullIf(SpanAttributes['session.id'], ''),\n nullIf(ResourceAttributes['session.id'], '')\n ) AS sid,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(nullIf(any(SpanAttributes['coding_agent.session.outcome']), ''), 'unknown') AS outcome,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY sid, vendor\n )\n\nSELECT outcome, CAST(count() AS INTEGER) AS sessions\nFROM per_session\nWHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}}\n AND user = '{{filter.user}}'{{/filter.user}}\nGROUP BY outcome\nORDER BY sessions DESC"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:30:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa55555552": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa55555552",
+ "title": "Edit decisions",
+ "description": "Auto-applied vs user-reviewed edits — gauge user trust in the agent. Optionally vendor- and user-scoped.",
+ "type": "PIE_CHART",
+ "properties": {
+ "labelPath": "decision",
+ "valuePath": "edits",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time\n\nSELECT\n coalesce(nullIf(SpanAttributes['coding_agent.edit.decision'], ''), 'unknown') AS decision,\n CAST(COUNT(*) AS INTEGER) AS edits\nFROM otel_traces\nWHERE\n SpanName = 'coding_agent.edit.decision'\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\nGROUP BY decision\nORDER BY edits DESC"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:35:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa55555553": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa55555553",
+ "title": "MCP servers in use",
+ "description": "Top MCP servers attached to coding-agent runs (governance signal). Optionally vendor- and user-scoped.",
+ "type": "BAR_CHART",
+ "properties": {
+ "xAxis": "server",
+ "yAxis": "invocations",
+ "color": "#F36C06"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time\n\nSELECT\n SpanAttributes['coding_agent.mcp.server.name'] AS server,\n CAST(COUNT(*) AS INTEGER) AS invocations\nFROM otel_traces\nWHERE\n notEmpty(SpanAttributes['coding_agent.mcp.server.name'])\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\nGROUP BY server\nORDER BY invocations DESC\nLIMIT 10"
+ },
+ "createdAt": "2026-05-25 11:00:00",
+ "updatedAt": "2026-05-28 03:35:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa66666661": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa66666661",
+ "title": "Lines of code (accepted)",
+ "description": "Lines of code accepted across coding-agent sessions in the selected window. Uses the same greatest(session-rollup-attr, per-edit-decision-sum) pattern as the Sessions list so the dashboard agrees with the per-row totals.",
+ "type": "STAT_CARD",
+ "properties": {
+ "value": "0.lines_accepted",
+ "trend": "0.rate",
+ "trendSuffix": "%",
+ "color": "#10b981"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n (end_time - start_time) AS duration,\n (start_time - duration) AS prev_start_time,\n (end_time - duration) AS prev_end_time,\n per_chat_now AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user,\n greatest(\n toInt64OrZero(any(SpanAttributes['coding_agent.session.lines.accepted'])),\n toInt64(sumIf(\n toInt64OrZero(SpanAttributes['coding_agent.edit.lines.added']),\n SpanName = 'coding_agent.edit.decision'\n AND SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted')\n ))\n ) AS lines_accepted\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY chat_id, vendor\n ),\n per_chat_prev AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user,\n greatest(\n toInt64OrZero(any(SpanAttributes['coding_agent.session.lines.accepted'])),\n toInt64(sumIf(\n toInt64OrZero(SpanAttributes['coding_agent.edit.lines.added']),\n SpanName = 'coding_agent.edit.decision'\n AND SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted')\n ))\n ) AS lines_accepted\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= prev_start_time AND Timestamp <= prev_end_time\n GROUP BY chat_id, vendor\n ),\n totals AS (\n SELECT\n (SELECT toInt64(sumOrNull(lines_accepted)) FROM per_chat_now WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS now_total,\n (SELECT toInt64(sumOrNull(lines_accepted)) FROM per_chat_prev WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS prev_total\n )\n\nSELECT\n CAST(coalesce(now_total, 0) AS INTEGER) AS lines_accepted,\n CAST(coalesce(prev_total, 0) AS INTEGER) AS lines_accepted_previous,\n if(coalesce(prev_total, 0) > 0, round((coalesce(now_total, 0) - coalesce(prev_total, 0)) * 100.0 / coalesce(prev_total, 0), 1), NULL) AS rate\nFROM totals\n"
+ },
+ "createdAt": "2026-05-28 11:00:00",
+ "updatedAt": "2026-05-28 11:00:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa66666662": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa66666662",
+ "title": "Acceptance %",
+ "description": "Percentage of edit decisions accepted (accept + auto_accepted) vs rejected. Computed from coding_agent.edit.decision spans, denominator is total accept + reject decisions (same shape as the Sessions list).",
+ "type": "STAT_CARD",
+ "properties": {
+ "value": "0.acceptance_pct",
+ "trend": "0.rate",
+ "trendSuffix": "%",
+ "color": "#10b981",
+ "suffix": "%"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n (end_time - start_time) AS duration,\n (start_time - duration) AS prev_start_time,\n (end_time - duration) AS prev_end_time,\n -- We deliberately count individual edit-decision spans here\n -- rather than reading the session-rollup attribute. The rollup\n -- attribute only lands on the session-root span at\n -- SessionEnd; Codex never emits one, and live in-flight\n -- sessions skip it too. Counting per-event spans keeps the\n -- acceptance % live as soon as the first edit happens.\n now_edits AS (\n SELECT\n countIf(SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted')) AS accepts,\n countIf(SpanAttributes['coding_agent.edit.decision'] = 'reject') AS rejects\n FROM otel_traces\n WHERE\n SpanName = 'coding_agent.edit.decision'\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\n ),\n prev_edits AS (\n SELECT\n countIf(SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted')) AS accepts,\n countIf(SpanAttributes['coding_agent.edit.decision'] = 'reject') AS rejects\n FROM otel_traces\n WHERE\n SpanName = 'coding_agent.edit.decision'\n AND Timestamp >= prev_start_time AND Timestamp <= prev_end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\n ),\n totals AS (\n SELECT\n if((now_edits.accepts + now_edits.rejects) > 0,\n round(now_edits.accepts * 100.0 / (now_edits.accepts + now_edits.rejects), 1),\n NULL) AS now_total,\n if((prev_edits.accepts + prev_edits.rejects) > 0,\n round(prev_edits.accepts * 100.0 / (prev_edits.accepts + prev_edits.rejects), 1),\n NULL) AS prev_total\n FROM now_edits, prev_edits\n )\n\nSELECT\n coalesce(now_total, 0) AS acceptance_pct,\n coalesce(prev_total, 0) AS acceptance_pct_previous,\n if(coalesce(prev_total, 0) > 0, round((coalesce(now_total, 0) - coalesce(prev_total, 0)) * 100.0 / coalesce(prev_total, 0), 1), NULL) AS rate\nFROM totals\n"
+ },
+ "createdAt": "2026-05-28 11:00:00",
+ "updatedAt": "2026-05-28 11:00:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa66666663": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa66666663",
+ "title": "Commits",
+ "description": "Total git commits authored inside coding-agent sessions (detected from the Bash / shell / local_shell tools across vendors). Uses greatest(session-rollup-attr, count of coding_agent.git.commit spans) so Codex / in-flight sessions still register.",
+ "type": "STAT_CARD",
+ "properties": {
+ "value": "0.commits",
+ "trend": "0.rate",
+ "trendSuffix": "%",
+ "color": "#6366f1"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n (end_time - start_time) AS duration,\n (start_time - duration) AS prev_start_time,\n (end_time - duration) AS prev_end_time,\n per_chat_now AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user,\n greatest(\n toInt64OrZero(any(SpanAttributes['coding_agent.session.commit_count'])),\n toInt64(countIf(SpanName = 'coding_agent.git.commit'))\n ) AS commits\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY chat_id, vendor\n ),\n per_chat_prev AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user,\n greatest(\n toInt64OrZero(any(SpanAttributes['coding_agent.session.commit_count'])),\n toInt64(countIf(SpanName = 'coding_agent.git.commit'))\n ) AS commits\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= prev_start_time AND Timestamp <= prev_end_time\n GROUP BY chat_id, vendor\n ),\n totals AS (\n SELECT\n (SELECT toInt64(sumOrNull(commits)) FROM per_chat_now WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS now_total,\n (SELECT toInt64(sumOrNull(commits)) FROM per_chat_prev WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS prev_total\n )\n\nSELECT\n CAST(coalesce(now_total, 0) AS INTEGER) AS commits,\n CAST(coalesce(prev_total, 0) AS INTEGER) AS commits_previous,\n if(coalesce(prev_total, 0) > 0, round((coalesce(now_total, 0) - coalesce(prev_total, 0)) * 100.0 / coalesce(prev_total, 0), 1), NULL) AS rate\nFROM totals\n"
+ },
+ "createdAt": "2026-05-28 11:00:00",
+ "updatedAt": "2026-05-28 11:00:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa66666664": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa66666664",
+ "title": "Pull requests",
+ "description": "GitHub PRs created via gh pr inside coding-agent sessions (parsed out of Bash / shell hooks). Uses greatest(session-rollup-attr, count of coding_agent.git.pull_request spans).",
+ "type": "STAT_CARD",
+ "properties": {
+ "value": "0.prs",
+ "trend": "0.rate",
+ "trendSuffix": "%",
+ "color": "#6366f1"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n (end_time - start_time) AS duration,\n (start_time - duration) AS prev_start_time,\n (end_time - duration) AS prev_end_time,\n per_chat_now AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user,\n greatest(\n toInt64OrZero(any(SpanAttributes['coding_agent.session.pr_count'])),\n toInt64(countIf(SpanName = 'coding_agent.git.pull_request'))\n ) AS prs\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= start_time AND Timestamp <= end_time\n GROUP BY chat_id, vendor\n ),\n per_chat_prev AS (\n SELECT\n coalesce(\n nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),\n nullIf(SpanAttributes['coding_agent.session.id'], ''),\n nullIf(ResourceAttributes['coding_agent.session.id'], '')\n ) AS chat_id,\n coalesce( nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(SpanAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], ''), 'unknown' ) AS vendor,\n coalesce(\n nullIf(any(SpanAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),\n nullIf(any(ResourceAttributes['service.name']), ''),\n 'unknown'\n ) AS user,\n greatest(\n toInt64OrZero(any(SpanAttributes['coding_agent.session.pr_count'])),\n toInt64(countIf(SpanName = 'coding_agent.git.pull_request'))\n ) AS prs\n FROM otel_traces\n WHERE (\n notEmpty(SpanAttributes['coding_agent.session.id'])\n OR (ResourceAttributes['service.name'] = 'claude-code'\n AND (notEmpty(SpanAttributes['session.id']) OR notEmpty(ResourceAttributes['session.id'])))\n )\n AND Timestamp >= prev_start_time AND Timestamp <= prev_end_time\n GROUP BY chat_id, vendor\n ),\n totals AS (\n SELECT\n (SELECT toInt64(sumOrNull(prs)) FROM per_chat_now WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS now_total,\n (SELECT toInt64(sumOrNull(prs)) FROM per_chat_prev WHERE 1=1{{#filter.vendor}} AND vendor = '{{filter.vendor}}'{{/filter.vendor}}{{#filter.user}} AND user = '{{filter.user}}'{{/filter.user}}) AS prev_total\n )\n\nSELECT\n CAST(coalesce(now_total, 0) AS INTEGER) AS prs,\n CAST(coalesce(prev_total, 0) AS INTEGER) AS prs_previous,\n if(coalesce(prev_total, 0) > 0, round((coalesce(now_total, 0) - coalesce(prev_total, 0)) * 100.0 / coalesce(prev_total, 0), 1), NULL) AS rate\nFROM totals\n"
+ },
+ "createdAt": "2026-05-28 11:00:00",
+ "updatedAt": "2026-05-28 11:00:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa66666665": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa66666665",
+ "title": "Lines over time",
+ "description": "Lines accepted vs rejected bucketed across the window. Reads coding_agent.edit.decision spans directly so the time series stays live for in-flight Codex sessions (which never emit a SessionEnd rollup).",
+ "type": "AREA_CHART",
+ "properties": {
+ "xAxis": "request_time",
+ "yAxes": [
+ {
+ "key": "accepted",
+ "color": "#10b981"
+ },
+ {
+ "key": "rejected",
+ "color": "#ef4444"
+ }
+ ]
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time,\n dateDiff('day', start_time, end_time) AS days_diff,\n dateDiff('year', start_time, end_time) AS years_diff,\n multiIf(\n years_diff >= 1, 'month',\n days_diff <= 1, 'hour',\n 'day'\n ) AS date_granularity\n\nSELECT\n CAST(sumIf(\n toInt64OrZero(SpanAttributes['coding_agent.edit.lines.added']),\n SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted')\n ) AS INTEGER) AS accepted,\n CAST(sumIf(\n toInt64OrZero(SpanAttributes['coding_agent.edit.lines.added']),\n SpanAttributes['coding_agent.edit.decision'] = 'reject'\n ) AS INTEGER) AS rejected,\n formatDateTime(DATE_TRUNC(date_granularity, Timestamp), '%Y/%m/%d %R') AS request_time\nFROM otel_traces\nWHERE\n SpanName = 'coding_agent.edit.decision'\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\nGROUP BY request_time\nORDER BY request_time"
+ },
+ "createdAt": "2026-05-28 11:00:00",
+ "updatedAt": "2026-05-28 11:00:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa66666666": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa66666666",
+ "title": "Top users by accepted lines",
+ "description": "Who is shipping with help from the agent. Lines accepted per user across the window, vendor-scoped when filter.vendor is set.",
+ "type": "BAR_CHART",
+ "properties": {
+ "xAxis": "user",
+ "yAxis": "lines",
+ "color": "#10b981"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time\n\nSELECT\n coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) AS user,\n CAST(sumIf(\n toInt64OrZero(SpanAttributes['coding_agent.edit.lines.added']),\n SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted')\n ) AS INTEGER) AS lines\nFROM otel_traces\nWHERE\n SpanName = 'coding_agent.edit.decision'\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\nGROUP BY user\nHAVING lines > 0\nORDER BY lines DESC\nLIMIT 10"
+ },
+ "createdAt": "2026-05-28 11:00:00",
+ "updatedAt": "2026-05-28 11:00:00"
+ },
+ "9a1f1c20-3b27-4f88-9d51-1aaa66666667": {
+ "id": "9a1f1c20-3b27-4f88-9d51-1aaa66666667",
+ "title": "Acceptance breakdown",
+ "description": "Distribution of edit decisions (accept / auto_accepted / reject) across the window. Highlights when the agent is being auto-trusted vs human-reviewed.",
+ "type": "PIE_CHART",
+ "properties": {
+ "labelPath": "decision",
+ "valuePath": "edits",
+ "color": "#10b981"
+ },
+ "config": {
+ "query": "WITH\n parseDateTimeBestEffort('{{filter.timeLimit.start}}') AS start_time,\n parseDateTimeBestEffort('{{filter.timeLimit.end}}') AS end_time\n\nSELECT\n coalesce(nullIf(SpanAttributes['coding_agent.edit.decision'], ''), 'unknown') AS decision,\n CAST(COUNT(*) AS INTEGER) AS edits\nFROM otel_traces\nWHERE\n SpanName = 'coding_agent.edit.decision'\n AND SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted', 'reject')\n AND Timestamp >= start_time AND Timestamp <= end_time\n {{#filter.vendor}}AND coalesce(nullIf(SpanAttributes['coding_agent.client'], ''), nullIf(ResourceAttributes['gen_ai.agent.name'], ''), nullIf(ResourceAttributes['service.name'], '')) = '{{filter.vendor}}'{{/filter.vendor}}\n {{#filter.user}}AND coalesce(\n nullIf(SpanAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['gen_ai.user.name'], ''),\n nullIf(ResourceAttributes['service.name'], ''),\n 'unknown'\n ) = '{{filter.user}}'{{/filter.user}}\nGROUP BY decision\nORDER BY edits DESC"
+ },
+ "createdAt": "2026-05-28 11:00:00",
+ "updatedAt": "2026-05-28 11:00:00"
+ }
+ },
+ "layouts": {
+ "lg": [
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa11111111",
+ "x": 0,
+ "y": 0,
+ "w": 1,
+ "h": 1
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa11111112",
+ "x": 1,
+ "y": 0,
+ "w": 1,
+ "h": 1
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa11111113",
+ "x": 2,
+ "y": 0,
+ "w": 1,
+ "h": 1
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa11111114",
+ "x": 3,
+ "y": 0,
+ "w": 1,
+ "h": 1
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa22222221",
+ "x": 0,
+ "y": 1,
+ "w": 3,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa22222222",
+ "x": 3,
+ "y": 1,
+ "w": 1,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa33333331",
+ "x": 0,
+ "y": 3,
+ "w": 2,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa33333332",
+ "x": 2,
+ "y": 3,
+ "w": 2,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa33333333",
+ "x": 0,
+ "y": 5,
+ "w": 2,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa44444441",
+ "x": 2,
+ "y": 5,
+ "w": 1,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa44444442",
+ "x": 3,
+ "y": 5,
+ "w": 1,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa55555551",
+ "x": 0,
+ "y": 7,
+ "w": 1,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa55555552",
+ "x": 1,
+ "y": 7,
+ "w": 1,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa55555553",
+ "x": 2,
+ "y": 7,
+ "w": 2,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa66666661",
+ "x": 0,
+ "y": 9,
+ "w": 1,
+ "h": 1
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa66666662",
+ "x": 1,
+ "y": 9,
+ "w": 1,
+ "h": 1
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa66666663",
+ "x": 2,
+ "y": 9,
+ "w": 1,
+ "h": 1
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa66666664",
+ "x": 3,
+ "y": 9,
+ "w": 1,
+ "h": 1
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa66666665",
+ "x": 0,
+ "y": 10,
+ "w": 2,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa66666666",
+ "x": 2,
+ "y": 10,
+ "w": 1,
+ "h": 2
+ },
+ {
+ "i": "9a1f1c20-3b27-4f88-9d51-1aaa66666667",
+ "x": 3,
+ "y": 10,
+ "w": 1,
+ "h": 2
+ }
+ ]
+ }
+}
diff --git a/src/client/src/clickhouse/seed/dashboards.ts b/src/client/src/clickhouse/seed/dashboards.ts
index 3573da31..1d4cb4d4 100644
--- a/src/client/src/clickhouse/seed/dashboards.ts
+++ b/src/client/src/clickhouse/seed/dashboards.ts
@@ -1,43 +1,163 @@
-import { importBoardLayout, isBoardTableEmpty } from "@/lib/platform/manage-dashboard/board";
+import {
+ boardExistsByTitle,
+ importBoardLayout,
+ isBoardTableEmpty,
+} from "@/lib/platform/manage-dashboard/board";
+import { updateWidget } from "@/lib/platform/manage-dashboard/widget";
import llmDashboard from "../seed-data/openlit-dashboard-LLM-dashboard-layout.json";
import vectorDbDashboard from "../seed-data/openlit-dashboard-Vector-DB-layout.json";
import gpuDashboard from "../seed-data/openlit-dashboard-GPU-dashboard-layout.json";
+import codingAgentsDashboard from "../seed-data/openlit-dashboard-coding-agents-layout.json";
-export default async function CreateCustomDashboardsSeed(databaseConfigId?: string) {
- console.log(
- `********* Seeding Dashboards *********`
- );
+/**
+ * Per-board seed entry. We treat the JSON file's `title` as the
+ * de-duplication key — if a board with that exact title is already in
+ * the table, the seed is a no-op; otherwise we import it.
+ *
+ * This is a behavioral upgrade over the original "table empty"
+ * gate: the gate caused new seed files (Coding Agents) to be skipped
+ * forever on stacks that already had the older boards seeded. Per-
+ * board upsert lets us add new built-in dashboards without manual
+ * migration.
+ *
+ * `seedTitle` is duplicated from the JSON so we don't have to load the
+ * file just to read its title field (it's typed as a JSON import).
+ */
+const SEEDED_DASHBOARDS: ReadonlyArray<{
+ seedTitle: string;
+ layout: any;
+}> = [
+ { seedTitle: "LLM dashboard", layout: llmDashboard },
+ { seedTitle: "Vector DB", layout: vectorDbDashboard },
+ { seedTitle: "GPU dashboard", layout: gpuDashboard },
+ { seedTitle: "Coding Agents", layout: codingAgentsDashboard },
+];
- const { data: isBoardTableEmptyData, err: isBoardTableEmptyErr } = await isBoardTableEmpty(databaseConfigId);
+export default async function CreateCustomDashboardsSeed(
+ databaseConfigId?: string
+) {
+ console.log(`********* Seeding Dashboards *********`);
- if (isBoardTableEmptyErr) {
- console.log(
- `********* Error checking if board table is empty *********`
- );
- console.log(isBoardTableEmptyErr);
+ const { data: tableEmpty, err: emptyErr } = await isBoardTableEmpty(
+ databaseConfigId
+ );
+ if (emptyErr) {
+ console.log(`********* Error checking if board table is empty *********`);
+ console.log(emptyErr);
return;
}
- if (!isBoardTableEmptyData) {
- console.log(
- `********* Board Table is not empty hence skipping seeding *********`
- );
- return;
- }
+ let seededCount = 0;
+ let skippedCount = 0;
+ const failures: string[] = [];
- const { err: llmDashboardErr } = await importBoardLayout(llmDashboard, databaseConfigId);
- const { err: vectorDbDashboardErr } = await importBoardLayout(vectorDbDashboard, databaseConfigId);
- const { err: gpuDashboardErr } = await importBoardLayout(gpuDashboard, databaseConfigId);
+ for (const entry of SEEDED_DASHBOARDS) {
+ // When the table is empty we know all boards must be created;
+ // skip the per-title existence check to save a round-trip per
+ // dashboard on a fresh stack.
+ let exists = false;
+ if (!tableEmpty) {
+ const { data, err } = await boardExistsByTitle(
+ entry.seedTitle,
+ databaseConfigId
+ );
+ if (err) {
+ failures.push(`${entry.seedTitle}: ${String(err)}`);
+ continue;
+ }
+ exists = Boolean(data);
+ }
- if (llmDashboardErr || vectorDbDashboardErr || gpuDashboardErr) {
- console.log(
- `********* Seeding Dashboards Failed *********`
- );
- console.log(llmDashboardErr, vectorDbDashboardErr, gpuDashboardErr);
- return;
+ if (exists) {
+ skippedCount++;
+ // Existing seeds get a per-widget SQL sync. We update only
+ // the `config` field (which holds the SQL `query` for each
+ // widget) so layout / title / properties the user might
+ // have nudged stay intact. Widget IDs are stable in the
+ // seed JSON which makes this a safe by-id upsert. Without
+ // this step, fixes to the seed SQL (e.g. the canonical
+ // per-session cost formula in the Total Cost widget) would
+ // only land for brand-new installs, never for stacks that
+ // already had the board.
+ try {
+ await syncWidgetSqlFromSeed(entry.layout);
+ } catch (e: any) {
+ failures.push(
+ `${entry.seedTitle} sync: thrown ${e?.message || String(e)}`
+ );
+ }
+ continue;
+ }
+
+ try {
+ const { err: importErr } = await importBoardLayout(
+ entry.layout,
+ databaseConfigId,
+ // Preserve the seed JSON's widget ids so the per-boot
+ // `syncWidgetSqlFromSeed` step below can update widgets
+ // by id when the seed file ships an SQL or properties
+ // fix. Public/user-driven imports keep the default
+ // (regenerate ids) to avoid colliding with whatever's
+ // already in the widget table.
+ { preserveWidgetIds: true }
+ );
+ if (importErr) {
+ failures.push(`${entry.seedTitle}: ${String(importErr)}`);
+ continue;
+ }
+ seededCount++;
+ } catch (e: any) {
+ failures.push(
+ `${entry.seedTitle}: thrown ${e?.message || String(e)}`
+ );
+ continue;
+ }
+
+ // `importBoardLayout` reads back the newly-inserted board with
+ // `ORDER BY created_at DESC LIMIT 1`. ClickHouse stores
+ // `created_at` at second precision, so two seeds in the same
+ // second can collide and the wrong board id is returned to the
+ // widget-attach step. A small spacer avoids the race without
+ // forcing a schema migration; we'll revisit when we move the
+ // import path off of timestamp-based lookup.
+ await new Promise((r) => setTimeout(r, 1100));
+ }
+
+ if (failures.length) {
+ console.log(`********* Seeding Dashboards Failed *********`);
+ for (const f of failures) console.log(f);
}
console.log(
- `********* Seeding Dashboards Completed *********`
+ `********* Seeding Dashboards Completed (seeded ${seededCount}, skipped ${skippedCount}) *********`
);
-}
\ No newline at end of file
+}
+
+/**
+ * Rewrite widget SQL from the seed JSON onto already-seeded widgets,
+ * matched by widget id. Only the `config` field is touched, which
+ * holds the SQL `query` (and any rendering knobs the widget needs to
+ * execute its query). User-editable surfaces — title, description,
+ * properties (color / value paths) — are left alone so a workspace
+ * that re-themed a widget doesn't get reset on the next boot.
+ *
+ * Why we do this without a version bump: shipping a fix to the
+ * canonical cost formula needs to take effect everywhere the
+ * dashboard widgets read it (Total Cost stat card today; any future
+ * per-vendor / per-user widgets the same way). The widget IDs in
+ * the seed JSON are stable UUIDs, so by-id targeting is safe — and
+ * gives us a one-line escape hatch for any "the seed got wrong"
+ * fixes. The cost is a few extra UPDATEs on each boot, which is
+ * cheap (4 widgets × 1 UPDATE each).
+ */
+async function syncWidgetSqlFromSeed(layout: any): Promise<void> {
+ const widgets = (layout?.widgets || {}) as Record<string, any>;
+ for (const id of Object.keys(widgets)) {
+ const seed = widgets[id];
+ if (!seed?.config) continue;
+ await updateWidget({
+ id,
+ config: seed.config,
+ } as any);
+ }
+}
diff --git a/src/client/src/components/(playground)/agents/agent-header.tsx b/src/client/src/components/(playground)/agents/agent-header.tsx
index 9cc1c5f5..18dd529c 100644
--- a/src/client/src/components/(playground)/agents/agent-header.tsx
+++ b/src/client/src/components/(playground)/agents/agent-header.tsx
@@ -1,11 +1,17 @@
"use client";
-import { useCallback, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import Link from "next/link";
+import { useSearchParams } from "next/navigation";
import { ArrowLeft, RefreshCw } from "lucide-react";
import { toast } from "sonner";
import getMessage from "@/constants/messages";
import type { UnifiedAgent } from "@/types/agents";
+import {
+ CodingAgentVendorIcon,
+ codingAgentVendorLabel,
+ hasCodingAgentVendorIcon,
+} from "@/components/svg/coding-agents";
interface AgentHeaderProps {
agent: UnifiedAgent;
@@ -13,12 +19,36 @@ interface AgentHeaderProps {
rightSlot?: React.ReactNode;
}
+// Map a `?from=<tab>` source the table click stamped on the
+// drill-in URL back into the agents-hub tab query the user expects
+// to land on. We default to `services` (Applications) for
+// unrecognised values so legacy links don't break, and to `coding`
+// for coding-sourced agents — that way a deep link to a Claude
+// Code session detail still routes back to the right tab even if
+// `from` is missing.
+function buildBackHref(
+ from: string | null,
+ agentSource: UnifiedAgent["source"] | undefined
+) {
+ const ALLOWED = new Set(["services", "controllers", "coding"]);
+ let tab = from && ALLOWED.has(from) ? from : null;
+ if (!tab) {
+ tab = agentSource === "coding" ? "coding" : "services";
+ }
+ return tab === "services" ? "/agents" : `/agents?tab=${tab}`;
+}
+
export default function AgentHeader({
agent,
onRefresh,
rightSlot,
}: AgentHeaderProps) {
const [isRefreshing, setIsRefreshing] = useState(false);
+ const searchParams = useSearchParams();
+ const backHref = useMemo(
+ () => buildBackHref(searchParams?.get("from") || null, agent.source),
+ [searchParams, agent.source]
+ );
const handleRefresh = useCallback(async () => {
setIsRefreshing(true);
@@ -44,7 +74,7 @@ export default function AgentHeader({
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<Link
- href="/agents"
+ href={backHref}
className="flex items-center gap-1.5 text-sm text-stone-500 dark:text-stone-400 hover:text-stone-900 dark:hover:text-stone-100"
>
<ArrowLeft className="w-4 h-4" />
@@ -65,8 +95,25 @@ export default function AgentHeader({
</div>
<div className="flex items-center justify-between gap-3 flex-wrap">
- <h1 className="text-2xl font-semibold text-stone-900 dark:text-stone-100">
- {agent.service_name}
+ {/* For coding-agent rows we render the vendor logo + the
+ pretty vendor label (e.g. "Claude Code" instead of
+ the raw `claude-code` service name). For services /
+ controllers we keep the existing service_name
+ rendering — no logo, no transformation. */}
+ <h1 className="text-2xl font-semibold text-stone-900 dark:text-stone-100 inline-flex items-center gap-2">
+ {hasCodingAgentVendorIcon(agent.coding_agent_vendor) ? (
+ <>
+ <CodingAgentVendorIcon
+ vendor={agent.coding_agent_vendor}
+ className="h-7 w-7 shrink-0"
+ />
+ <span>
+ {codingAgentVendorLabel(agent.coding_agent_vendor)}
+ </span>
+ </>
+ ) : (
+ agent.service_name
+ )}
</h1>
{rightSlot && <div className="shrink-0">{rightSlot}</div>}
</div>
diff --git a/src/client/src/components/(playground)/coding-agents/coding-agent-detail.tsx b/src/client/src/components/(playground)/coding-agents/coding-agent-detail.tsx
new file mode 100644
index 00000000..9d9c04a9
--- /dev/null
+++ b/src/client/src/components/(playground)/coding-agents/coding-agent-detail.tsx
@@ -0,0 +1,143 @@
+"use client";
+
+/**
+ * Coding-agent detail view rendered when /agents/[agentKey] resolves to a
+ * row with `source === "coding"`. We keep the same outer chrome (header,
+ * breadcrumbs) as the SDK/controller detail page but swap the body for a
+ * tab set that's relevant to a fleet of coding-agent users:
+ *
+ * - Overview — rollups (sessions, cost, active users, top
+ * models / tools / repos) over the time window
+ * selected in the global filter picker — no fixed
+ * 24h fallback. The Overview tab body is the
+ * embedded seeded dashboard; its widgets read
+ * `{{filter.timeLimit.*}}` so they move with the
+ * picker too.
+ * - Sessions — recent sessions with drill-in to per-session detail.
+ * - Dashboard — embedded seeded board for this vendor.
+ *
+ * Sessions and Dashboard are scaffolded here and wired up by the
+ * queries-lib + api-routes + dashboard-seed todos. The Overview pulls
+ * from the materialized rollups already on UnifiedAgent so it's live the
+ * moment the materializer runs.
+ */
+
+import dynamic from "next/dynamic";
+import {
+ LayoutGrid,
+ List,
+ Loader2,
+ Users,
+} from "lucide-react";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@/components/ui/tabs";
+import getMessage from "@/constants/messages";
+import type { UnifiedAgent } from "@/types/agents";
+
+// The sessions list and embedded dashboard are heavier; lazy-load them
+// so a user that just wants Overview doesn't pay for echarts + the
+// session table on initial render.
+const CodingSessionsTab = dynamic(
+ () => import("./coding-sessions-tab"),
+ {
+ loading: () => <TabLoading label={getMessage().AGENTS_LOADING_REQUESTS} />,
+ ssr: false,
+ }
+);
+const CodingDashboardTab = dynamic(
+ () => import("./coding-dashboard-tab"),
+ {
+ loading: () => <TabLoading label={getMessage().AGENTS_LOADING_DASHBOARD} />,
+ ssr: false,
+ }
+);
+const CodingUsersTab = dynamic(
+ () => import("./coding-users-tab"),
+ {
+ loading: () => <TabLoading label={getMessage().AGENTS_LOADING_REQUESTS} />,
+ ssr: false,
+ }
+);
+
+interface CodingAgentDetailProps {
+ agent: UnifiedAgent;
+ tab: string;
+ onTabChange: (tab: string) => void;
+}
+
+export default function CodingAgentDetail({
+ agent,
+ tab,
+ onTabChange,
+}: CodingAgentDetailProps) {
+ // Overview is just the embedded "Coding Agents" board. The earlier
+ // StatTile cluster + Client info card duplicated values that
+ // already live on the board (cost, sessions, users) so we removed
+ // them; the dashboard widgets + the page header carry that data.
+ return (
+ <Tabs value={tab} onValueChange={onTabChange} className="w-full">
+ <TabsList className="h-auto rounded-none border-b border-stone-200 dark:border-stone-800 bg-transparent p-0 w-full justify-start gap-1">
+ <UnderlineTab
+ value="overview"
+ icon={<LayoutGrid className="w-3.5 h-3.5" />}
+ label={getMessage().AGENTS_TAB_OVERVIEW}
+ />
+ <UnderlineTab
+ value="sessions"
+ icon={<List className="w-3.5 h-3.5" />}
+ label={getMessage().AGENTS_CODING_TAB_SESSIONS}
+ />
+ <UnderlineTab
+ value="users"
+ icon={<Users className="w-3.5 h-3.5" />}
+ label={getMessage().AGENTS_CODING_USERS_SHORT_LABEL}
+ />
+ </TabsList>
+
+ <TabsContent value="overview" className="mt-4">
+ <CodingDashboardTab agent={agent} />
+ </TabsContent>
+
+ <TabsContent value="sessions" className="mt-4">
+ <CodingSessionsTab agent={agent} />
+ </TabsContent>
+
+ <TabsContent value="users" className="mt-4">
+ <CodingUsersTab agent={agent} />
+ </TabsContent>
+ </Tabs>
+ );
+}
+
+function UnderlineTab({
+ value,
+ icon,
+ label,
+}: {
+ value: string;
+ icon: React.ReactNode;
+ label: string;
+}) {
+ return (
+ <TabsTrigger
+ value={value}
+ className="rounded-none border-b-2 border-transparent bg-transparent shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-stone-900 dark:data-[state=active]:text-stone-100 data-[state=active]:shadow-none px-3 py-2 text-sm text-stone-500 dark:text-stone-400 hover:text-stone-700 dark:hover:text-stone-200 -mb-px flex items-center gap-1.5 relative"
+ >
+ {icon}
+ {label}
+ </TabsTrigger>
+ );
+}
+
+function TabLoading({ label }: { label: string }) {
+ return (
+ <div className="flex items-center justify-center py-12 text-sm text-stone-500 dark:text-stone-400 gap-2">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ {label}
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/coding-agents/coding-dashboard-tab.tsx b/src/client/src/components/(playground)/coding-agents/coding-dashboard-tab.tsx
new file mode 100644
index 00000000..95191637
--- /dev/null
+++ b/src/client/src/components/(playground)/coding-agents/coding-dashboard-tab.tsx
@@ -0,0 +1,341 @@
+"use client";
+
+/**
+ * Dashboard tab for the coding-agent detail page.
+ *
+ * Embeds the seeded "Coding Agents" board inline (read-only) instead
+ * of deep-linking out — same in-page rendering pattern that the LLM
+ * Observability dashboard uses on the Applications detail page. We
+ * resolve the seeded board by exact title (constant
+ * `CODING_AGENTS_DASHBOARD_TITLE` mirrors the seed JSON's `title`
+ * field). On rename, we'd rev that constant alongside the seed file.
+ *
+ * The Dashboard component already does width-aware layout, so we just
+ * need to scope it to the coding-agent vendor by passing a `runFilters`
+ * value through. The vendor scoping is enforced server-side because
+ * the seed widgets all carry coding_agent.client filters in their
+ * SQL templates.
+ */
+
+import { useEffect, useMemo, useState } from "react";
+import Link from "next/link";
+import { useSearchParams } from "next/navigation";
+import { ArrowUpRight, HelpCircle, Loader2, X } from "lucide-react";
+import Dashboard from "@/components/(playground)/manage-dashboard/board-creator";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ DashboardConfig,
+ Widget,
+} from "@/components/(playground)/manage-dashboard/board-creator/types";
+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import { getFilterParamsForDashboard } from "@/helpers/client/filter";
+import { useFilters } from "@/selectors/filter";
+import getMessage from "@/constants/messages";
+import type { UnifiedAgent } from "@/types/agents";
+
+const CODING_AGENTS_DASHBOARD_TITLE = "Coding Agents";
+
+interface CodingDashboardTabProps {
+ agent: UnifiedAgent;
+ /**
+ * Pre-applied user filter — set by the per-user page so the same
+ * board renders pinned to one developer. URL `?user=` still wins
+ * (set by Top-users widget click) so the filter cascades smoothly.
+ */
+ pinnedUser?: string | null;
+ /**
+ * Override vendor scoping. The per-vendor detail page pins to
+ * `agent.coding_agent_vendor` so the dashboard never aggregates
+ * across vendors (which would make the Total Cost widget here
+ * disagree with the agents-hub card and the Sessions/Users
+ * tabs). The per-user page leaves it `null` so the user's
+ * cross-vendor view stays intact.
+ */
+ pinnedVendor?: string | null;
+}
+
+interface BoardSummary {
+ id: string;
+ title: string;
+}
+
+export default function CodingDashboardTab({
+ agent,
+ pinnedUser = null,
+ pinnedVendor: pinnedVendorProp,
+}: CodingDashboardTabProps) {
+ // Default to the agent's vendor when no explicit override was
+ // passed — the per-user page sends `pinnedVendor={null}` to opt
+ // out, while the per-vendor detail page just inherits via the
+ // agent prop.
+ const pinnedVendor =
+ pinnedVendorProp === null
+ ? null
+ : pinnedVendorProp ?? agent.coding_agent_vendor ?? null;
+ const { fireRequest } = useFetchWrapper();
+ const { fireRequest: fireRunQuery } = useFetchWrapper();
+ const { details: filter } = useFilters();
+ const searchParams = useSearchParams();
+ // URL `?user=` overrides the pinned prop so the Top-users widget
+ // link can route the same board into a per-user view without a
+ // page navigation. Falls back to the pinned prop (used by the
+ // dedicated `/coding-agents/users/[userId]` page).
+ const activeUser = searchParams?.get("user") || pinnedUser || null;
+ const [boardId, setBoardId] = useState<string | null>(null);
+ const [config, setConfig] = useState<DashboardConfig | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ setLoading(true);
+ const { response: boardsRes } = await fireRequest({
+ url: "/api/manage-dashboard/board",
+ requestType: "GET",
+ });
+ if (cancelled) return;
+ const boards = (boardsRes?.data || []) as BoardSummary[];
+ const match =
+ boards.find((b) => b.title === CODING_AGENTS_DASHBOARD_TITLE) ||
+ null;
+ if (!match) {
+ setError("not_seeded");
+ return;
+ }
+ setBoardId(match.id);
+ const { response: layoutRes, error: layoutErr } = await fireRequest({
+ url: `/api/manage-dashboard/board/${match.id}/layout`,
+ requestType: "GET",
+ });
+ if (cancelled) return;
+ if (layoutErr) {
+ setError(String(layoutErr));
+ return;
+ }
+ if (layoutRes?.data) {
+ setConfig(layoutRes.data as DashboardConfig);
+ setError(null);
+ }
+ } catch (e) {
+ if (!cancelled) setError(String(e));
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [fireRequest]);
+
+ const runFilters = useMemo(() => {
+ const base = getFilterParamsForDashboard({ ...filter });
+ // Inject the active-user filter as a top-level key on the
+ // filter envelope so widget SQL templates can reference it via
+ // `{{filter.user}}` (or pull it from the bag in custom
+ // renderers). We keep it nullable rather than empty-string so
+ // "no user filter" stays distinguishable from "explicitly empty
+ // user".
+ //
+ // `filter.vendor` is the same shape: when set (per-vendor
+ // detail page) the seed widgets gate their WHERE clauses on
+ // `coding_agent.client = '{{filter.vendor}}'`. When unset
+ // (per-user page) the widgets aggregate cross-vendor.
+ const next: Record<string, unknown> = { ...base };
+ if (pinnedVendor) {
+ next.vendor = pinnedVendor;
+ }
+ if (activeUser) {
+ next.user = activeUser;
+ next.codingAgentUser = activeUser;
+ }
+ return next;
+ }, [filter, activeUser, pinnedVendor]);
+
+ const runQuery = async (
+ widgetId: string,
+ params: Record<string, unknown>
+ ) => {
+ const data = await fireRunQuery({
+ requestType: "POST",
+ url: "/api/manage-dashboard/query/run",
+ body: JSON.stringify({ widgetId, filter: runFilters, ...params }),
+ });
+ return data.response;
+ };
+
+ // We render the embedded dashboard read-only — editing the layout
+ // belongs on /d/[id] where the full chrome (filters, share, edit
+ // affordances) lives. Adopting the read-only mode also disables
+ // drag/drop/resize so it never mutates the saved layout from a
+ // per-vendor view.
+ const handleSave = async () => {
+ // no-op (readonly)
+ };
+ const handleWidgetCrud = async (_updates: Partial<Widget>) => {
+ throw new Error("readonly_widget_edit_disabled");
+ };
+ const fetchExistingWidgets = async () => [] as Widget[];
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center py-12 text-sm text-stone-500 dark:text-stone-400 gap-2">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ {getMessage().AGENTS_LOADING_DASHBOARD}
+ </div>
+ );
+ }
+
+ if (error === "not_seeded") {
+ return (
+ <div className="border dark:border-stone-800 rounded-lg p-6 text-sm text-stone-500 dark:text-stone-400">
+ {getMessage().AGENTS_CODING_DASHBOARD_NOT_SEEDED}
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="border border-red-200 dark:border-red-900/50 rounded-lg p-6 text-sm text-red-700 dark:text-red-400">
+ {error}
+ </div>
+ );
+ }
+
+ if (!config) return null;
+
+ const showUserPill =
+ !!activeUser && searchParams?.get("user") === activeUser;
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-3">
+ <ClassificationHelpPopover />
+ {showUserPill && (
+ <Link
+ href={typeof window !== "undefined" ? window.location.pathname : "."}
+ className="inline-flex items-center gap-1.5 rounded-full border border-violet-200 bg-violet-50 px-2 py-1 text-xs font-medium text-violet-700 hover:bg-violet-100 dark:border-violet-900 dark:bg-violet-950/40 dark:text-violet-300 dark:hover:bg-violet-900/40"
+ title="Clear user filter"
+ >
+ <span className="font-mono">@{activeUser}</span>
+ <X className="h-3 w-3" />
+ </Link>
+ )}
+ </div>
+ {boardId && (
+ <Link
+ href={`/d/${boardId}`}
+ className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
+ >
+ {getMessage().AGENTS_CODING_DASHBOARD_OPEN}
+ <ArrowUpRight className="w-3.5 h-3.5" />
+ </Link>
+ )}
+ </div>
+ <Dashboard
+ className="overflow-visible"
+ initialConfig={config}
+ readonly
+ runQuery={runQuery}
+ onSave={handleSave}
+ handleWidgetCrud={handleWidgetCrud}
+ fetchExistingWidgets={fetchExistingWidgets}
+ runFilters={runFilters}
+ />
+ </div>
+ );
+}
+
+/**
+ * Inline explainer for the "Personal vs work classification" donut on
+ * the Coding Agents dashboard. Users (rightly) ask "how was this
+ * decided?" — the answer is below. The rules mirror
+ * `cli/internal/coding/classify/classify.go`; if that file's branch
+ * order changes, update this copy.
+ */
+function ClassificationHelpPopover() {
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className="inline-flex items-center gap-1.5 text-xs text-stone-500 dark:text-stone-400 hover:text-stone-900 dark:hover:text-stone-100 transition-colors"
+ >
+ <HelpCircle className="w-3.5 h-3.5" />
+ How is classification computed?
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ className="w-[420px] text-xs leading-relaxed"
+ >
+ <div className="space-y-3">
+ <div className="font-medium text-stone-900 dark:text-stone-100 text-sm">
+ Work vs personal classification
+ </div>
+ <p className="text-stone-600 dark:text-stone-400">
+ Each session is labelled <code>work</code>,{" "}
+ <code>personal</code>, or <code>unknown</code> based on two
+ high-confidence signals — never on keystroke timing or
+ hours-of-day.
+ </p>
+ <ol className="list-decimal pl-4 space-y-1.5 text-stone-600 dark:text-stone-400">
+ <li>
+ <strong>Repo origin.</strong> The session&rsquo;s git
+ remote is matched against{" "}
+ <code>OPENLIT_CODING_REPO_ALLOWLIST</code> (a
+ comma-separated list of substring patterns).
+ </li>
+ <li>
+ <strong>API-key allowlist.</strong> The OpenLit org can
+ register which API keys are work identities. v1 ships
+ without that surface, so currently the repo signal
+ carries the call.
+ </li>
+ </ol>
+ <div className="rounded border border-stone-200 dark:border-stone-800 p-2 space-y-1.5">
+ <div className="font-medium text-stone-900 dark:text-stone-100">
+ Decision rules (in order)
+ </div>
+ <ul className="text-stone-600 dark:text-stone-400 space-y-1">
+ <li>
+ <span className="text-emerald-600 dark:text-emerald-400">
+ work
+ </span>{" "}
+ — repo on allowlist (with or without API-key signal).
+ </li>
+ <li>
+ <span className="text-amber-600 dark:text-amber-400">
+ personal
+ </span>{" "}
+ — allowlist exists and repo is not on it; or
+ API-key is positively not on the org allowlist while
+ the repo is.
+ </li>
+ <li>
+ <span className="text-stone-500 dark:text-stone-400">
+ unknown
+ </span>{" "}
+ — no allowlist configured, or signals conflict (e.g.
+ work API-key on a non-allowlisted repo). Surfaces in
+ the dispute UI.
+ </li>
+ </ul>
+ </div>
+ <p className="text-stone-500 dark:text-stone-500 text-[11px]">
+ Disagree with a classification? File a dispute via the
+ platform API — surfacing it from the Sessions tab is
+ planned for the next release. Disputes survive future
+ re-classifications.
+ </p>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/client/src/components/(playground)/coding-agents/coding-quick-filters.tsx b/src/client/src/components/(playground)/coding-agents/coding-quick-filters.tsx
new file mode 100644
index 00000000..3421c399
--- /dev/null
+++ b/src/client/src/components/(playground)/coding-agents/coding-quick-filters.tsx
@@ -0,0 +1,202 @@
+"use client";
+
+/**
+ * User-picker dropdown rendered next to the global filter button on
+ * the Sessions tab toolbar. Reads/writes the `?user=` URL param so
+ * deep-links and the back button round-trip cleanly with the table
+ * state.
+ *
+ * The picker's option set is fetched from
+ * `/api/coding-agents/users?limit=50` (vendor-scoped when the agent
+ * detail page pins a vendor). The list endpoint already enforces the
+ * privacy cohort floor, so `low_cohort` users that come back from the
+ * API are filtered client-side here — selecting a masked user
+ * wouldn't navigate anywhere useful.
+ *
+ * F5 / F9 cleanup note: the previous "CodingQuickFilters" default
+ * export (a redundant inline filter bar) was removed; this file now
+ * holds only the picker that is actually rendered by
+ * `<CodingSessionsTab>`.
+ */
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { ChevronDown, User, X } from "lucide-react";
+
+interface CodingUserRow {
+ user: string;
+ session_count?: number;
+}
+
+interface CodingUserPickerProps {
+ /** When set, the user list is restricted to this vendor. */
+ vendorScope?: string | null;
+}
+
+const PICKER_LIMIT = 50;
+
+export function CodingUserPicker({ vendorScope }: CodingUserPickerProps) {
+ const router = useRouter();
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+ const selectedUser = searchParams?.get("user") || "";
+
+ const [open, setOpen] = useState(false);
+ const [users, setUsers] = useState<CodingUserRow[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const writeUserParam = useCallback(
+ (next: string | null) => {
+ const sp = new URLSearchParams(searchParams?.toString() || "");
+ if (next) {
+ sp.set("user", next);
+ } else {
+ sp.delete("user");
+ }
+ const query = sp.toString();
+ router.replace(`${pathname}${query ? `?${query}` : ""}`, {
+ scroll: false,
+ });
+ },
+ [pathname, router, searchParams]
+ );
+
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ (async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const url = new URL(
+ "/api/coding-agents/users",
+ typeof window !== "undefined"
+ ? window.location.origin
+ : "http://localhost"
+ );
+ url.searchParams.set("limit", String(PICKER_LIMIT));
+ if (vendorScope) {
+ url.searchParams.set("vendor", vendorScope);
+ }
+ const res = await fetch(url.toString());
+ if (cancelled) return;
+ if (!res.ok) {
+ setError(`HTTP ${res.status}`);
+ setUsers([]);
+ return;
+ }
+ const body = (await res.json()) as {
+ data?: CodingUserRow[];
+ records?: CodingUserRow[];
+ };
+ const rows = (body.data || body.records || []).filter(
+ (row) =>
+ row.user &&
+ row.user !== "low_cohort" &&
+ row.user !== "unknown"
+ );
+ setUsers(rows);
+ } catch (e) {
+ if (!cancelled) {
+ setError(String(e));
+ setUsers([]);
+ }
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [open, vendorScope]);
+
+ const triggerLabel = useMemo(() => {
+ if (selectedUser) return selectedUser;
+ return "All users";
+ }, [selectedUser]);
+
+ return (
+ <div className="inline-flex items-center gap-1">
+ <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 gap-1.5 text-xs font-normal"
+ >
+ <User className="h-3.5 w-3.5 text-stone-500" />
+ <span className="max-w-[180px] truncate">{triggerLabel}</span>
+ <ChevronDown className="h-3.5 w-3.5 text-stone-400" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-[260px]">
+ <DropdownMenuLabel>Filter by user</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuCheckboxItem
+ checked={!selectedUser}
+ onCheckedChange={() => writeUserParam(null)}
+ >
+ All users
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuSeparator />
+ {loading && (
+ <div className="px-2 py-1.5 text-xs text-stone-500">
+ Loading…
+ </div>
+ )}
+ {error && (
+ <div className="px-2 py-1.5 text-xs text-red-600 dark:text-red-400">
+ {error}
+ </div>
+ )}
+ {!loading && !error && users.length === 0 && (
+ <div className="px-2 py-1.5 text-xs text-stone-500">
+ No users in this window
+ </div>
+ )}
+ {users.map((row) => (
+ <DropdownMenuCheckboxItem
+ key={row.user}
+ checked={selectedUser === row.user}
+ onCheckedChange={(checked) =>
+ writeUserParam(checked ? row.user : null)
+ }
+ >
+ <div className="flex w-full items-center justify-between gap-2">
+ <span className="truncate" title={row.user}>
+ {row.user}
+ </span>
+ {typeof row.session_count === "number" && (
+ <span className="text-[10px] text-stone-500 tabular-nums">
+ {row.session_count}
+ </span>
+ )}
+ </div>
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {selectedUser && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 w-8 p-0"
+ onClick={() => writeUserParam(null)}
+ title="Clear user filter"
+ >
+ <X className="h-3.5 w-3.5" />
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/coding-agents/coding-sessions-tab.tsx b/src/client/src/components/(playground)/coding-agents/coding-sessions-tab.tsx
new file mode 100644
index 00000000..fb72e7c7
--- /dev/null
+++ b/src/client/src/components/(playground)/coding-agents/coding-sessions-tab.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+/**
+ * Sessions tab for the coding-agent detail page.
+ *
+ * After PR #1200 merged the new telemetry primitives (`<ObservabilitySignalList>`
+ * + `TraceDetailView` + resizable maximize sheet), this tab is a thin
+ * shell that pins the right vendor + optional user filter and lets the
+ * shared list/sheet machinery do the rest:
+ * - the list renders via the `'sessions'` signal config
+ * - row click opens the trace detail sheet at the session-root SpanId
+ * (Phase 2 of the coding-agents work made that SpanId stable)
+ * - the sheet has the same maximize handle as `/telemetry`
+ *
+ * The legacy table + custom session-detail sheet that lived here have
+ * been removed; the equivalent transcript / tool / edit drilldowns now
+ * live inside the trace hierarchy explorer.
+ */
+
+import { useSearchParams } from "next/navigation";
+import ObservabilitySignalList from "@/components/(playground)/observability/signal-list";
+import { getSignalConfig } from "@/components/(playground)/observability/registry";
+import { CodingUserPicker } from "./coding-quick-filters";
+import type { UnifiedAgent } from "@/types/agents";
+
+interface CodingSessionsTabProps {
+ agent: UnifiedAgent;
+}
+
+export default function CodingSessionsTab({ agent }: CodingSessionsTabProps) {
+ const searchParams = useSearchParams();
+ const pinnedVendor = agent.coding_agent_vendor || null;
+ // `?vendor=` overrides the agent-pinned vendor so deep-links from
+ // the Coding agents hub still land on the right vendor scope.
+ const vendorParam = searchParams?.get("vendor") || pinnedVendor;
+ const userParam = searchParams?.get("user") || null;
+ // The user picker is rendered as part of the global toolbar (next
+ // to the SlidersHorizontal filter button) so it stays in the same
+ // visual cluster as the time range / sorting / share controls
+ // instead of spawning a second filter bar above the table.
+ return (
+ <ObservabilitySignalList
+ config={getSignalConfig("sessions")}
+ runFilters={{
+ vendor: vendorParam,
+ user: userParam,
+ }}
+ toolbarExtraControls={
+ <CodingUserPicker vendorScope={vendorParam} />
+ }
+ />
+ );
+}
diff --git a/src/client/src/components/(playground)/coding-agents/coding-users-tab.tsx b/src/client/src/components/(playground)/coding-agents/coding-users-tab.tsx
new file mode 100644
index 00000000..772fa6d6
--- /dev/null
+++ b/src/client/src/components/(playground)/coding-agents/coding-users-tab.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+/**
+ * Users tab for the coding-agent detail page.
+ *
+ * Thin shell that pins the vendor filter and renders the shared
+ * `ObservabilitySignalList` orchestrator with the `'coding_users'`
+ * signal config. Sort options are driven by the registry's
+ * `customSortOptions` so they live in the same toolbar dropdown
+ * everywhere — see `observability/registry.tsx`.
+ *
+ * Row click navigates to `/coding-agents/users/[userId]` (handled by
+ * the registry's `getDetailHref`); the per-user page embeds the
+ * dashboard pinned to that user.
+ */
+
+import { useSearchParams } from "next/navigation";
+import ObservabilitySignalList from "@/components/(playground)/observability/signal-list";
+import { getSignalConfig } from "@/components/(playground)/observability/registry";
+import type { UnifiedAgent } from "@/types/agents";
+
+interface CodingUsersTabProps {
+ agent: UnifiedAgent;
+}
+
+export default function CodingUsersTab({ agent }: CodingUsersTabProps) {
+ const searchParams = useSearchParams();
+ const pinnedVendor = agent.coding_agent_vendor || null;
+ const vendorParam = searchParams?.get("vendor") || pinnedVendor;
+
+ return (
+ <ObservabilitySignalList
+ config={getSignalConfig("coding_users")}
+ runFilters={{ vendor: vendorParam }}
+ />
+ );
+}
diff --git a/src/client/src/components/(playground)/filter/sorting.tsx b/src/client/src/components/(playground)/filter/sorting.tsx
index 3cae03b7..8777c432 100644
--- a/src/client/src/components/(playground)/filter/sorting.tsx
+++ b/src/client/src/components/(playground)/filter/sorting.tsx
@@ -27,12 +27,21 @@ const SORTING_TYPES = [
},
];
+export type SortOption = { key: string; label: string };
+
export default function Sorting({
sorting,
includeOnlySorting,
+ customOptions,
}: {
sorting: FilterSorting;
includeOnlySorting?: string[];
+ // `customOptions` lets a signal override the OTel-attribute
+ // driven defaults with its own aggregation-level keys (e.g.
+ // "cost", "tokens", "sessions"). When set, the API for that
+ // signal interprets `filter.sorting.type` as one of these keys
+ // and maps it to its underlying ClickHouse column.
+ customOptions?: SortOption[];
}) {
const updateFilter = useRootStore(getUpdateFilter);
const onSortingChange = (type: string) => {
@@ -44,9 +53,11 @@ export default function Sorting({
updateFilter("sorting", updatedSorting);
};
- const sortingOptions = includeOnlySorting?.length
- ? SORTING_TYPES.filter((i) => includeOnlySorting.includes(i.key))
- : SORTING_TYPES;
+ const sortingOptions = customOptions?.length
+ ? customOptions
+ : includeOnlySorting?.length
+ ? SORTING_TYPES.filter((i) => includeOnlySorting.includes(i.key))
+ : SORTING_TYPES;
return (
<DropdownMenu>
diff --git a/src/client/src/components/(playground)/filter/traces-filter.tsx b/src/client/src/components/(playground)/filter/traces-filter.tsx
index a4ca5c70..ff0e27a3 100644
--- a/src/client/src/components/(playground)/filter/traces-filter.tsx
+++ b/src/client/src/components/(playground)/filter/traces-filter.tsx
@@ -10,7 +10,7 @@ import {
getUpdateAttributeKeys,
} from "@/selectors/filter";
import { useRootStore } from "@/store";
-import Sorting from "./sorting";
+import Sorting, { type SortOption } from "./sorting";
import ComboDropdown from "./combo-dropdown";
import SlideWithValue from "./slider-with-value";
import { Button } from "@/components/ui/button";
@@ -1122,24 +1122,37 @@ export default function TracesFilter({
showGroupBy = true,
showVisibilityColumns = true,
includeOnlySorting,
+ customSortOptions,
pageName,
columns,
configUrl = "/api/metrics/request/config",
attributeKeysUrl = "/api/metrics/request/attribute-keys",
customAttributeTypes = ["SpanAttributes", "ResourceAttributes", "Field"],
filterStorageScope,
+ extraControls,
}: {
total?: number;
supportDynamicFilters?: boolean;
showGroupBy?: boolean;
showVisibilityColumns?: boolean;
includeOnlySorting?: string[];
+ // When provided, replaces the default OTel-attribute sort
+ // options with aggregation-level keys (e.g. "cost", "tokens",
+ // "sessions"). Each signal type wires its own resolver in the
+ // API route — see `coding-agents/sessions/route.ts` and
+ // `coding-agents/users/route.ts`.
+ customSortOptions?: SortOption[];
pageName: PAGE;
columns: Columns<any, any>;
configUrl?: string;
attributeKeysUrl?: string;
customAttributeTypes?: CustomFilterAttributeType[];
filterStorageScope?: string;
+ // `extraControls` is rendered immediately to the LEFT of the
+ // SlidersHorizontal filter button on the toolbar. Used by
+ // coding-agent pages to drop in a User picker that's visually
+ // part of the same control cluster.
+ extraControls?: React.ReactNode;
}) {
const [isVisibleFilters, setIsVisibileFilters] = useState<boolean>(false);
const filter = useRootStore(getFilterDetails);
@@ -1230,6 +1243,7 @@ export default function TracesFilter({
<Sorting
sorting={filter.sorting}
includeOnlySorting={includeOnlySorting}
+ customOptions={customSortOptions}
/>
)}
{supportDynamicFilters && showGroupBy && (
@@ -1239,6 +1253,7 @@ export default function TracesFilter({
customAttributeTypes={customAttributeTypes}
/>
)}
+ {extraControls}
{supportDynamicFilters && (
<Button
variant="outline"
diff --git a/src/client/src/components/(playground)/observability/columns.tsx b/src/client/src/components/(playground)/observability/columns.tsx
index 27d70907..46c43f86 100644
--- a/src/client/src/components/(playground)/observability/columns.tsx
+++ b/src/client/src/components/(playground)/observability/columns.tsx
@@ -5,6 +5,64 @@ import getMessage from "@/constants/messages";
const m = getMessage();
+export type CodingAgentSessionRowView = {
+ session_id: string;
+ vendor: string;
+ user: string;
+ started_at: string;
+ ended_at: string | null;
+ duration_ms: number;
+ tool_call_count: number;
+ cost_usd: number;
+ outcome: string;
+ classification: string;
+ classification_reason: string;
+ repo_url: string;
+ repo_dirty: boolean;
+ model: string;
+ input_tokens: number;
+ output_tokens: number;
+ total_tokens: number;
+ trace_id: string;
+ session_root_span_id: string;
+ permission_mode: string;
+ working_dir: string;
+ working_dir_label: string;
+ // Per-session code-change rollups. Mirrors CodingAgentSessionRow
+ // from queries.ts. `acceptance_pct` is computed server-side from
+ // accept / (accept + reject) so the cell renders directly.
+ lines_added: number;
+ lines_removed: number;
+ lines_accepted: number;
+ lines_rejected: number;
+ edit_accept_count: number;
+ edit_reject_count: number;
+ acceptance_pct: number;
+ commit_count: number;
+ pr_count: number;
+};
+
+export type CodingAgentUserRowView = {
+ user: string;
+ last_seen: string;
+ session_count: number;
+ tool_call_count: number;
+ cost_usd: number;
+ total_tokens: number;
+ top_vendor: string;
+ classification_work: number;
+ classification_personal: number;
+ // Per-user code-impact rollups. Same dual-source shape the
+ // per-session list uses; precomputed `acceptance_pct` is over
+ // edit decisions, NOT lines.
+ lines_added: number;
+ lines_accepted: number;
+ lines_rejected: number;
+ acceptance_pct: number;
+ commit_count: number;
+ pr_count: number;
+};
+
export type LogRow = {
rowId: string | number;
Timestamp: string;
@@ -151,3 +209,368 @@ export const metricColumns: Columns<string, MetricRow> = {
enableHiding: true,
},
};
+
+function durationLabel(ms: number) {
+ if (!Number.isFinite(ms) || ms <= 0) return "—";
+ if (ms < 1000) return `${ms.toFixed(0)}ms`;
+ const sec = ms / 1000;
+ if (sec < 60) return `${sec.toFixed(1)}s`;
+ const min = sec / 60;
+ if (min < 60) return `${min.toFixed(1)}m`;
+ return `${(min / 60).toFixed(1)}h`;
+}
+
+const OUTCOME_TONE: Record<string, string> = {
+ merged:
+ "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",
+ committed:
+ "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",
+ abandoned_with_change:
+ "bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",
+};
+
+const CLASSIFICATION_TONE: Record<string, string> = {
+ work: "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
+ personal:
+ "bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",
+ disputed: "bg-rose-100 text-rose-800 dark:bg-rose-900/40 dark:text-rose-300",
+};
+
+function pillClass(map: Record<string, string>, key: string) {
+ return (
+ map[key] ||
+ "bg-stone-100 text-stone-700 dark:bg-stone-800 dark:text-stone-300"
+ );
+}
+
+export const sessionsColumns: Columns<string, CodingAgentSessionRowView> = {
+ session: {
+ header: () => m.AGENTS_CODING_SESSIONS_SESSION,
+ cell: ({ row }) => {
+ const title =
+ row.vendor && row.session_id
+ ? `${row.vendor} session`
+ : "untitled session";
+ const shortId = row.session_id ? row.session_id.slice(0, 8) : "—";
+ return (
+ <div className="min-w-0">
+ <div className="truncate text-xs font-medium text-stone-900 dark:text-stone-100" title={row.session_id}>
+ {title}
+ </div>
+ <div
+ className="truncate font-mono text-[10px] text-stone-500 dark:text-stone-400"
+ title={row.session_id}
+ >
+ {shortId}
+ </div>
+ </div>
+ );
+ },
+ enableHiding: true,
+ },
+ user: {
+ header: () => m.AGENTS_CODING_SESSIONS_USER,
+ cell: ({ row }) => (
+ <div className="truncate" title={row.user || ""}>
+ {row.user || "—"}
+ </div>
+ ),
+ enableHiding: true,
+ },
+ started: {
+ header: () => m.AGENTS_CODING_SESSIONS_STARTED,
+ cell: ({ row }) => (
+ <div
+ className="flex items-center gap-2 truncate"
+ title={row.started_at || ""}
+ >
+ <CalendarDays size="14" />
+ <span className="truncate">{formatDate(row.started_at)}</span>
+ </div>
+ ),
+ enableHiding: true,
+ },
+ duration: {
+ header: () => m.AGENTS_CODING_SESSIONS_DURATION,
+ cell: ({ row }) => (
+ <span className="tabular-nums">{durationLabel(row.duration_ms)}</span>
+ ),
+ enableHiding: true,
+ },
+ model: {
+ header: () => "Model",
+ cell: ({ row }) => (
+ <div className="truncate font-mono text-xs" title={row.model || ""}>
+ {row.model || "—"}
+ </div>
+ ),
+ enableHiding: true,
+ },
+ tools: {
+ header: () => m.AGENTS_CODING_SESSIONS_TOOLS,
+ cell: ({ row }) => (
+ <span className="tabular-nums">
+ {(row.tool_call_count ?? 0).toLocaleString()}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ // Code-impact: shows added / removed (with rejected lines as
+ // tooltip) so a reviewer can scan the Sessions list and spot
+ // outliers without opening each session.
+ code: {
+ header: () => m.AGENTS_CODING_SESSIONS_CODE,
+ cell: ({ row }) => {
+ const added = row.lines_added ?? 0;
+ const removed = row.lines_removed ?? 0;
+ const accepted = row.lines_accepted ?? 0;
+ const rejected = row.lines_rejected ?? 0;
+ const tooltip = `+${added} added · −${removed} removed · ${accepted} accepted · ${rejected} rejected`;
+ if (!added && !removed) {
+ return <span className="text-stone-400">—</span>;
+ }
+ return (
+ <span className="text-xs tabular-nums" title={tooltip}>
+ <span className="text-emerald-600 dark:text-emerald-400">
+ +{added.toLocaleString()}
+ </span>
+ <span className="mx-1 text-stone-400">/</span>
+ <span className="text-rose-600 dark:text-rose-400">
+ −{removed.toLocaleString()}
+ </span>
+ </span>
+ );
+ },
+ enableHiding: true,
+ },
+ acceptance: {
+ header: () => m.AGENTS_CODING_SESSIONS_ACCEPTANCE,
+ cell: ({ row }) => {
+ const accepts = row.edit_accept_count ?? 0;
+ const rejects = row.edit_reject_count ?? 0;
+ const total = accepts + rejects;
+ if (!total) return <span className="text-stone-400">—</span>;
+ return (
+ <span
+ className="text-xs tabular-nums"
+ title={`${accepts} accepted · ${rejects} rejected of ${total} decisions`}
+ >
+ {Math.round(row.acceptance_pct ?? 0)}%
+ </span>
+ );
+ },
+ enableHiding: true,
+ },
+ commits: {
+ header: () => m.AGENTS_CODING_SESSIONS_COMMITS,
+ cell: ({ row }) => (
+ <span className="tabular-nums">
+ {(row.commit_count ?? 0).toLocaleString()}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ prs: {
+ header: () => m.AGENTS_CODING_SESSIONS_PRS,
+ cell: ({ row }) => (
+ <span className="tabular-nums">
+ {(row.pr_count ?? 0).toLocaleString()}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ tokens: {
+ header: () => "Tokens",
+ cell: ({ row }) => {
+ const total =
+ Number(row.total_tokens || 0) ||
+ Number(row.input_tokens || 0) + Number(row.output_tokens || 0);
+ return (
+ <span
+ className="tabular-nums"
+ title={`in ${row.input_tokens ?? 0} / out ${row.output_tokens ?? 0}`}
+ >
+ {total > 0 ? total.toLocaleString() : "—"}
+ </span>
+ );
+ },
+ enableHiding: true,
+ },
+ cost: {
+ header: () => m.AGENTS_CODING_SESSIONS_COST,
+ cell: ({ row }) => (
+ <span className="tabular-nums">${(row.cost_usd ?? 0).toFixed(4)}</span>
+ ),
+ enableHiding: true,
+ },
+ outcome: {
+ header: () => m.AGENTS_CODING_SESSIONS_OUTCOME,
+ cell: ({ row }) => (
+ <span
+ className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${pillClass(
+ OUTCOME_TONE,
+ row.outcome
+ )}`}
+ >
+ {row.outcome || "—"}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ classification: {
+ header: () => m.AGENTS_CODING_SESSIONS_CLASSIFICATION,
+ cell: ({ row }) => (
+ <span
+ className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${pillClass(
+ CLASSIFICATION_TONE,
+ row.classification
+ )}`}
+ title={row.classification_reason || row.classification}
+ >
+ {row.classification || "unknown"}
+ </span>
+ ),
+ enableHiding: true,
+ },
+};
+
+export const codingUsersColumns: Columns<string, CodingAgentUserRowView> = {
+ user: {
+ header: () => m.AGENTS_CODING_SESSIONS_USER,
+ cell: ({ row }) => (
+ <div className="truncate font-mono" title={row.user || ""}>
+ {row.user || "—"}
+ </div>
+ ),
+ enableHiding: true,
+ },
+ sessions: {
+ header: () => m.AGENTS_CODING_SESSIONS_SESSION,
+ cell: ({ row }) => (
+ <span className="tabular-nums">
+ {(row.session_count ?? 0).toLocaleString()}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ tools: {
+ header: () => m.AGENTS_CODING_SESSIONS_TOOLS,
+ cell: ({ row }) => (
+ <span className="tabular-nums">
+ {(row.tool_call_count ?? 0).toLocaleString()}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ cost: {
+ header: () => m.AGENTS_CODING_SESSIONS_COST,
+ cell: ({ row }) => (
+ <span className="tabular-nums">${(row.cost_usd ?? 0).toFixed(4)}</span>
+ ),
+ enableHiding: true,
+ },
+ tokens: {
+ header: () => "Tokens",
+ cell: ({ row }) => (
+ <span className="tabular-nums">
+ {(row.total_tokens ?? 0).toLocaleString()}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ lines: {
+ header: () => m.AGENTS_CODING_USERS_LINES,
+ cell: ({ row }) => {
+ const added = row.lines_added ?? 0;
+ if (!added) return <span className="text-stone-400">—</span>;
+ return (
+ <span
+ className="text-xs tabular-nums text-emerald-600 dark:text-emerald-400"
+ title={`${row.lines_accepted ?? 0} accepted · ${row.lines_rejected ?? 0} rejected`}
+ >
+ +{added.toLocaleString()}
+ </span>
+ );
+ },
+ enableHiding: true,
+ },
+ acceptance: {
+ header: () => m.AGENTS_CODING_USERS_ACCEPTANCE,
+ cell: ({ row }) => {
+ const accepts = row.acceptance_pct ?? 0;
+ if (!row.lines_accepted && !row.lines_rejected) {
+ return <span className="text-stone-400">—</span>;
+ }
+ return (
+ <span className="text-xs tabular-nums">
+ {Math.round(accepts)}%
+ </span>
+ );
+ },
+ enableHiding: true,
+ },
+ commits: {
+ header: () => m.AGENTS_CODING_USERS_COMMITS,
+ cell: ({ row }) => (
+ <span className="tabular-nums">
+ {(row.commit_count ?? 0).toLocaleString()}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ prs: {
+ header: () => m.AGENTS_CODING_USERS_PRS,
+ cell: ({ row }) => (
+ <span className="tabular-nums">
+ {(row.pr_count ?? 0).toLocaleString()}
+ </span>
+ ),
+ enableHiding: true,
+ },
+ topVendor: {
+ header: () => "Top vendor",
+ cell: ({ row }) => (
+ <div className="truncate" title={row.top_vendor || ""}>
+ {row.top_vendor || "—"}
+ </div>
+ ),
+ enableHiding: true,
+ },
+ mix: {
+ header: () => "Work / personal",
+ cell: ({ row }) => {
+ const total = Math.max(
+ 1,
+ (row.classification_work ?? 0) + (row.classification_personal ?? 0)
+ );
+ const workPct = ((row.classification_work ?? 0) / total) * 100;
+ return (
+ <div className="flex items-center gap-2 min-w-[120px]">
+ <div className="h-1.5 flex-1 overflow-hidden rounded bg-stone-100 dark:bg-stone-800">
+ <div
+ className="h-full bg-blue-500"
+ style={{ width: `${workPct}%` }}
+ />
+ </div>
+ <span className="tabular-nums text-xs text-stone-600 dark:text-stone-400">
+ {Math.round(workPct)}%
+ </span>
+ </div>
+ );
+ },
+ enableHiding: true,
+ },
+ lastSeen: {
+ header: () => m.OBSERVABILITY_LAST_SEEN,
+ cell: ({ row }) => (
+ <div
+ className="flex items-center gap-2 truncate"
+ title={row.last_seen || ""}
+ >
+ <CalendarDays size="14" />
+ <span className="truncate">{formatDate(row.last_seen)}</span>
+ </div>
+ ),
+ enableHiding: true,
+ },
+};
diff --git a/src/client/src/components/(playground)/observability/registry.tsx b/src/client/src/components/(playground)/observability/registry.tsx
index 29d53f69..ed0ebf32 100644
--- a/src/client/src/components/(playground)/observability/registry.tsx
+++ b/src/client/src/components/(playground)/observability/registry.tsx
@@ -1,22 +1,36 @@
import { Columns } from "@/components/data-table/columns";
import { columns as traceColumns } from "@/components/(playground)/request/columns";
import { columns as exceptionColumns } from "@/components/(playground)/exceptions/columns";
-import { logColumns, metricColumns } from "./columns";
+import {
+ codingUsersColumns,
+ logColumns,
+ metricColumns,
+ sessionsColumns,
+} from "./columns";
import { normalizeTrace } from "@/helpers/client/trace";
import {
Activity,
BarChart3,
+ Bot,
FileText,
ShieldAlert,
+ Users,
type LucideIcon,
} from "lucide-react";
import { CustomFilterAttributeType } from "@/types/store/filter";
import { PAGE } from "@/types/store/page";
+import type { SortOption } from "@/components/(playground)/filter/sorting";
import getMessage from "@/constants/messages";
const m = getMessage();
-export type ObservabilitySignal = "traces" | "exceptions" | "metrics" | "logs";
+export type ObservabilitySignal =
+ | "traces"
+ | "exceptions"
+ | "metrics"
+ | "logs"
+ | "sessions"
+ | "coding_users";
export type ObservabilitySignalConfig = {
key: ObservabilitySignal;
@@ -35,6 +49,12 @@ export type ObservabilitySignalConfig = {
supportGrouping?: boolean;
groupedUrl?: string;
includeOnlySorting?: string[];
+ // Aggregation-level sort options (e.g. "cost", "tokens",
+ // "sessions"). When set, the API route is responsible for
+ // translating `filter.sorting.type` into the right ClickHouse
+ // column. We use this for sessions + coding_users where the
+ // rows aren't a 1-to-1 mapping of OTel attributes.
+ customSortOptions?: SortOption[];
customAttributeTypes: CustomFilterAttributeType[];
normalize?: (row: any) => any;
getRowId: (row: any) => string;
@@ -142,6 +162,79 @@ export const OBSERVABILITY_SIGNALS: ObservabilitySignalConfig[] = [
getDetailHref: (row, from) =>
`/telemetry/logs/${row.rowId}?from=${encodeURIComponent(from)}`,
},
+ {
+ // Coding-agent sessions live alongside the other signals so a
+ // caller can drop `<ObservabilitySignalList config={getSignalConfig("sessions")} />`
+ // onto any page (e.g. the agent detail page or the per-user
+ // page) and inherit summary/list/sheet/full-screen for free.
+ key: "sessions",
+ label: m.AGENTS_CODING_SESSIONS_LABEL,
+ shortLabel: m.AGENTS_CODING_SESSIONS_SHORT_LABEL,
+ tone: "text-violet-600 dark:text-violet-400 bg-violet-50 dark:bg-violet-950/40 border-violet-200 dark:border-violet-900",
+ summary: m.AGENTS_CODING_SESSIONS_SUMMARY,
+ icon: Bot,
+ listUrl: "/api/coding-agents/sessions",
+ summaryUrl: "/api/coding-agents/sessions/summary",
+ // We reuse the trace request config endpoints for the dynamic
+ // filter UI (span attribute / resource attribute keys); the
+ // underlying server query for sessions still scopes by
+ // `coding_agent.session.id` so unrelated traces never leak in.
+ configUrl: "/api/metrics/request/config",
+ attributeKeysUrl: "/api/metrics/request/attribute-keys",
+ columns: sessionsColumns,
+ pageName: "codingAgentSessions",
+ visibilityPage: "codingAgentSessions",
+ customSortOptions: [
+ { key: "latest", label: "Latest" },
+ { key: "duration", label: "Duration" },
+ { key: "cost", label: "Cost" },
+ { key: "tokens", label: "Tokens" },
+ { key: "tool_calls", label: "Tool calls" },
+ ],
+ customAttributeTypes: ["SpanAttributes", "ResourceAttributes", "Field"],
+ getRowId: (row) => row.session_id,
+ // Detail href resolves to the trace-detail page at the
+ // session-root SpanId. Phase 2 makes this SpanId stable
+ // (deterministic from the session id), so deep-linking and
+ // reload-after-refresh both work.
+ getDetailHref: (row, from) =>
+ `/telemetry/traces/${row.session_root_span_id || row.session_id}?from=${encodeURIComponent(from)}`,
+ },
+ {
+ // Coding-agent users directory — same orchestration as
+ // `sessions` but the row click navigates to the per-user page
+ // instead of opening a sheet (the per-user page is rich enough
+ // to warrant a full route).
+ key: "coding_users",
+ label: m.AGENTS_CODING_USERS_LABEL,
+ shortLabel: m.AGENTS_CODING_USERS_SHORT_LABEL,
+ tone: "text-violet-600 dark:text-violet-400 bg-violet-50 dark:bg-violet-950/40 border-violet-200 dark:border-violet-900",
+ summary: m.AGENTS_CODING_USERS_SUMMARY,
+ icon: Users,
+ listUrl: "/api/coding-agents/users",
+ summaryUrl: "/api/coding-agents/users/summary",
+ // User directory shares the same dynamic-filter shape as the
+ // sessions page (vendor / user / classification live on
+ // otel_traces span attributes) so we can reuse the existing
+ // metrics/request config endpoints.
+ configUrl: "/api/metrics/request/config",
+ attributeKeysUrl: "/api/metrics/request/attribute-keys",
+ columns: codingUsersColumns,
+ pageName: "codingAgentSessions",
+ visibilityPage: "codingAgentSessions",
+ customSortOptions: [
+ { key: "last_seen", label: "Last seen" },
+ { key: "sessions", label: "Sessions" },
+ { key: "tool_calls", label: "Tool calls" },
+ { key: "cost", label: "Cost" },
+ { key: "tokens", label: "Tokens" },
+ { key: "work", label: "Work classified" },
+ ],
+ customAttributeTypes: ["SpanAttributes", "ResourceAttributes", "Field"],
+ getRowId: (row) => row.user || "low_cohort",
+ getDetailHref: (row, from) =>
+ `/coding-agents/users/${encodeURIComponent(row.user)}?from=${encodeURIComponent(from)}`,
+ },
];
export function getSignalConfig(signal: string | null | undefined) {
diff --git a/src/client/src/components/(playground)/observability/signal-list.tsx b/src/client/src/components/(playground)/observability/signal-list.tsx
index 7cea4668..5d73fd95 100644
--- a/src/client/src/components/(playground)/observability/signal-list.tsx
+++ b/src/client/src/components/(playground)/observability/signal-list.tsx
@@ -71,8 +71,22 @@ function ResizableDetailSheet({
export default function ObservabilitySignalList({
config,
+ runFilters,
+ toolbarExtraControls,
}: {
config: ObservabilitySignalConfig;
+ // runFilters is a per-render filter slice that callers pin onto the
+ // list/summary requests (e.g. an agent-scoped sessions tab pins
+ // `vendor`, the per-user page pins `user`). We forward them as-is
+ // inside the POST body so the route handler picks them up without
+ // the global filter store needing to know about coding-agent
+ // concepts.
+ runFilters?: Record<string, unknown>;
+ // `toolbarExtraControls` are rendered immediately to the LEFT of
+ // the filter (`SlidersHorizontal`) button. Coding-agent tabs use
+ // this to inject a per-user picker into the same toolbar without
+ // the inline filter bar above the table.
+ toolbarExtraControls?: ReactNode;
}) {
const m = getMessage();
const router = useRouter();
@@ -101,18 +115,33 @@ export default function ObservabilitySignalList({
}, [config.key]);
const effectiveFilter = useMemo(() => {
- if (filter.groupBy && filter.groupValue) {
- return {
- ...filter,
- selectedConfig: buildGroupValueFilter(
- filter.groupBy,
- filter.groupValue,
- filter.selectedConfig
- ),
- };
+ const base =
+ filter.groupBy && filter.groupValue
+ ? {
+ ...filter,
+ selectedConfig: buildGroupValueFilter(
+ filter.groupBy,
+ filter.groupValue,
+ filter.selectedConfig
+ ),
+ }
+ : filter;
+ // Pin caller-supplied filters under a stable key so route
+ // handlers (and the cache key implicitly via JSON body) pick
+ // them up. Stripping nullish entries keeps the cache key stable
+ // when a caller toggles a filter on/off.
+ if (runFilters && Object.keys(runFilters).length > 0) {
+ const cleaned = Object.fromEntries(
+ Object.entries(runFilters).filter(
+ ([, value]) => value !== undefined && value !== null && value !== ""
+ )
+ );
+ if (Object.keys(cleaned).length > 0) {
+ return { ...base, runFilters: cleaned };
+ }
}
- return filter;
- }, [filter]);
+ return base;
+ }, [filter, runFilters]);
const showFlatList =
!config.supportGrouping || !filter.groupBy || !!filter.groupValue;
@@ -159,6 +188,11 @@ export default function ObservabilitySignalList({
const isTraceSignal = config.key === "traces" || config.key === "exceptions";
const isMetricSignal = config.key === "metrics";
const isLogSignal = config.key === "logs";
+ // Coding-agent sessions render through the same TraceDetailView used
+ // for trace/exception signals — Phase 2 of the coding-agents work
+ // makes the session-root SpanId stable, so opening that SpanId in
+ // the trace detail sheet shows the full session as one trace tree.
+ const isSessionSignal = config.key === "sessions";
const setSelectedInUrl = useCallback(
(id: string | null) => {
@@ -188,12 +222,16 @@ export default function ObservabilitySignalList({
setPreviewSpanId(null);
return;
}
- if (isTraceSignal && !previewSpanId && !skipSelectedHydrationRef.current) {
+ if (
+ (isTraceSignal || isSessionSignal) &&
+ !previewSpanId &&
+ !skipSelectedHydrationRef.current
+ ) {
setPreviewSpanId(selectedParam);
return;
}
- if (!isTraceSignal) setPreviewSpanId(null);
- }, [isTraceSignal, previewSpanId, selectedParam]);
+ if (!isTraceSignal && !isSessionSignal) setPreviewSpanId(null);
+ }, [isTraceSignal, isSessionSignal, previewSpanId, selectedParam]);
const selectedMetricRow = useMemo(() => {
if (!isMetricSignal || !selectedParam) return null;
@@ -217,6 +255,22 @@ export default function ObservabilitySignalList({
setSelectedInUrl(row.spanId);
return;
}
+ if (isSessionSignal) {
+ // TraceDetailView opens on a SpanId. Prefer the explicit
+ // session-root SpanId (post-Phase-2 the CLI derives this
+ // deterministically from the session id); fall back to the
+ // chronologically-first child span; final fallback is the
+ // session id itself, which the trace detail page handles
+ // gracefully by surfacing an empty trace state.
+ const safe = row && typeof row === "object" ? row : {};
+ const targetSpanId =
+ safe.session_root_span_id || safe.session_id || safe.trace_id || "";
+ if (!targetSpanId) return;
+ skipSelectedHydrationRef.current = false;
+ setPreviewSpanId(targetSpanId);
+ setSelectedInUrl(targetSpanId);
+ return;
+ }
if (isMetricSignal) {
setSelectedInUrl(config.getRowId(row));
return;
@@ -272,9 +326,20 @@ export default function ObservabilitySignalList({
const updateActiveTraceSelection = useCallback(
(spanId: string) => {
+ // Drilling into a child span inside an open SESSION must not
+ // rewrite the URL. A coding-agent session is one logical unit:
+ // `?selected=` stays pinned to the session-root SpanId so (a)
+ // the session row keeps its highlight and (b) the list subtree
+ // doesn't re-render on every span click — that re-render was the
+ // row "flicker". The active inner span is tracked entirely by
+ // TraceDetailView's own `selectedSpanId` state, which is all the
+ // detail panel + AI analysis tab consume; the URL only needs the
+ // session-level entry point. Trace/exception signals keep writing
+ // the active span so per-span deep-links there still work.
+ if (isSessionSignal) return;
setSelectedInUrl(spanId);
},
- [setSelectedInUrl]
+ [isSessionSignal, setSelectedInUrl]
);
const updateTraceNavigationPage = useCallback(
@@ -298,6 +363,7 @@ export default function ObservabilitySignalList({
total={showFlatList ? total : undefined}
supportDynamicFilters
includeOnlySorting={config.includeOnlySorting}
+ customSortOptions={config.customSortOptions}
pageName={config.pageName}
columns={config.columns}
configUrl={config.configUrl}
@@ -306,6 +372,7 @@ export default function ObservabilitySignalList({
filterStorageScope={config.key}
showGroupBy={!!config.supportGrouping}
showVisibilityColumns
+ extraControls={toolbarExtraControls}
/>
{config.supportGrouping && filter.groupBy && (
@@ -332,13 +399,23 @@ export default function ObservabilitySignalList({
isFetched={isFetched || pingStatus !== "pending"}
isLoading={isLoading || pingStatus === "pending"}
onOpen={openDetail}
- selectedId={selectedParam}
+ // For sessions, the row highlight tracks the OPEN session
+ // (its root span id, held in `previewSpanId`), not the
+ // live `?selected=` value. Drilling into a child span
+ // (chat message, llm.turn, tool.call) rewrites `?selected=`
+ // to that child's id, which would otherwise drop the
+ // session row's highlight on every click — the flicker the
+ // row exhibited. Trace/exception signals keep matching the
+ // live selection.
+ selectedId={
+ isSessionSignal ? previewSpanId || selectedParam : selectedParam
+ }
/>
</div>
)}
<Sheet
modal={false}
- open={isTraceSignal && !!previewSpanId}
+ open={(isTraceSignal || isSessionSignal) && !!previewSpanId}
onOpenChange={(open) => !open && closePreview()}
>
<SheetContent
diff --git a/src/client/src/components/(playground)/observability/signal-records.tsx b/src/client/src/components/(playground)/observability/signal-records.tsx
index 0168f56c..12d77c0c 100644
--- a/src/client/src/components/(playground)/observability/signal-records.tsx
+++ b/src/client/src/components/(playground)/observability/signal-records.tsx
@@ -3,12 +3,21 @@
import { format } from "date-fns";
import {
BarChart3,
+ Bot,
Clock,
+ DollarSign,
+ Folder,
+ GitBranch,
Hash,
Info,
+ Wrench,
Zap,
} from "lucide-react";
import { ObservabilitySignalConfig } from "./registry";
+import {
+ CodingAgentVendorIcon,
+ hasCodingAgentVendorIcon,
+} from "@/components/svg/coding-agents";
import getMessage from "@/constants/messages";
const m = getMessage();
@@ -333,6 +342,336 @@ function MetricRecord({
);
}
+function durationLabel(ms: number) {
+ if (!Number.isFinite(ms) || ms <= 0) return "—";
+ if (ms < 1000) return `${Math.round(ms)}ms`;
+ const sec = ms / 1000;
+ if (sec < 60) return `${sec.toFixed(1)}s`;
+ const min = sec / 60;
+ if (min < 60) return `${min.toFixed(1)}m`;
+ return `${(min / 60).toFixed(1)}h`;
+}
+
+const SESSION_OUTCOME_TONE: Record<string, string> = {
+ merged:
+ "bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",
+ committed:
+ "bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",
+ abandoned_with_change:
+ "bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300",
+};
+
+const SESSION_CLASS_TONE: Record<string, string> = {
+ work: "bg-blue-100 text-blue-700 dark:bg-blue-950 dark:text-blue-300",
+ personal:
+ "bg-orange-100 text-orange-700 dark:bg-orange-950 dark:text-orange-300",
+ disputed: "bg-rose-100 text-rose-700 dark:bg-rose-950 dark:text-rose-300",
+};
+
+function tone(map: Record<string, string>, key: string) {
+ return (
+ map[key] ||
+ "bg-stone-100 text-stone-700 dark:bg-stone-800 dark:text-stone-300"
+ );
+}
+
+function CodingUserRecord({
+ row,
+ visibilityColumns,
+ isSelected,
+ onOpen,
+}: {
+ row: any;
+ visibilityColumns: Record<string, boolean>;
+ isSelected?: boolean;
+ onOpen: (row: any) => void;
+}) {
+ const show = (key: string) => visibilityColumns[key] !== false;
+ const masked = row.user === "low_cohort";
+ const total = Math.max(
+ 1,
+ Number(row.classification_work || 0) +
+ Number(row.classification_personal || 0)
+ );
+ const workPct = (Number(row.classification_work || 0) / total) * 100;
+ return (
+ <button
+ type="button"
+ onClick={() => !masked && onOpen(row)}
+ disabled={masked}
+ className={`group w-full rounded-md border p-3 text-left transition ${
+ isSelected
+ ? "border-violet-500 bg-violet-50 shadow-sm ring-1 ring-violet-200 dark:border-violet-500 dark:bg-violet-950/30 dark:ring-violet-900"
+ : masked
+ ? "border-stone-200 bg-stone-50 cursor-not-allowed dark:border-stone-800 dark:bg-stone-900/40"
+ : "border-stone-200 bg-white hover:border-violet-400 hover:bg-violet-50/60 dark:border-stone-800 dark:bg-stone-950 dark:hover:border-violet-700 dark:hover:bg-violet-950/20"
+ }`}
+ >
+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ {/* Use the vendor's logo as the row leading icon when
+ we know it; falls back to the generic Bot icon
+ for an unknown vendor. We drop the separate
+ vendor pill below to avoid duplicating the
+ information. */}
+ {hasCodingAgentVendorIcon(row.top_vendor) ? (
+ <CodingAgentVendorIcon
+ vendor={row.top_vendor}
+ className="h-4 w-4 shrink-0"
+ />
+ ) : (
+ <Bot className="h-4 w-4 shrink-0 text-violet-500" />
+ )}
+ <h3 className="truncate font-mono text-sm font-semibold text-stone-950 dark:text-stone-50">
+ {masked ? "low cohort (privacy floor)" : row.user || "—"}
+ </h3>
+ </div>
+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-stone-500 dark:text-stone-400">
+ {show("lastSeen") && <span>Last {formatDate(row.last_seen)}</span>}
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-1.5 sm:flex sm:flex-wrap sm:justify-end">
+ {show("sessions") && (
+ <MiniMeta
+ icon={<Bot className="h-3.5 w-3.5" />}
+ label="sessions"
+ value={Number(row.session_count || 0).toLocaleString()}
+ />
+ )}
+ {show("tools") && (
+ <MiniMeta
+ icon={<Wrench className="h-3.5 w-3.5" />}
+ label="tools"
+ value={Number(row.tool_call_count || 0).toLocaleString()}
+ />
+ )}
+ {show("cost") && (
+ <MiniMeta
+ icon={<DollarSign className="h-3.5 w-3.5" />}
+ label="cost"
+ value={`$${Number(row.cost_usd || 0).toFixed(4)}`}
+ />
+ )}
+ {show("tokens") && (
+ <MiniMeta
+ icon={<Hash className="h-3.5 w-3.5" />}
+ label="tokens"
+ value={compactNumber(Number(row.total_tokens || 0))}
+ />
+ )}
+ {show("mix") && (
+ <MiniMeta
+ icon={<Bot className="h-3.5 w-3.5" />}
+ label="work%"
+ value={`${Math.round(workPct)}%`}
+ />
+ )}
+ </div>
+ </div>
+ </button>
+ );
+}
+
+function SessionRecord({
+ row,
+ visibilityColumns,
+ isSelected,
+ onOpen,
+}: {
+ row: any;
+ visibilityColumns: Record<string, boolean>;
+ isSelected?: boolean;
+ onOpen: (row: any) => void;
+}) {
+ const show = (key: string) => visibilityColumns[key] !== false;
+ const sessionId = row.session_id || "";
+ // Cursor session ids are long UUIDs — show enough characters to disambiguate
+ // at a glance but keep the row visually compact.
+ const shortSessionId = sessionId
+ ? sessionId.length > 12
+ ? `${sessionId.slice(0, 12)}…`
+ : sessionId
+ : "—";
+ const vendor = (row.vendor || "").toLowerCase();
+ const totalTokens = Number(
+ row.total_tokens ||
+ Number(row.input_tokens || 0) + Number(row.output_tokens || 0)
+ );
+ // Repo / branch / working folder — surfaced as a thin metadata
+ // strip below the identity row so a developer can pick a session
+ // by repo without opening it. We trim noisy URL prefixes/suffixes
+ // to keep the chip compact (e.g. "openlit/openlit @ main") and
+ // fall back to the working-folder label when there's no VCS
+ // remote (e.g. a fresh clone or a non-git workspace).
+ const repoUrl = (row.repo_url || "").trim();
+ const repoLabel = repoUrl
+ ? repoUrl.replace(/^https?:\/\//, "").replace(/\.git$/, "")
+ : "";
+ const branchName = (row.branch || "").trim();
+ const folderLabel = (row.working_dir_label || "").trim();
+ return (
+ <button
+ type="button"
+ onClick={() => onOpen(row)}
+ className={`group w-full rounded-md border p-3 text-left transition ${
+ isSelected
+ ? "border-violet-500 bg-violet-50 shadow-sm ring-1 ring-violet-200 dark:border-violet-500 dark:bg-violet-950/30 dark:ring-violet-900"
+ : "border-stone-200 bg-white hover:border-violet-400 hover:bg-violet-50/60 dark:border-stone-800 dark:bg-stone-950 dark:hover:border-violet-700 dark:hover:bg-violet-950/20"
+ }`}
+ >
+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-start gap-2">
+ {hasCodingAgentVendorIcon(vendor) ? (
+ <CodingAgentVendorIcon
+ vendor={vendor}
+ className="mt-0.5 h-4 w-4 shrink-0"
+ />
+ ) : (
+ <Bot className="mt-0.5 h-4 w-4 shrink-0 text-violet-500" />
+ )}
+ <div className="min-w-0">
+ <h3
+ className="truncate font-mono text-sm font-semibold text-stone-950 dark:text-stone-50"
+ title={sessionId}
+ >
+ {shortSessionId}
+ </h3>
+ <div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs">
+ {/* Vendor pill removed — the vendor icon
+ already sits to the left of the session id
+ so showing "cursor" here is redundant. */}
+ {show("user") && row.user && (
+ <span className="truncate text-xs text-stone-500 dark:text-stone-400">
+ {row.user}
+ </span>
+ )}
+ {row.model && (
+ <span
+ className="truncate rounded bg-stone-100 px-1.5 py-0.5 text-[11px] text-stone-600 dark:bg-stone-900 dark:text-stone-300"
+ title={row.model}
+ >
+ {row.model}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-stone-500 dark:text-stone-400">
+ {show("started") && <span>{formatDate(row.started_at)}</span>}
+ {/* Outcome and classification often arrive as the literal
+ string "unknown" — Cursor's sessionEnd payload omits
+ `reason`, and the CLI classifier returns "unknown"
+ when no signal is decisive. Showing those as pills
+ just clutters the row with two grey "unknown" chips
+ per session. We render them only when they carry a
+ real value; "running" stands in for "session is
+ still open" so users still see SOMETHING when no
+ end-of-session telemetry has landed yet. */}
+ {show("outcome") &&
+ row.outcome &&
+ row.outcome !== "unknown" && (
+ <span
+ className={`rounded px-1.5 py-0.5 text-[11px] font-medium ${tone(
+ SESSION_OUTCOME_TONE,
+ row.outcome
+ )}`}
+ >
+ {row.outcome}
+ </span>
+ )}
+ {show("outcome") && (!row.outcome || row.outcome === "unknown") && (
+ <span className="rounded px-1.5 py-0.5 text-[11px] font-medium bg-sky-100 text-sky-700 dark:bg-sky-950 dark:text-sky-300">
+ running
+ </span>
+ )}
+ {show("classification") &&
+ row.classification &&
+ row.classification !== "unknown" && (
+ <span
+ className={`rounded px-1.5 py-0.5 text-[11px] font-medium ${tone(
+ SESSION_CLASS_TONE,
+ row.classification
+ )}`}
+ title={row.classification_reason || row.classification}
+ >
+ {row.classification}
+ </span>
+ )}
+ {row.permission_mode && (
+ <span
+ className="rounded bg-stone-100 px-1.5 py-0.5 text-[11px] text-stone-600 dark:bg-stone-900 dark:text-stone-300"
+ title={`Last seen mode: ${row.permission_mode}`}
+ >
+ {row.permission_mode}
+ </span>
+ )}
+ {repoLabel && (
+ <span
+ className="inline-flex items-center gap-1 rounded bg-stone-100 px-1.5 py-0.5 text-[11px] text-stone-600 dark:bg-stone-900 dark:text-stone-300"
+ title={`${repoUrl}${branchName ? ` @ ${branchName}` : ""}`}
+ >
+ <GitBranch className="h-3 w-3 shrink-0" />
+ {repoLabel}
+ {branchName && (
+ <span className="text-stone-400">@{branchName}</span>
+ )}
+ </span>
+ )}
+ {folderLabel && (
+ <span
+ className="inline-flex items-center gap-1 rounded bg-stone-100 px-1.5 py-0.5 text-[11px] text-stone-600 dark:bg-stone-900 dark:text-stone-300"
+ title={row.working_dir || folderLabel}
+ >
+ <Folder className="h-3 w-3 shrink-0" />
+ {folderLabel}
+ </span>
+ )}
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-1.5 sm:flex sm:flex-wrap sm:justify-end">
+ {show("duration") && (
+ <MiniMeta
+ icon={<Clock className="h-3.5 w-3.5" />}
+ label="duration"
+ value={durationLabel(Number(row.duration_ms || 0))}
+ />
+ )}
+ {show("tools") && (
+ <MiniMeta
+ icon={<Wrench className="h-3.5 w-3.5" />}
+ label="tools"
+ value={Number(row.tool_call_count || 0).toLocaleString()}
+ />
+ )}
+ {show("tokens") && totalTokens > 0 && (
+ <MiniMeta
+ icon={<Hash className="h-3.5 w-3.5" />}
+ label="tokens"
+ value={compactNumber(totalTokens)}
+ />
+ )}
+ {show("cost") && (
+ <MiniMeta
+ icon={<DollarSign className="h-3.5 w-3.5" />}
+ label="cost"
+ value={`$${Number(row.cost_usd || 0).toFixed(4)}`}
+ />
+ )}
+ </div>
+ </div>
+ </button>
+ );
+}
+
+function compactNumber(value: number): string {
+ if (!Number.isFinite(value)) return "0";
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}m`;
+ if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`;
+ return value.toLocaleString();
+}
+
export default function SignalRecords({
config,
rows,
@@ -387,6 +726,43 @@ export default function SignalRecords({
);
}
+ if (config.key === "sessions") {
+ return (
+ <div className="grid gap-2">
+ {rows.map((row) => (
+ <SessionRecord
+ key={config.getRowId(row)}
+ row={row}
+ visibilityColumns={visibilityColumns}
+ // For sessions, `selectedId` is the OPEN session's root
+ // SpanId (the parent passes `previewSpanId`, not the live
+ // `?selected=` value). It stays put while the developer
+ // drills into child spans inside the sheet, so the row
+ // highlight no longer flickers off on each span click.
+ isSelected={selectedId === row.session_root_span_id}
+ onOpen={onOpen}
+ />
+ ))}
+ </div>
+ );
+ }
+
+ if (config.key === "coding_users") {
+ return (
+ <div className="grid gap-2">
+ {rows.map((row) => (
+ <CodingUserRecord
+ key={config.getRowId(row)}
+ row={row}
+ visibilityColumns={visibilityColumns}
+ isSelected={selectedId === config.getRowId(row)}
+ onOpen={onOpen}
+ />
+ ))}
+ </div>
+ );
+ }
+
return (
<div className="grid gap-2">
{rows.map((row) =>
diff --git a/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx b/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx
index c3770000..02da9ede 100644
--- a/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx
+++ b/src/client/src/components/(playground)/observability/span-hierarchy-explorer.tsx
@@ -70,6 +70,17 @@ function SelectionBridge({
return null;
}
+function isCodingAgentTree(span?: TraceHeirarchySpan): boolean {
+ if (!span) return false;
+ if (span.SpanName?.startsWith("coding_agent.")) return true;
+ if (Array.isArray(span.children)) {
+ for (const child of span.children) {
+ if (isCodingAgentTree(child)) return true;
+ }
+ }
+ return false;
+}
+
function SpanHierarchyExplorerInner({
hierarchySpanId,
selectedSpanId,
@@ -84,6 +95,10 @@ function SpanHierarchyExplorerInner({
const m = getMessage();
const [, updateRequest] = useRequest();
const [viewMode, setViewMode] = useState<ViewMode>("tree");
+ // User-driven view-mode changes win over the auto-default. We track
+ // whether the user has explicitly picked a view so we don't keep
+ // snapping back to "chat" every time the trace data refreshes.
+ const userPickedViewRef = useRef(false);
const { data, fireRequest, isLoading } = useFetchWrapper();
useEffect(() => {
@@ -104,6 +119,16 @@ function SpanHierarchyExplorerInner({
[record]
);
const spanCount = useMemo(() => countSpans(record), [record]);
+ const isCodingAgent = useMemo(() => isCodingAgentTree(record), [record]);
+
+ // Coding-agent traces default to the Chat view because that's the
+ // surface that renders the conversational signal (prompts, thinking,
+ // tools, edits, subagents). Plain LLM traces stay on the Tree view.
+ useEffect(() => {
+ if (isCodingAgent && !userPickedViewRef.current) {
+ setViewMode("chat");
+ }
+ }, [isCodingAgent]);
return (
<section
@@ -122,7 +147,10 @@ function SpanHierarchyExplorerInner({
{VIEW_MODES.map((mode) => (
<button
key={mode.key}
- onClick={() => setViewMode(mode.key)}
+ onClick={() => {
+ userPickedViewRef.current = true;
+ setViewMode(mode.key);
+ }}
className={`inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium transition-colors ${
viewMode === mode.key
? "bg-primary text-white"
diff --git a/src/client/src/components/(playground)/observability/trace-detail-page.tsx b/src/client/src/components/(playground)/observability/trace-detail-page.tsx
index 13cb378b..fbaaa672 100644
--- a/src/client/src/components/(playground)/observability/trace-detail-page.tsx
+++ b/src/client/src/components/(playground)/observability/trace-detail-page.tsx
@@ -5,11 +5,15 @@ import type { ReactNode } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import DetailShell from "./detail-shell";
-import { getExtraTabsContentTypes, normalizeTrace } from "@/helpers/client/trace";
+import {
+ getExtraTabsContentTypes,
+ normalizeTrace,
+ isSyntheticSpanId,
+} from "@/helpers/client/trace";
import { getTimeLimitObject } from "@/store/filter";
import { FilterConfig, FilterType, TIME_RANGES } from "@/types/store/filter";
import { useCustomBreadcrumbs } from "@/utils/hooks/useBreadcrumbs";
-import { AlertTriangle, ArrowLeft, ChevronLeft, ChevronRight, Clock, Cpu, DollarSign, RefreshCw, Zap } from "lucide-react";
+import { AlertTriangle, ArrowLeft, ChevronLeft, ChevronRight, Clock, Copy, Cpu, DollarSign, Info, RefreshCw, Zap } from "lucide-react";
import SpanHierarchyExplorer from "./span-hierarchy-explorer";
import { Button } from "@/components/ui/button";
import getMessage from "@/constants/messages";
@@ -23,8 +27,65 @@ import {
ResizablePanelGroup,
} from "@/components/ui/resizable";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ CodingAgentVendorIcon,
+ hasCodingAgentVendorIcon,
+} from "@/components/svg/coding-agents";
import { toast } from "sonner";
+// Mirror of `durationLabel` in observability/columns.tsx — kept local
+// so the top-card override for coding-agent sessions can format the
+// session-level wall-clock duration the same way the Sessions list
+// row does ("1.2m", "12.3s", "450ms"). Returns "" for non-positive
+// inputs so the caller can fall back to the span-local duration.
+function formatSessionDurationMs(ms: number): string {
+ if (!Number.isFinite(ms) || ms <= 0) return "";
+ if (ms < 1000) return `${ms.toFixed(0)}ms`;
+ const sec = ms / 1000;
+ if (sec < 60) return `${sec.toFixed(1)}s`;
+ const min = sec / 60;
+ if (min < 60) return `${min.toFixed(1)}m`;
+ return `${(min / 60).toFixed(1)}h`;
+}
+
+// Compact inline notice when a coding-agent span was recorded with a
+// non-`full` content-capture mode (CLI flag OPENLIT_CODING_CONTENT_CAPTURE).
+// We surface the one command that flips it on; everything else (modes,
+// scope, scrubbing guarantees) lives in the docs to keep this terse.
+function ContentCaptureNote() {
+ const m = getMessage();
+ const command = m.CODING_AGENT_CONTENT_CAPTURE_NOTE_COMMAND;
+ const onCopy = useCallback(async () => {
+ try {
+ await navigator.clipboard.writeText(command);
+ toast.success("Copied to clipboard");
+ } catch {
+ // Clipboard API is gated behind a secure context. Fail
+ // silently rather than throwing — the command text is
+ // still selectable, and a noisy toast on every
+ // HTTP-served dev instance would be worse than a no-op.
+ }
+ }, [command]);
+ return (
+ <div className="flex flex-wrap items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-2 py-1 text-[11px] text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/40 dark:text-amber-200">
+ <Info className="h-3 w-3 shrink-0" />
+ <span className="font-medium">{m.CODING_AGENT_CONTENT_CAPTURE_NOTE_TITLE}</span>
+ <code className="rounded bg-amber-100 px-1 py-0.5 font-mono text-[10px] text-amber-900 dark:bg-amber-900/40 dark:text-amber-100">
+ {command}
+ </code>
+ <button
+ type="button"
+ onClick={onCopy}
+ className="inline-flex items-center gap-1 rounded border border-amber-300 px-1 py-0.5 text-[10px] hover:bg-amber-100 dark:border-amber-800 dark:hover:bg-amber-900/40"
+ aria-label="Copy command"
+ >
+ <Copy className="h-2.5 w-2.5" />
+ Copy
+ </button>
+ </div>
+ );
+}
+
function Stat({ icon, label, value }: { icon: ReactNode; label: string; value?: string }) {
return (
<div className="rounded-md bg-stone-100 px-2.5 py-1.5 dark:bg-stone-900">
@@ -121,15 +182,27 @@ function CostStat({
);
}
-function MetaPill({ label, value }: { label: string; value?: string }) {
+function MetaPill({
+ label,
+ value,
+ icon,
+}: {
+ label: string;
+ value?: string;
+ icon?: ReactNode;
+}) {
if (!value) return null;
return (
<div className="min-w-0 rounded-md border border-stone-200 bg-white px-2 py-1 dark:border-stone-800 dark:bg-stone-950">
<div className="text-[10px] uppercase tracking-wide text-stone-500 dark:text-stone-400">
{label}
</div>
- <div className="max-w-72 truncate font-mono text-[11px] font-medium text-stone-900 dark:text-stone-100" title={value}>
- {value}
+ <div
+ className="flex max-w-72 items-center gap-1.5 truncate font-mono text-[11px] font-medium text-stone-900 dark:text-stone-100"
+ title={value}
+ >
+ {icon ? <span className="shrink-0">{icon}</span> : null}
+ <span className="truncate">{value}</span>
</div>
</div>
);
@@ -240,6 +313,44 @@ export function TraceDetailView({
const from = searchParams.get("from");
const [selectedSpanId, setSelectedSpanId] = useState(spanId);
const [activeListSpanId, setActiveListSpanId] = useState(spanId);
+ // Per-session code-impact rollups (lines added / removed,
+ // commits, edit accept/reject, PRs, acceptance %) fetched by
+ // session_id from the trace's coding-agent attributes. Used to
+ // keep the trace-detail header pills populated even when the
+ // operator clicks into a child span (llm.turn / edit.decision /
+ // tool.call) — those don't carry the rollup attrs directly.
+ // Shape mirrors `CodingSessionDigest` from the queries module.
+ const [sessionDigest, setSessionDigest] = useState<{
+ lines_added: number;
+ lines_removed: number;
+ lines_accepted: number;
+ lines_rejected: number;
+ edit_accept_count: number;
+ edit_reject_count: number;
+ commit_count: number;
+ pr_count: number;
+ acceptance_pct: number;
+ // Session-level usage rollups (see CodingSessionDigest in
+ // `lib/platform/coding-agents/queries.ts`). These power the
+ // top-card overrides below so a still-running coding-agent
+ // session doesn't render Tokens / Cost / Duration / Model as
+ // empty just because the user is looking at a child span.
+ total_tokens: number;
+ input_tokens: number;
+ output_tokens: number;
+ cost_usd: number;
+ duration_ms: number;
+ model: string;
+ // Latest VCS / workspace context across the session (see
+ // CodingSessionDigest). The header pills prefer these over the
+ // selected span's own attributes so a mid-session branch / repo /
+ // folder switch is reflected regardless of which (often the
+ // chronologically-first) span the detail view opened on.
+ repo_url: string;
+ branch: string;
+ working_dir: string;
+ working_dir_label: string;
+ } | null>(null);
const hierarchySpanIdRef = useRef(spanId);
const [listOffset, setListOffset] = useState(() => filterFromSource(from).offset);
const [navigationPageOverride, setNavigationPageOverride] = useState<{
@@ -297,6 +408,13 @@ export function TraceDetailView({
const selectSpanInCurrentTrace = useCallback(
(nextSpanId: string) => {
+ // The synthetic session-root node has no backing row in
+ // `otel_traces`. Selecting it would fire a span-detail fetch
+ // and an AI-analysis fetch that both 404 ("Span not found"
+ // toast) and blank the detail panel. It's a visual grouping
+ // node only — ignore clicks so the panel stays on the last
+ // real span the developer was viewing.
+ if (isSyntheticSpanId(nextSpanId)) return;
setSelectedSpanId(nextSpanId);
onActiveSpanChange?.(nextSpanId);
},
@@ -348,6 +466,7 @@ export function TraceDetailView({
const raw = (data as any)?.record;
const trace = raw ? normalizeTrace(raw) : null;
const resourceAttributes = raw?.ResourceAttributes || {};
+ const spanAttributes = raw?.SpanAttributes || {};
const serviceNamespace = resourceAttributes["service.namespace"];
const deploymentEnvironment =
resourceAttributes["deployment.environment"] ||
@@ -357,6 +476,166 @@ export function TraceDetailView({
raw?.StatusMessage || raw?.StatusCode
? [raw?.StatusCode, raw?.StatusMessage].filter(Boolean).join(" / ")
: undefined;
+ // Coding-agent extras: repo URL/branch, vendor, classification — surfaced
+ // as MetaPills below the header so the session detail keeps the same
+ // signal users had on the dedicated session sheet.
+ //
+ // All of these fields live ONLY on the session-root span when the
+ // CLI emits them (working folder, repo, branch, mode, outcome,
+ // classification). When a developer clicks on a child span — an
+ // llm.turn or a tool.call — the SpanAttributes don't carry them.
+ // We fall through to ResourceAttributes (which the CLI also stamps
+ // per process so every span in the same process invocation has
+ // them) so the header pills stay populated regardless of which
+ // span the developer drills into.
+ const ca = (k: string) =>
+ (spanAttributes[k] as string) || (resourceAttributes[k] as string) || "";
+ const codingAgentVendor = (ca("coding_agent.client") ||
+ ca("gen_ai.agent.name") ||
+ "") as string;
+ // Prefer the session digest's LATEST repo / branch / folder (resolved
+ // across every span by Timestamp) over the currently-selected span's
+ // own attributes. The detail view opens on the session-root span,
+ // which is the chronologically-FIRST span and therefore carries the
+ // session-start VCS snapshot — so without this a mid-session branch
+ // switch would keep showing the old branch. `sessionDigest` is only
+ // populated for coding-agent sessions, so this is a no-op elsewhere.
+ const repoUrl = sessionDigest?.repo_url || ca("vcs.repository.url.full");
+ const repoLabel = repoUrl
+ ? repoUrl.replace(/^https?:\/\//, "").replace(/\.git$/, "")
+ : "";
+ const branchName = sessionDigest?.branch || ca("vcs.ref.head.name");
+ const codingAgentUser = (spanAttributes["gen_ai.user.name"] ||
+ resourceAttributes["gen_ai.user.name"] ||
+ "") as string;
+ const rawOutcome = ca("coding_agent.session.outcome");
+ // "unknown" is what the CLI stamps when a session ends without a
+ // definitive reason (e.g. the user closed the editor before
+ // sessionEnd fired). It carries no information for the operator,
+ // so render an empty pill rather than a confusing "unknown" chip.
+ const sessionOutcome = rawOutcome && rawOutcome !== "unknown" ? rawOutcome : "";
+ const rawClassification = ca("coding_agent.user.classification");
+ const userClassification =
+ rawClassification && rawClassification !== "unknown" ? rawClassification : "";
+ // Working folder ("cwd") — the host process directory where the
+ // agent was invoked. Useful when a developer has multiple repos
+ // open at once and the repo URL alone doesn't disambiguate.
+ const workingDir = sessionDigest?.working_dir || ca("code.cwd");
+ const workingDirLabel =
+ sessionDigest?.working_dir_label ||
+ (workingDir
+ ? workingDir.split("/").filter(Boolean).slice(-2).join("/") || workingDir
+ : "");
+ // Permission mode (Cursor's composer_mode / Claude Code's permission mode).
+ // We surface the LATEST recorded value so the chat view header
+ // reflects what the agent is currently set to even if the user
+ // flipped modes mid-session.
+ const permissionMode = ca("coding_agent.policy.permission_mode");
+ const terminalType = (resourceAttributes["terminal.type"] || "") as string;
+ // Per-session code-impact rollups. The CLI stamps these on the
+ // session-root span at SessionEnd, so they're only populated on
+ // the root span itself; clicking a child span (llm.turn,
+ // edit.decision, tool.call) would leave the pills empty. We
+ // fold them up to every child span via a tiny digest endpoint
+ // keyed by `coding_agent.session.id`, falling back to the
+ // span-level attribute when the digest hasn't arrived yet (or
+ // can't be fetched). The digest itself reuses the same
+ // greatest(rollup-attr, per-edit-sum) dual-source pattern as
+ // SESSION_BASE_COLUMNS, so the numbers are guaranteed to match
+ // what the Sessions list and the per-session detail view show.
+ const isCodingAgentTrace = !!codingAgentVendor;
+ const codingSessionId = ca("coding_agent.session.id");
+
+ // Fold per-session code-impact rollups up to whichever span the
+ // operator is viewing. The session-root attributes (`session.lines.added`
+ // etc.) only land on SessionEnd; child spans (turns, edits, tool
+ // calls) don't carry them. The digest endpoint runs the same
+ // dual-source greatest() logic the Sessions list does so the
+ // totals can never disagree across surfaces. Best-effort: a
+ // failed lookup just leaves the pills auto-hidden via the
+ // empty-value guard below.
+ useEffect(() => {
+ if (!isCodingAgentTrace || !codingSessionId) {
+ setSessionDigest(null);
+ return;
+ }
+ let cancelled = false;
+ (async () => {
+ try {
+ const res = await fetch(
+ `/api/coding-agents/sessions/${encodeURIComponent(codingSessionId)}/digest`,
+ );
+ if (!res.ok) return;
+ const body = (await res.json()) as { data?: typeof sessionDigest };
+ if (!cancelled && body?.data) setSessionDigest(body.data);
+ } catch {
+ // Best-effort — pills fall back to the span-level
+ // attributes (which are populated on the session-root span).
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [isCodingAgentTrace, codingSessionId]);
+
+ const linesAdded = ca("coding_agent.session.lines.added");
+ const linesRemoved = ca("coding_agent.session.lines.removed");
+ const linesAddedNum =
+ Number(linesAdded || 0) ||
+ Number(sessionDigest?.lines_added || 0);
+ const linesRemovedNum =
+ Number(linesRemoved || 0) ||
+ Number(sessionDigest?.lines_removed || 0);
+ // Split add/remove counts into their own pills so the header is
+ // scannable at a glance ("+128 added" / "-42 removed") rather
+ // than a packed slash-separated combo. We keep each pill empty
+ // when its underlying count is missing or zero so the row
+ // doesn't render a noisy `+0` / `-0` for sessions that didn't
+ // touch any code yet.
+ const linesAddedValue = linesAddedNum > 0
+ ? `+${linesAddedNum.toLocaleString()}`
+ : "";
+ const linesRemovedValue = linesRemovedNum > 0
+ ? `-${linesRemovedNum.toLocaleString()}`
+ : "";
+ const editAccepts =
+ Number(ca("coding_agent.session.edit.accept_count") || 0) ||
+ Number(sessionDigest?.edit_accept_count || 0);
+ const editRejects =
+ Number(ca("coding_agent.session.edit.reject_count") || 0) ||
+ Number(sessionDigest?.edit_reject_count || 0);
+ const editTotal = editAccepts + editRejects;
+ const acceptanceValue = editTotal > 0
+ ? `${Math.round((editAccepts * 100) / editTotal)}%`
+ : "";
+ const commitCountNum =
+ Number(ca("coding_agent.session.commit_count") || 0) ||
+ Number(sessionDigest?.commit_count || 0);
+ const commitCountValue = commitCountNum > 0
+ ? commitCountNum.toLocaleString()
+ : "";
+ const prCountNum =
+ Number(ca("coding_agent.session.pr_count") || 0) ||
+ Number(sessionDigest?.pr_count || 0);
+ const prCountValue = prCountNum > 0 ? prCountNum.toLocaleString() : "";
+
+ // Content-capture banner gating.
+ //
+ // We show the "content capture is off" hint only when the span's
+ // own `coding_agent.content_capture_mode` resource attribute (which
+ // the CLI stamps from cfg.CodingContentCapture on every span) is
+ // explicitly something other than "full". That's the authoritative
+ // signal — much more reliable than the previous heuristic of
+ // "no content-bearing attribute is populated", which produced
+ // false positives on spans where the vendor legitimately emits
+ // empty bodies (e.g. a Grep tool call whose tool_input was empty)
+ // even though the CLI is in full mode.
+ const captureModeRaw = ca("coding_agent.content_capture_mode");
+ const captureMode =
+ typeof captureModeRaw === "string" ? captureModeRaw.trim().toLowerCase() : "";
+ const showContentCaptureNote =
+ isCodingAgentTrace && captureMode !== "" && captureMode !== "full";
+
const hasEvaluationPanel = trace
? getExtraTabsContentTypes(trace).includes("Evaluation")
: false;
@@ -461,6 +740,50 @@ export function TraceDetailView({
router.push(resultsHref);
};
+ // Top-card overrides for coding-agent sessions only.
+ //
+ // `trace.*` is span-local — for a still-running session viewed at
+ // its root, or for any child span (llm.turn / tool.call /
+ // edit.decision) clicked into via the hierarchy explorer, those
+ // fields are either zero or reflect only that one span's slice.
+ // The sessions list page meanwhile shows the session-level
+ // rollup; without these overrides the trace-detail header
+ // silently disagrees with the row the user just clicked through
+ // from.
+ //
+ // Hard scope guardrail: `isCodingAgentTrace` is derived from
+ // `coding_agent.client` (set exclusively by the CLI's hook
+ // adapters in `cli/internal/otlp/exporter.go`). Non-coding traces
+ // (SDK instrumentation, manual OTel spans, ad-hoc curl) fall
+ // through to the existing `trace.*` values unchanged — the
+ // digest fetch itself is also gated on this flag (see useEffect
+ // at ~line 500), so for non-coding traces `sessionDigest` stays
+ // null and every override here short-circuits.
+ const codingTokensValue =
+ isCodingAgentTrace && sessionDigest && Number(sessionDigest.total_tokens) > 0
+ ? Number(sessionDigest.total_tokens).toLocaleString()
+ : undefined;
+ const codingCostValue =
+ isCodingAgentTrace && sessionDigest && Number(sessionDigest.cost_usd) > 0
+ ? `$${Number(sessionDigest.cost_usd).toFixed(4)}`
+ : undefined;
+ const codingDurationValue =
+ isCodingAgentTrace && sessionDigest
+ ? formatSessionDurationMs(Number(sessionDigest.duration_ms || 0))
+ : "";
+ const codingModelValue =
+ isCodingAgentTrace && sessionDigest && sessionDigest.model
+ ? sessionDigest.model
+ : "";
+
+ const tokensValue = codingTokensValue ?? trace?.totalTokens;
+ const costValue =
+ codingCostValue ?? (trace?.cost && trace.cost !== "-" ? `$${trace.cost}` : undefined);
+ const durationValue =
+ codingDurationValue ||
+ (trace ? `${parseFloat(trace.requestDuration).toFixed(3)}s` : "");
+ const modelValue = codingModelValue || trace?.model || trace?.serviceName;
+
return (
<DetailShell
title={title}
@@ -484,15 +807,15 @@ export function TraceDetailView({
{statusValue && (
<Stat icon={<AlertTriangle className="h-3.5 w-3.5" />} label="Status" value={statusValue} />
)}
- <Stat icon={<Clock className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_DURATION} value={`${parseFloat(trace.requestDuration).toFixed(3)}s`} />
- <Stat icon={<Zap className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_TOKENS} value={trace.totalTokens} />
+ <Stat icon={<Clock className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_DURATION} value={durationValue} />
+ <Stat icon={<Zap className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_TOKENS} value={tokensValue} />
<CostStat
- costValue={trace.cost && trace.cost !== "-" ? `$${trace.cost}` : undefined}
+ costValue={costValue}
spanId={trace.spanId}
- hasModel={!!trace.model}
+ hasModel={!!modelValue}
onRecalculated={fetchData}
/>
- <Stat icon={<Cpu className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_MODEL} value={trace.model || trace.serviceName} />
+ <Stat icon={<Cpu className="h-3.5 w-3.5" />} label={m.OBSERVABILITY_MODEL} value={modelValue} />
</div>
) : undefined
}
@@ -528,10 +851,66 @@ export function TraceDetailView({
<div className="flex flex-wrap gap-1.5">
<MetaPill label={m.OBSERVABILITY_TRACE_ID} value={trace.id} />
<MetaPill label={m.OBSERVABILITY_SPAN_ID} value={trace.spanId} />
- <MetaPill label={m.OBSERVABILITY_SERVICE} value={trace.serviceName} />
- <MetaPill label="Service Namespace" value={serviceNamespace} />
- <MetaPill label="Deployment Environment" value={deploymentEnvironment} />
+ {!isCodingAgentTrace && (
+ <>
+ <MetaPill label={m.OBSERVABILITY_SERVICE} value={trace.serviceName} />
+ <MetaPill label="Service Namespace" value={serviceNamespace} />
+ <MetaPill label="Deployment Environment" value={deploymentEnvironment} />
+ </>
+ )}
+ {isCodingAgentTrace && (
+ <>
+ <MetaPill
+ label="Coding Agent"
+ value={codingAgentVendor}
+ icon={
+ hasCodingAgentVendorIcon(codingAgentVendor) ? (
+ <CodingAgentVendorIcon
+ vendor={codingAgentVendor}
+ className="h-3.5 w-3.5"
+ />
+ ) : null
+ }
+ />
+ {/* User pill only renders for coding-agent
+ traces; on non-coding spans `gen_ai.user.name`
+ is usually empty and the pill became
+ blank noise. */}
+ {codingAgentUser ? (
+ <MetaPill label="User" value={codingAgentUser} />
+ ) : null}
+ </>
+ )}
+ <MetaPill label="Working Folder" value={workingDirLabel} />
+ <MetaPill label="Repository" value={repoLabel} />
+ <MetaPill label="Branch" value={branchName} />
+ {!isCodingAgentTrace && (
+ <MetaPill label="Mode" value={permissionMode} />
+ )}
+ <MetaPill label="Terminal" value={terminalType} />
+ {isCodingAgentTrace && (
+ <>
+ {/* Code-impact pills, anchored next to
+ Terminal so the row reads as one
+ "what was done in this session"
+ cluster. Order: Commits first
+ (whether work shipped), then the
+ add/remove split (volume), then
+ Acceptance + PRs as supporting
+ quality / shipping signals. */}
+ <MetaPill label="Commits" value={commitCountValue} />
+ <MetaPill label="Lines added" value={linesAddedValue} />
+ <MetaPill label="Lines deleted" value={linesRemovedValue} />
+ <MetaPill label="Acceptance" value={acceptanceValue} />
+ <MetaPill label="PRs" value={prCountValue} />
+ </>
+ )}
+ <MetaPill label="Outcome" value={sessionOutcome} />
+ <MetaPill label="Classification" value={userClassification} />
</div>
+ {showContentCaptureNote && (
+ <ContentCaptureNote />
+ )}
<div className="hidden h-[min(860px,calc(100vh-12rem))] min-h-[620px] overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950 lg:block">
<ResizablePanelGroup direction="horizontal" className="h-full">
<ResizablePanel defaultSize={48} minSize={32} maxSize={68}>
diff --git a/src/client/src/components/(playground)/request/components/chat-view.tsx b/src/client/src/components/(playground)/request/components/chat-view.tsx
index 4e91a80b..7b639cc3 100644
--- a/src/client/src/components/(playground)/request/components/chat-view.tsx
+++ b/src/client/src/components/(playground)/request/components/chat-view.tsx
@@ -22,21 +22,38 @@ import {
getSpanCostFormatted,
} from "@/helpers/client/trace";
import {
+ ArrowRight,
Bot,
+ Brain,
ChevronDown,
ChevronRight,
Clock,
Cog,
DollarSign,
+ FileEdit,
MessageSquare,
+ Network,
User,
Wrench,
} from "lucide-react";
import { useState } from "react";
+// OTel GenAI canonical key for the tool-call id. Kept local so the
+// chat view doesn't have to import the platform table-details (which
+// would pull a server-only module into a client component).
+const GEN_AI_TOOL_CALL_ID_ATTR = "gen_ai.tool.call.id";
+
// ─── Types ───────────────────────────────────────────────────────────────────
-type ChatItemType = "message" | "tool-indicator" | "span-indicator";
+type ChatItemType =
+ | "message"
+ | "tool-indicator"
+ | "span-indicator"
+ | "thought"
+ | "edit"
+ | "subagent"
+ | "mode-transition"
+ | "model-swap";
interface ChatItem {
type: ChatItemType;
@@ -48,6 +65,34 @@ interface ChatItem {
toolType?: string;
/** Tool call arguments (full, for expandable display) */
toolArgs?: string;
+ /** Tool call result (for coding-agent tool spans) */
+ toolResult?: string;
+ /** Free-form details, e.g. subagent summary or edit diff stats */
+ details?: string;
+ /** Optional sub-label, e.g. file path / mcp server / cwd */
+ subLabel?: string;
+ /**
+ * gen_ai.tool.call.id, set on tool-indicator and subagent items so
+ * the renderer can fold a (Task tool call, subagent stop) pair
+ * into one collapsible block instead of two separate timeline
+ * entries. Claude Code's subagents are bracketed exactly this way.
+ */
+ toolCallId?: string;
+ /**
+ * coding_agent.agent.parent_id, read from either SpanAttributes
+ * (Codex stamps it on every span) or ResourceAttributes (Cursor
+ * stamps it as a resource attr). When non-empty AND this isn't
+ * the parent chat the viewer is currently looking at, the
+ * timeline indents the item to show it ran inside a subagent.
+ */
+ parentId?: string;
+ /**
+ * Mode / model transition from-value, e.g. "agent". Renders as
+ * `Plan mode → Agent mode` slim pill.
+ */
+ fromValue?: string;
+ /** Mode / model transition to-value. */
+ toValue?: string;
span: TraceHeirarchySpan;
timestampMs: number;
}
@@ -71,11 +116,52 @@ function tryParseJson(raw: unknown): any[] | null {
}
}
+/**
+ * True when the string looks like it was meant to be JSON (starts
+ * with `[` or `{`, optionally after whitespace). Used by
+ * `extractTextMessages` to suppress the raw-string fallback when
+ * the value was clearly a serialised messages envelope that simply
+ * failed to parse — usually because it was truncated mid-token at
+ * the OTLP attribute-size cap. Without this guard, the truncated
+ * blob renders as a "user" bubble with the full raw JSON inside,
+ * which is how Claude Code traces ended up showing tool_result
+ * contents as user messages.
+ */
+function looksLikeJson(raw: string): boolean {
+ const trimmed = raw.trimStart();
+ return trimmed.startsWith("[") || trimmed.startsWith("{");
+}
+
function extractTextMessages(
- raw: unknown
+ raw: unknown,
+ defaultRole: "user" | "assistant" = "user"
): { role: string; content: string }[] {
+ if (raw == null) return [];
+ // The CLI emits `gen_ai.{input,output}.messages` per the OTel
+ // GenAI semantic convention (https://github.com/open-telemetry/
+ // semantic-conventions-genai → docs/gen-ai/gen-ai-spans.md):
+ // [{ role, parts: [{ type: "text", content: "..." }],
+ // finish_reason? }]
+ // Tool-call / tool-call-response parts are intentionally NOT
+ // stamped onto LLM-turn messages by the CLI — the canonical
+ // source for tool data is the matching `coding_agent.tool.call`
+ // span. See cli/internal/otlp/attrs.go for the rationale.
+ //
+ // Legacy paths fall back to a plain string body and to OpenAI's
+ // `content: "..."` / `content: [{type:"text", text:"..."}]` so
+ // vendors mid-migration still render.
const arr = tryParseJson(raw);
- if (!arr) return [];
+ if (!arr) {
+ if (typeof raw === "string" && raw.trim()) {
+ // Drop unparseable strings that look like JSON — they're
+ // almost always a truncated messages envelope, and
+ // rendering them verbatim creates the "tool_result JSON
+ // appears as a user bubble" failure mode.
+ if (looksLikeJson(raw)) return [];
+ return [{ role: defaultRole, content: raw }];
+ }
+ return [];
+ }
const result: { role: string; content: string }[] = [];
for (const msg of arr) {
@@ -83,14 +169,27 @@ function extractTextMessages(
const role = msg.role || "unknown";
if (Array.isArray(msg.parts)) {
- const texts: string[] = [];
+ const lines: string[] = [];
for (const p of msg.parts) {
- if (p?.type === "text" && typeof p.content === "string" && p.content) {
- texts.push(p.content);
+ if (!p?.type) continue;
+ if (p.type === "text") {
+ // OTel canonical uses `content`; legacy emitters
+ // may use `text` — accept both for resilience.
+ const t =
+ (typeof p.content === "string" && p.content) ||
+ (typeof p.text === "string" && p.text) ||
+ "";
+ if (t) lines.push(t);
}
+ // `tool_call` / `tool_call_response` parts are
+ // intentionally ignored here. Tool data lives on
+ // `coding_agent.tool.call` spans (rendered by
+ // `ToolIndicator` below); duplicating it inside a
+ // chat bubble produces redundant "Tool Result" /
+ // "🛠 tool_call" lines that clutter the conversation.
}
- if (texts.length > 0) {
- result.push({ role, content: texts.join("\n") });
+ if (lines.length > 0) {
+ result.push({ role, content: lines.join("\n\n") });
}
continue;
}
@@ -161,6 +260,16 @@ function anyDescendantHasMessages(span: TraceHeirarchySpan): boolean {
return false;
}
+function readParentId(span: TraceHeirarchySpan): string {
+ const sa = span.SpanAttributes || {};
+ const ra = span.ResourceAttributes || {};
+ const v =
+ (sa["coding_agent.agent.parent_id"] as string | undefined) ||
+ ra["coding_agent.agent.parent_id"] ||
+ "";
+ return typeof v === "string" ? v : "";
+}
+
function extractItemsFromSpan(
span: TraceHeirarchySpan,
skipMessages: boolean
@@ -169,16 +278,26 @@ function extractItemsFromSpan(
const items: ChatItem[] = [];
const ts = parseTimestampMs(span.Timestamp);
const spanDurationMs = span.Duration / 1e6;
+ const isCodingLLMTurn = span.SpanName === "coding_agent.llm.turn";
+ const parentId = readParentId(span);
+
+ // Coding-agent llm.turn carries a `kind` attribute that disambiguates
+ // what the span represents:
+ // - "user_prompt" → user message body lives in input.messages
+ // - "assistant_only" → assistant body lives in output.messages
+ // - empty + thought → thinking-only turn (no user-visible message)
+ const codingTurnKind = attrs["coding_agent.llm.turn.kind"] as string | undefined;
if (!skipMessages) {
// ── Input messages ──
- const inputMsgs = extractTextMessages(attrs["gen_ai.input.messages"]);
+ const inputMsgs = extractTextMessages(attrs["gen_ai.input.messages"], "user");
if (inputMsgs.length > 0) {
for (const msg of inputMsgs) {
items.push({
type: "message",
role: normalizeRole(msg.role),
content: msg.content,
+ parentId,
span,
timestampMs: ts,
});
@@ -192,6 +311,7 @@ function extractItemsFromSpan(
type: "message",
role: "user",
content: prompt,
+ parentId,
span,
timestampMs: ts,
});
@@ -199,13 +319,17 @@ function extractItemsFromSpan(
}
// ── Output messages ──
- const outputMsgs = extractTextMessages(attrs["gen_ai.output.messages"]);
+ const outputMsgs = extractTextMessages(
+ attrs["gen_ai.output.messages"],
+ "assistant"
+ );
if (outputMsgs.length > 0) {
for (const msg of outputMsgs) {
items.push({
type: "message",
role: normalizeRole(msg.role),
content: msg.content,
+ parentId,
span,
timestampMs: ts + spanDurationMs,
});
@@ -219,45 +343,170 @@ function extractItemsFromSpan(
type: "message",
role: "assistant",
content: response,
+ parentId,
span,
timestampMs: ts + spanDurationMs,
});
}
}
+
+ // ── Reasoning / thinking text (coding-agent only) ──
+ const thoughtText = attrs["coding_agent.llm.thought.text"] as
+ | string
+ | undefined;
+ if (thoughtText && thoughtText.trim()) {
+ const thoughtMs = Number(
+ attrs["coding_agent.llm.thought.duration_ms"] || 0
+ );
+ items.push({
+ type: "thought",
+ content: thoughtText,
+ meta:
+ thoughtMs > 0
+ ? `${(thoughtMs / 1000).toFixed(1)}s of thinking`
+ : undefined,
+ parentId,
+ span,
+ timestampMs: ts + spanDurationMs * 0.25,
+ });
+ }
}
// ── Tool call indicator (always shown — these are actions, not duplicated) ──
+ // Coding-agent tool.call spans carry the same gen_ai.tool.* attrs, plus
+ // optional MCP server name, command (for shell tools), cwd, and the tool
+ // result. We surface those alongside the standard fields.
const toolName = attrs["gen_ai.tool.name"] as string | undefined;
const toolCallId = attrs["gen_ai.tool.call.id"] as string | undefined;
const toolArgs = attrs["gen_ai.tool.call.arguments"] as string | undefined;
const toolType = attrs["gen_ai.tool.type"] as string | undefined;
+ const toolResult = attrs["gen_ai.tool.call.result"] as string | undefined;
+ const toolCommand = attrs["coding_agent.tool.command"] as string | undefined;
+ const toolCwd = attrs["code.cwd"] as string | undefined;
+ const toolMCPServer = attrs["coding_agent.mcp.server.name"] as
+ | string
+ | undefined;
+ const toolErrorType = attrs["error.type"] as string | undefined;
if (toolName) {
+ const subLabelParts: string[] = [];
+ if (toolMCPServer) subLabelParts.push(`MCP: ${toolMCPServer}`);
+ if (toolCwd) subLabelParts.push(toolCwd);
items.push({
type: "tool-indicator",
label: toolName,
meta: toolCallId || undefined,
- toolType: toolType || undefined,
- toolArgs: toolArgs || undefined,
+ toolType: toolType || (toolErrorType ? `error: ${toolErrorType}` : undefined),
+ // Prefer the structured arguments JSON; if absent, surface the raw
+ // shell command so shell-style tool calls (Bash, run_shell) are
+ // still readable in the chat view.
+ toolArgs: toolArgs || toolCommand || undefined,
+ toolResult: toolResult || undefined,
+ subLabel: subLabelParts.join(" • ") || undefined,
+ toolCallId: toolCallId || undefined,
+ parentId,
span,
timestampMs: ts + spanDurationMs * 0.5,
});
}
+ // ── Edit decision (coding-agent only) ──
+ if (span.SpanName === "coding_agent.edit.decision") {
+ const filePath = attrs["code.file.path"] as string | undefined;
+ const decision = attrs["coding_agent.edit.decision"] as string | undefined;
+ const linesAdded = Number(attrs["coding_agent.edit.lines_added"] || 0);
+ const linesRemoved = Number(attrs["coding_agent.edit.lines_removed"] || 0);
+ const lang = attrs["coding_agent.edit.language"] as string | undefined;
+ items.push({
+ type: "edit",
+ label: decision || "edit",
+ subLabel: filePath || undefined,
+ meta: lang || undefined,
+ details:
+ linesAdded || linesRemoved
+ ? `+${linesAdded} / -${linesRemoved}`
+ : undefined,
+ parentId,
+ span,
+ timestampMs: ts,
+ });
+ }
+
+ // ── Subagent (coding-agent only) ──
+ if (span.SpanName === "coding_agent.subagent") {
+ const subagentType = attrs["coding_agent.subagent.type"] as string | undefined;
+ const task = attrs["coding_agent.subagent.task"] as string | undefined;
+ const summary = attrs["coding_agent.subagent.summary"] as string | undefined;
+ // gen_ai.tool.call.id is the canonical OTel key (now stamped
+ // by setSubagentAttrs). Keep the legacy `coding_agent.subagent.tool_call_id`
+ // readable so older traces still group correctly.
+ const subagentToolCallId =
+ (attrs[GEN_AI_TOOL_CALL_ID_ATTR] as string | undefined) ||
+ (attrs["coding_agent.subagent.tool_call_id"] as string | undefined);
+ items.push({
+ type: "subagent",
+ label: subagentType || "subagent",
+ content: task || undefined,
+ details: summary || undefined,
+ toolCallId: subagentToolCallId || undefined,
+ parentId,
+ span,
+ timestampMs: ts,
+ });
+ }
+
+ // ── Permission-mode transition (coding-agent only) ──
+ // Emitted as a low-cost child span by hook.go whenever the user
+ // toggles Cursor's composer_mode / Claude Code's permission_mode
+ // / Codex's approval_mode mid-session. Show as a slim centered
+ // pill so the chat reads like a Slack channel.
+ if (span.SpanName === "coding_agent.session.permission_mode.changed") {
+ items.push({
+ type: "mode-transition",
+ fromValue:
+ (attrs["coding_agent.session.permission_mode.from"] as string) || "",
+ toValue:
+ (attrs["coding_agent.session.permission_mode.to"] as string) || "",
+ parentId,
+ span,
+ timestampMs: ts,
+ });
+ }
+ // ── Model swap (coding-agent only) ──
+ if (span.SpanName === "coding_agent.session.model.changed") {
+ items.push({
+ type: "model-swap",
+ fromValue: (attrs["coding_agent.session.model.from"] as string) || "",
+ toValue: (attrs["coding_agent.session.model.to"] as string) || "",
+ parentId,
+ span,
+ timestampMs: ts,
+ });
+ }
+
// ── Non-LLM span indicator ──
- if (items.length === 0) {
+ // Only fall through when the span produced nothing else above. We
+ // also explicitly skip the coding_agent.session root span (it carries
+ // session-level metadata that's surfaced in the header, not the chat).
+ if (
+ items.length === 0 &&
+ span.SpanName !== "coding_agent.session" &&
+ !isCodingLLMTurn
+ ) {
const spanKind =
(attrs["gen_ai.operation.name"] as string) ||
- (attrs["openai.api_type"] as string);
+ (attrs["openai.api_type"] as string) ||
+ codingTurnKind;
const isInteresting =
spanKind ||
span.SpanName.match(
- /retriev|embed|search|tool|function|db|query|fetch|call/i
+ /retriev|embed|search|tool|function|db|query|fetch|call|coding_agent/i
);
if (isInteresting) {
items.push({
type: "span-indicator",
label: span.SpanName,
meta: spanKind || undefined,
+ parentId,
span,
timestampMs: ts,
});
@@ -278,9 +527,13 @@ function ToolIndicator({
isSelected: boolean;
onClick: () => void;
}) {
- const [expanded, setExpanded] = useState(false);
+ const [argsExpanded, setArgsExpanded] = useState(false);
+ const [resultExpanded, setResultExpanded] = useState(false);
const prettyArgs = item.toolArgs ? tryPrettyJson(item.toolArgs) : null;
const displayArgs = prettyArgs || item.toolArgs;
+ const prettyResult = item.toolResult ? tryPrettyJson(item.toolResult) : null;
+ const displayResult = prettyResult || item.toolResult;
+ const isMCP = !!item.subLabel?.startsWith("MCP:");
return (
<div
@@ -294,7 +547,13 @@ function ToolIndicator({
{/* Header row */}
<div className="flex items-center gap-2 px-2.5 py-1.5">
<div className="flex h-5 w-5 shrink-0 items-center justify-center rounded border border-stone-200 bg-stone-50 dark:border-stone-800 dark:bg-stone-900">
- <Wrench className="h-3 w-3 text-stone-500 dark:text-stone-400" />
+ {isMCP ? (
+ <Network className="h-3 w-3 text-violet-500 dark:text-violet-400" />
+ ) : item.toolType?.startsWith("error") ? (
+ <Wrench className="h-3 w-3 text-rose-500 dark:text-rose-400" />
+ ) : (
+ <Wrench className="h-3 w-3 text-stone-500 dark:text-stone-400" />
+ )}
</div>
<div className="flex flex-col min-w-0 flex-1">
<div className="flex items-center gap-1.5">
@@ -302,18 +561,29 @@ function ToolIndicator({
{item.label}
</span>
{item.toolType && (
- <span className="rounded border border-stone-200 px-1.5 py-0.5 text-[9px] font-medium text-stone-500 dark:border-stone-800 dark:text-stone-400">
+ <span
+ className={`rounded border px-1.5 py-0.5 text-[9px] font-medium ${
+ item.toolType.startsWith("error")
+ ? "border-rose-200 text-rose-700 dark:border-rose-900 dark:text-rose-300"
+ : "border-stone-200 text-stone-500 dark:border-stone-800 dark:text-stone-400"
+ }`}
+ >
{item.toolType}
</span>
)}
</div>
+ {item.subLabel && (
+ <span className="truncate text-[10px] text-stone-500 dark:text-stone-400">
+ {item.subLabel}
+ </span>
+ )}
{item.meta && (
- <span className="text-[9px] text-stone-400 dark:text-stone-500 font-mono truncate">
+ <span className="truncate font-mono text-[9px] text-stone-400 dark:text-stone-500">
{item.meta}
</span>
)}
</div>
- <span className="text-[9px] tabular-nums text-stone-400 dark:text-stone-500 shrink-0">
+ <span className="shrink-0 text-[9px] tabular-nums text-stone-400 dark:text-stone-500">
{getSpanDurationDisplay(item.span)}
</span>
</div>
@@ -322,26 +592,275 @@ function ToolIndicator({
{displayArgs && (
<div className="border-t border-stone-200 dark:border-stone-700">
<button
- className="flex items-center gap-1 px-2.5 py-1 text-[10px] text-stone-400 dark:text-stone-500 hover:text-stone-600 dark:hover:text-stone-300 w-full"
+ className="flex w-full items-center gap-1 px-2.5 py-1 text-[10px] text-stone-400 hover:text-stone-600 dark:text-stone-500 dark:hover:text-stone-300"
onClick={(e) => {
e.stopPropagation();
- setExpanded(!expanded);
+ setArgsExpanded(!argsExpanded);
}}
>
- {expanded ? (
+ {argsExpanded ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
Arguments
</button>
- {expanded && (
- <pre className="px-2.5 pb-2 text-[10px] leading-relaxed text-stone-600 dark:text-stone-400 font-mono overflow-x-auto max-h-48 overflow-y-auto">
+ {argsExpanded && (
+ <pre className="max-h-48 overflow-y-auto overflow-x-auto px-2.5 pb-2 font-mono text-[10px] leading-relaxed text-stone-600 dark:text-stone-400">
{displayArgs}
</pre>
)}
</div>
)}
+
+ {/* Expandable result */}
+ {displayResult && (
+ <div className="border-t border-stone-200 dark:border-stone-700">
+ <button
+ className="flex w-full items-center gap-1 px-2.5 py-1 text-[10px] text-stone-400 hover:text-stone-600 dark:text-stone-500 dark:hover:text-stone-300"
+ onClick={(e) => {
+ e.stopPropagation();
+ setResultExpanded(!resultExpanded);
+ }}
+ >
+ {resultExpanded ? (
+ <ChevronDown className="h-3 w-3" />
+ ) : (
+ <ChevronRight className="h-3 w-3" />
+ )}
+ Result
+ </button>
+ {resultExpanded && (
+ <pre className="max-h-48 overflow-y-auto overflow-x-auto px-2.5 pb-2 font-mono text-[10px] leading-relaxed text-stone-600 dark:text-stone-400">
+ {displayResult}
+ </pre>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ThoughtIndicator({
+ item,
+ isSelected,
+ onClick,
+}: {
+ item: ChatItem;
+ isSelected: boolean;
+ onClick: () => void;
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const text = item.content || "";
+ const preview = text.length > 280 ? text.slice(0, 280) + "…" : text;
+ const showToggle = text.length > 280;
+ return (
+ <div
+ className={`mx-2 cursor-pointer rounded-md border border-dashed transition-colors ${
+ isSelected
+ ? "border-amber-400/60 bg-amber-50/60 dark:border-amber-500/40 dark:bg-amber-950/30"
+ : "border-stone-300 bg-stone-50 hover:bg-stone-100 dark:border-stone-700 dark:bg-stone-900/40 dark:hover:bg-stone-900"
+ }`}
+ onClick={onClick}
+ >
+ <div className="flex items-start gap-2 px-2.5 py-1.5">
+ <Brain className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500 dark:text-amber-400" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="text-[10px] font-medium uppercase tracking-wide text-amber-700 dark:text-amber-400">
+ Thinking
+ </span>
+ {item.meta && (
+ <span className="text-[10px] text-stone-400 dark:text-stone-500">
+ {item.meta}
+ </span>
+ )}
+ </div>
+ <pre className="mt-1 whitespace-pre-wrap break-words font-sans text-[12px] leading-relaxed text-stone-700 dark:text-stone-300">
+ {expanded || !showToggle ? text : preview}
+ </pre>
+ {showToggle && (
+ <button
+ className="mt-0.5 text-[10px] text-stone-500 hover:text-stone-700 dark:text-stone-400 dark:hover:text-stone-200"
+ onClick={(e) => {
+ e.stopPropagation();
+ setExpanded((v) => !v);
+ }}
+ >
+ {expanded ? "Show less" : "Show more"}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function EditIndicator({
+ item,
+ isSelected,
+ onClick,
+}: {
+ item: ChatItem;
+ isSelected: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <div
+ className={`mx-2 flex cursor-pointer items-center gap-2 rounded-md border px-2.5 py-1.5 transition-colors ${
+ isSelected
+ ? "border-emerald-400/40 bg-emerald-50/60 dark:border-emerald-500/40 dark:bg-emerald-950/30"
+ : "border-stone-200 bg-white hover:bg-stone-50 dark:border-stone-800 dark:bg-stone-950 dark:hover:bg-stone-900"
+ }`}
+ onClick={onClick}
+ >
+ <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded border border-stone-200 bg-stone-50 dark:border-stone-800 dark:bg-stone-900">
+ <FileEdit className="h-3 w-3 text-emerald-500 dark:text-emerald-400" />
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex items-center gap-1.5">
+ <span className="text-[11px] font-semibold uppercase tracking-wide text-emerald-700 dark:text-emerald-400">
+ {item.label}
+ </span>
+ {item.meta && (
+ <span className="rounded border border-stone-200 px-1.5 py-0.5 text-[9px] font-medium text-stone-500 dark:border-stone-800 dark:text-stone-400">
+ {item.meta}
+ </span>
+ )}
+ </div>
+ {item.subLabel && (
+ <span className="truncate font-mono text-[10px] text-stone-500 dark:text-stone-400">
+ {item.subLabel}
+ </span>
+ )}
+ </div>
+ {item.details && (
+ <span className="shrink-0 font-mono text-[10px] text-stone-500 dark:text-stone-400">
+ {item.details}
+ </span>
+ )}
+ </div>
+ );
+}
+
+function SubagentIndicator({
+ item,
+ isSelected,
+ onClick,
+}: {
+ item: ChatItem;
+ isSelected: boolean;
+ onClick: () => void;
+}) {
+ const [expanded, setExpanded] = useState(false);
+ return (
+ <div
+ className={`mx-2 cursor-pointer rounded-md border transition-colors ${
+ isSelected
+ ? "border-violet-400/50 bg-violet-50/70 dark:border-violet-500/50 dark:bg-violet-950/30"
+ : "border-stone-200 bg-white hover:bg-stone-50 dark:border-stone-800 dark:bg-stone-950 dark:hover:bg-stone-900"
+ }`}
+ onClick={onClick}
+ >
+ <div className="flex items-start gap-2 px-2.5 py-1.5">
+ <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded border border-stone-200 bg-stone-50 dark:border-stone-800 dark:bg-stone-900">
+ <Bot className="h-3 w-3 text-violet-500 dark:text-violet-400" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <span className="text-[11px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-400">
+ Subagent
+ </span>
+ <span className="text-[10px] text-stone-500 dark:text-stone-400">
+ {item.label}
+ </span>
+ </div>
+ {item.content && (
+ <p className="mt-1 line-clamp-2 whitespace-pre-wrap text-[12px] leading-relaxed text-stone-700 dark:text-stone-300">
+ {item.content}
+ </p>
+ )}
+ {item.details && (
+ <>
+ <button
+ className="mt-1 flex items-center gap-1 text-[10px] text-stone-500 hover:text-stone-700 dark:text-stone-400 dark:hover:text-stone-200"
+ onClick={(e) => {
+ e.stopPropagation();
+ setExpanded((v) => !v);
+ }}
+ >
+ {expanded ? (
+ <ChevronDown className="h-3 w-3" />
+ ) : (
+ <ChevronRight className="h-3 w-3" />
+ )}
+ Summary
+ </button>
+ {expanded && (
+ <pre className="mt-1 whitespace-pre-wrap break-words font-sans text-[11px] leading-relaxed text-stone-600 dark:text-stone-400">
+ {item.details}
+ </pre>
+ )}
+ </>
+ )}
+ </div>
+ <span className="shrink-0 text-[9px] tabular-nums text-stone-400 dark:text-stone-500">
+ {getSpanDurationDisplay(item.span)}
+ </span>
+ </div>
+ </div>
+ );
+}
+
+// ─── Inline session-event pill (mode-transition / model-swap) ────────────────
+
+/**
+ * Slim centered pill used for non-conversational session events that
+ * happen between bubbles. Read like "--- Plan mode → Agent mode ---"
+ * so the eye knows the toggle happened but isn't pulled away from the
+ * conversation.
+ */
+function TransitionPill({
+ item,
+ prefix,
+ suffix,
+ indented,
+}: {
+ item: ChatItem;
+ prefix: string;
+ suffix?: string;
+ indented?: boolean;
+}) {
+ const from = (item.fromValue || "").trim();
+ const to = (item.toValue || "").trim();
+ if (!from && !to) return null;
+ return (
+ <div
+ className={`flex justify-center px-2 py-0.5 ${
+ indented ? "pl-6" : ""
+ }`}
+ >
+ <div className="inline-flex items-center gap-1.5 rounded-full border border-stone-200 bg-stone-50 px-2.5 py-0.5 text-[10px] uppercase tracking-wide text-stone-500 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-400">
+ <span className="font-semibold">{prefix}</span>
+ {from && (
+ <>
+ <span className="font-mono text-stone-600 dark:text-stone-300">
+ {from}
+ </span>
+ <ArrowRight className="h-2.5 w-2.5" />
+ </>
+ )}
+ {to && (
+ <span className="font-mono text-stone-600 dark:text-stone-300">
+ {to}
+ </span>
+ )}
+ {suffix && (
+ <span className="text-stone-400 dark:text-stone-500">
+ {suffix}
+ </span>
+ )}
+ </div>
</div>
);
}
@@ -435,7 +954,8 @@ export default function ChatView({
// In multi-step agent traces, each LLM call span carries the full
// conversation history in gen_ai.input.messages — so the same user
// prompt appears in every step. We keep only the first occurrence.
- // Tool indicators and span indicators are never deduped (they're unique actions).
+ // Tool indicators, span indicators, thoughts, edits, and subagents
+ // are never deduped (they're unique actions).
const seenMessages = new Set<string>();
const dedupedItems = allItems.filter((item) => {
if (item.type !== "message") return true; // keep all non-message items
@@ -445,8 +965,62 @@ export default function ChatView({
return true;
});
+ // 5b. Fold (Task tool-call → subagent) pairs into a single block.
+ // Claude Code emits PreToolUse(Task) as a separate tool span,
+ // then a SubagentStop span later. Both carry the same
+ // gen_ai.tool.call.id (newly stamped by setSubagentAttrs +
+ // PreToolUse caching in sessionstate). Rendering both would
+ // show the Task tool indicator AND the Subagent banner —
+ // redundant. Keep the subagent item, drop the tool indicator
+ // that pairs with it, and copy the tool's args onto the
+ // subagent so the user can still see what was requested.
+ const subagentByCallId = new Map<string, ChatItem>();
+ for (const it of dedupedItems) {
+ if (it.type === "subagent" && it.toolCallId) {
+ subagentByCallId.set(it.toolCallId, it);
+ }
+ }
+ const grouped = dedupedItems.filter((it) => {
+ if (
+ it.type === "tool-indicator" &&
+ it.label === "Task" &&
+ it.toolCallId &&
+ subagentByCallId.has(it.toolCallId)
+ ) {
+ // Merge the tool args/result onto the subagent item once.
+ const sa = subagentByCallId.get(it.toolCallId)!;
+ if (!sa.toolArgs && it.toolArgs) sa.toolArgs = it.toolArgs;
+ if (!sa.toolResult && it.toolResult) sa.toolResult = it.toolResult;
+ return false;
+ }
+ return true;
+ });
+
+ // 5c. Identify the parent chat id we're currently viewing so the
+ // renderer only indents items belonging to a *different*
+ // parent (i.e. spans from a subagent that ran inside this
+ // chat). Items whose parent_id == the chat we're viewing are
+ // the chat's own spans and stay flush-left.
+ let viewerChatId = "";
+ for (const it of grouped) {
+ const sa = it.span.SpanAttributes || {};
+ const ra = it.span.ResourceAttributes || {};
+ const ownId =
+ (sa["coding_agent.session.id"] as string | undefined) ||
+ ra["coding_agent.session.id"] ||
+ (sa["gen_ai.conversation.id"] as string | undefined) ||
+ ra["gen_ai.conversation.id"] ||
+ "";
+ if (ownId && !it.parentId) {
+ viewerChatId = ownId as string;
+ break;
+ }
+ }
+ const isSubagentItem = (it: ChatItem) =>
+ !!it.parentId && it.parentId !== viewerChatId;
+
// 6. Empty state
- if (dedupedItems.length === 0) {
+ if (grouped.length === 0) {
return (
<div className="flex flex-col items-center justify-center h-full text-stone-400 dark:text-stone-500 gap-2 py-12">
<MessageSquare className="h-8 w-8" />
@@ -460,14 +1034,95 @@ export default function ChatView({
return (
<div className="flex flex-col gap-2 py-2">
- {dedupedItems.map((item, i) => {
+ {grouped.map((item, i) => {
const isSelected = request?.spanId === item.span.SpanId;
+ const indented = isSubagentItem(item);
+ // Subagent items rendered indented with a thin left
+ // border so the user can see at a glance which part
+ // of the chat ran inside a subagent and which is the
+ // parent agent's own work. The border colour matches
+ // the SubagentIndicator's violet accent.
+ const indentClass = indented
+ ? "ml-6 border-l-2 border-violet-300/60 pl-2 dark:border-violet-700/50"
+ : "";
+
+ // ── Mode transition pill ──
+ if (item.type === "mode-transition") {
+ return (
+ <TransitionPill
+ key={`${item.span.SpanId}-mode-${i}`}
+ item={item}
+ prefix="Mode"
+ indented={indented}
+ />
+ );
+ }
+
+ // ── Model swap pill ──
+ if (item.type === "model-swap") {
+ return (
+ <TransitionPill
+ key={`${item.span.SpanId}-model-${i}`}
+ item={item}
+ prefix="Model"
+ indented={indented}
+ />
+ );
+ }
// ── Tool call indicator ──
if (item.type === "tool-indicator") {
return (
- <ToolIndicator
- key={`${item.span.SpanId}-tool-${i}`}
+ <div key={`${item.span.SpanId}-tool-${i}`} className={indentClass}>
+ <ToolIndicator
+ item={item}
+ isSelected={isSelected}
+ onClick={() =>
+ updateRequest({ spanId: item.span.SpanId })
+ }
+ />
+ </div>
+ );
+ }
+
+ // ── Thinking / reasoning text ──
+ if (item.type === "thought") {
+ return (
+ <div key={`${item.span.SpanId}-thought-${i}`} className={indentClass}>
+ <ThoughtIndicator
+ item={item}
+ isSelected={isSelected}
+ onClick={() =>
+ updateRequest({ spanId: item.span.SpanId })
+ }
+ />
+ </div>
+ );
+ }
+
+ // ── Edit decision ──
+ if (item.type === "edit") {
+ return (
+ <div key={`${item.span.SpanId}-edit-${i}`} className={indentClass}>
+ <EditIndicator
+ item={item}
+ isSelected={isSelected}
+ onClick={() =>
+ updateRequest({ spanId: item.span.SpanId })
+ }
+ />
+ </div>
+ );
+ }
+
+ // ── Subagent — always shown flush-left even when it
+ // represents inner-subagent activity, because the
+ // block itself is the visual anchor for that
+ // "subagent triggered" moment.
+ if (item.type === "subagent") {
+ return (
+ <SubagentIndicator
+ key={`${item.span.SpanId}-subagent-${i}`}
item={item}
isSelected={isSelected}
onClick={() =>
@@ -486,7 +1141,7 @@ export default function ChatView({
isSelected
? "border-primary/40 bg-primary/5"
: "border-stone-200 bg-white hover:bg-stone-50 dark:border-stone-800 dark:bg-stone-950 dark:hover:bg-stone-900"
- }`}
+ } ${indentClass}`}
onClick={() =>
updateRequest({ spanId: item.span.SpanId })
}
@@ -516,7 +1171,7 @@ export default function ChatView({
return (
<div
key={`${item.span.SpanId}-${role}-${i}`}
- className={`flex flex-col gap-0.5 px-2 ${config.align}`}
+ className={`flex flex-col gap-0.5 px-2 ${config.align} ${indentClass}`}
>
{/* Role label + span name */}
<div
diff --git a/src/client/src/components/(playground)/request/components/node-graph.tsx b/src/client/src/components/(playground)/request/components/node-graph.tsx
index f9bdb456..f6dc6d08 100644
--- a/src/client/src/components/(playground)/request/components/node-graph.tsx
+++ b/src/client/src/components/(playground)/request/components/node-graph.tsx
@@ -18,6 +18,7 @@ import {
getSpanDurationDisplay,
getSpanCostFormatted,
getSpanTooltipText,
+ isSyntheticSpanId,
} from "@/helpers/client/trace";
import { transformTracesToGraph } from "@/lib/platform/graph-transform";
import { useCallback, useEffect, useRef, useMemo, useState } from "react";
@@ -237,11 +238,18 @@ export default function NodeGraph({ record }: { record: TraceHeirarchySpan }) {
const dur = getSpanDurationDisplay(displaySpan);
const cost = getSpanCostFormatted(displaySpan, 4);
const tooltipText = getSpanTooltipText(displaySpan);
+ // Synthetic session-root node is a grouping device with
+ // no backing span — not selectable (no detail to show).
+ const synthetic = isSyntheticSpanId(node.spanId);
return (
<g key={node.spanId}
- onClick={e => { e.stopPropagation(); updateRequest({ spanId: node.spanId }); }}
- style={{ cursor: "pointer" }}
+ onClick={
+ synthetic
+ ? undefined
+ : e => { e.stopPropagation(); updateRequest({ spanId: node.spanId }); }
+ }
+ style={{ cursor: synthetic ? "default" : "pointer" }}
>
<title>{tooltipText}</title>
diff --git a/src/client/src/components/svg/coding-agents.tsx b/src/client/src/components/svg/coding-agents.tsx
new file mode 100644
index 00000000..a6dda592
--- /dev/null
+++ b/src/client/src/components/svg/coding-agents.tsx
@@ -0,0 +1,171 @@
+/**
+ * Vendor icons for coding-agent rows. Mirrors the convention in
+ * `components/svg/providers.tsx` — tiny SVGs inlined as React components
+ * so we don't add network round-trips to the agents hub or the session
+ * list. Each icon takes a `className` for sizing/colour.
+ *
+ * Source attributions:
+ * - Cursor: derived from icons8.com (cursor-ai), simplified for inline
+ * rendering. Recolours via the parent `text-*` class are not
+ * supported because Cursor's logo uses a deliberate multi-tone fill.
+ * - Claude Code: official Anthropic Claude Code mark, inlined as a
+ * single-path SVG. Single-tone (#D97757) so it tints correctly when
+ * placed inside a coloured pill.
+ * - Codex: derived from OpenAI's official Codex flower / swirl mark.
+ * Hand-traced as four 90°-rotated petals + an inner counter-flower
+ * so the icon stays under ~1KB and tints via `currentColor` when no
+ * explicit fill is supplied. The default fill (#788CFE) matches the
+ * primary swirl colour in the upstream SVG so the icon still reads
+ * as "Codex" outside a coloured pill.
+ */
+
+import type { SVGProps } from "react";
+
+type IconProps = SVGProps<SVGSVGElement> & { className?: string };
+
+export function CursorIcon({ className = "h-4 w-4", ...rest }: IconProps) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 48 48"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ baseProfile="basic"
+ className={className}
+ aria-label="Cursor"
+ role="img"
+ {...rest}
+ >
+ <polygon
+ fill="#bcbcbc"
+ points="23.974,4 6.97,14 6.97,34 23.998,44 40.97,34 40.97,14"
+ />
+ <polygon fill="#757575" points="23.974,4 6.97,14 6.97,34 23.97,24" />
+ <polygon fill="#424242" points="23.981,14 40.97,14 40.97,34 23.971,24" />
+ <polygon
+ fill="#616161"
+ fillRule="evenodd"
+ points="40.97,14 23.966,17 23.974,4"
+ clipRule="evenodd"
+ />
+ <polygon
+ fill="#616161"
+ fillRule="evenodd"
+ points="6.97,14 23.981,16.881 23.966,24 6.97,34"
+ clipRule="evenodd"
+ />
+ <polygon
+ fill="#ededed"
+ points="6.97,14 23.97,24 23.998,44 40.97,14"
+ />
+ </svg>
+ );
+}
+
+export function ClaudeCodeIcon({
+ className = "h-4 w-4",
+ ...rest
+}: IconProps) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ className={className}
+ aria-label="Claude Code"
+ role="img"
+ {...rest}
+ >
+ <path
+ clipRule="evenodd"
+ d="M20.998 10.949H24v3.102h-3v3.028h-1.487V20H18v-2.921h-1.487V20H15v-2.921H9V20H7.488v-2.921H6V20H4.487v-2.921H3V14.05H0V10.95h3V5h17.998v5.949zM6 10.949h1.488V8.102H6v2.847zm10.51 0H18V8.102h-1.49v2.847z"
+ fill="#D97757"
+ fillRule="evenodd"
+ />
+ </svg>
+ );
+}
+
+export function CodexIcon({ className = "h-4 w-4" }: IconProps) {
+ // The official Codex flower mark is detail-heavy (~120 traced paths
+ // covering the photo-realistic gradient swirl), so embedding it
+ // inline would bloat the JS bundle. We serve the asset from
+ // /public/images/codex.svg instead and reference it via <img> so
+ // Next.js streams it as a static file and the browser caches it.
+ // The <img> still accepts the same className the other vendor icons
+ // take, so this remains a drop-in for the existing call-sites.
+ return (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src="/images/codex.svg" alt="Codex" className={className} />
+ );
+}
+
+/**
+ * Returns true when we have an inline logo for the given vendor.
+ * Callers (table rows, session cards, trace-detail pills) use this
+ * to decide whether to render `CodingAgentVendorIcon` or the generic
+ * `Bot` fallback. Centralising the check here means new vendors only
+ * have to land their SVG + the switch case below; the conditionals in
+ * the consumer files don't need to be updated each time.
+ */
+export function hasCodingAgentVendorIcon(
+ vendor: string | null | undefined,
+): boolean {
+ if (!vendor) return false;
+ switch (vendor.toLowerCase()) {
+ case "cursor":
+ case "claude-code":
+ case "codex":
+ return true;
+ default:
+ return false;
+ }
+}
+
+/**
+ * Pretty display label for a coding-agent vendor id. The vendor ids
+ * we ship internally are kebab-case (`claude-code`) or lowercase
+ * (`cursor`, `codex`); call-sites that show a human-facing string
+ * should funnel through this helper so the spelling stays consistent
+ * across the hub table, the agent detail header, trace pills, and the
+ * onboarding tabs. New vendors only need a row here once their icon
+ * lands.
+ */
+const CODING_AGENT_VENDOR_LABELS: Record<string, string> = {
+ cursor: "Cursor",
+ "claude-code": "Claude Code",
+ codex: "Codex",
+ windsurf: "Windsurf",
+};
+
+export function codingAgentVendorLabel(
+ vendor: string | null | undefined,
+): string {
+ if (!vendor) return "Unknown";
+ return CODING_AGENT_VENDOR_LABELS[vendor.toLowerCase()] || vendor;
+}
+
+/**
+ * Single dispatch point for "render the right logo for this coding-agent
+ * vendor". Falls back to null when we don't have an icon yet (so the
+ * caller can keep the text-only label). Add new vendors here when new
+ * logos land. Keep `hasCodingAgentVendorIcon` in sync with the switch.
+ */
+export function CodingAgentVendorIcon({
+ vendor,
+ className,
+}: {
+ vendor: string | null | undefined;
+ className?: string;
+}) {
+ if (!vendor) return null;
+ switch (vendor.toLowerCase()) {
+ case "cursor":
+ return <CursorIcon className={className} />;
+ case "claude-code":
+ return <ClaudeCodeIcon className={className} />;
+ case "codex":
+ return <CodexIcon className={className} />;
+ default:
+ return null;
+ }
+}
diff --git a/src/client/src/components/svg/mac.tsx b/src/client/src/components/svg/mac.tsx
index 0366432a..4294f1ca 100644
--- a/src/client/src/components/svg/mac.tsx
+++ b/src/client/src/components/svg/mac.tsx
@@ -1,7 +1,17 @@
export default function MacSvg({ className = "" }: { className?: string }) {
return (
- <svg role="img" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" height="16" width="16" className={`${className} external-icon-svg`}>
- <path d="M10.306266666666666 2.6608c0.2964 -0.34159999999999996 0.5223333333333333 -0.7383333333333333 0.6649333333333333 -1.1675333333333333 0.1426 -0.42913333333333337 0.19906666666666664 -0.8822666666666665 0.16606666666666664 -1.3332666666666666 -0.9098666666666666 0.07346666666666667 -1.7544666666666666 0.5014 -2.3518666666666665 1.1916 -0.28606666666666664 0.3308 -0.5027999999999999 0.7156666666666666 -0.6375333333333333 1.1317333333333333 -0.13466666666666666 0.41606666666666664 -0.18446666666666667 0.855 -0.14639999999999997 1.2906666666666666 0.4438 0.003666666666666666 0.8825333333333334 -0.0948 1.2822 -0.28779999999999994 0.39966666666666667 -0.19306666666666666 0.7495333333333334 -0.4754666666666666 1.0226 -0.8253999999999999Zm1.9755333333333331 5.832533333333332c0.005266666666666667 -0.6007333333333333 0.16346666666666665 -1.1901333333333333 0.4598 -1.7127333333333334 0.2962666666666667 -0.5226 0.7207333333333332 -0.9610666666666666 1.2335333333333334 -1.2740666666666667 -0.3236 -0.46626666666666666 -0.7514 -0.8507333333333333 -1.2494666666666667 -1.1228666666666665 -0.498 -0.27213333333333334 -1.0526 -0.4245333333333333 -1.6198 -0.4450666666666666 -1.2229333333333332 -0.12539999999999998 -2.3518 0.7134 -3.002533333333333 0.7134 -0.6506666666666666 0 -1.5678666666666665 -0.6976666666666667 -2.5869999999999997 -0.6819999999999999 -0.6662666666666666 0.021933333333333332 -1.3154666666666666 0.21619999999999998 -1.8842666666666665 0.5638 -0.5688 0.34759999999999996 -1.0377999999999998 0.8366666666666666 -1.3612666666666666 1.4196 -1.3797333333333333 2.3988666666666667 -0.3528 5.9658 1.0269333333333333 7.902200000000001 0.6272 0.9485333333333333 1.4111333333333331 2.022533333333333 2.445933333333333 1.9833333333333334 1.0348 -0.0392 1.3719333333333332 -0.6427999999999999 2.5713333333333335 -0.6427999999999999 1.1994666666666665 0 1.5679333333333334 0.6427999999999999 2.5870666666666664 0.6193333333333333 1.0191333333333332 -0.02353333333333333 1.7403333333333333 -0.9721333333333333 2.3988666666666667 -1.9207333333333332 0.46646666666666664 -0.6886666666666665 0.8309333333333333 -1.4411999999999998 1.0818666666666665 -2.2342 -0.6212666666666666 -0.265 -1.1514 -0.7061333333333333 -1.5248 -1.269 -0.37333333333333335 -0.5628666666666666 -0.5736666666666667 -1.2227333333333332 -0.5761999999999999 -1.8982Z" fill="currentColor" strokeWidth="0.6667"></path>
+ <svg
+ role="img"
+ viewBox="0 0 50 50"
+ xmlns="http://www.w3.org/2000/svg"
+ height="24"
+ width="24"
+ className={`${className} external-icon-svg`}
+ >
+ <path
+ d="M 44.527344 34.75 C 43.449219 37.144531 42.929688 38.214844 41.542969 40.328125 C 39.601563 43.28125 36.863281 46.96875 33.480469 46.992188 C 30.46875 47.019531 29.691406 45.027344 25.601563 45.0625 C 21.515625 45.082031 20.664063 47.03125 17.648438 47 C 14.261719 46.96875 11.671875 43.648438 9.730469 40.699219 C 4.300781 32.429688 3.726563 22.734375 7.082031 17.578125 C 9.457031 13.921875 13.210938 11.773438 16.738281 11.773438 C 20.332031 11.773438 22.589844 13.746094 25.558594 13.746094 C 28.441406 13.746094 30.195313 11.769531 34.351563 11.769531 C 37.492188 11.769531 40.8125 13.480469 43.1875 16.433594 C 35.421875 20.691406 36.683594 31.78125 44.527344 34.75 Z M 31.195313 8.46875 C 32.707031 6.527344 33.855469 3.789063 33.4375 1 C 30.972656 1.167969 28.089844 2.742188 26.40625 4.78125 C 24.878906 6.640625 23.613281 9.398438 24.105469 12.066406 C 26.796875 12.152344 29.582031 10.546875 31.195313 8.46875 Z"
+ fill="currentColor"
+ />
</svg>
);
-}
\ No newline at end of file
+}
diff --git a/src/client/src/components/svg/windows.tsx b/src/client/src/components/svg/windows.tsx
index eca32134..a41318f6 100644
--- a/src/client/src/components/svg/windows.tsx
+++ b/src/client/src/components/svg/windows.tsx
@@ -1,7 +1,17 @@
export default function WindowsSvg({ className = "" }: { className?: string }) {
return (
- <svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" height="24" width="24" className={`${className} external-icon-svg`}>
- <path d="M3 3h8.5v8.5H3V3zm9.5 0H21v8.5h-8.5V3zM3 12.5h8.5V21H3v-8.5zm9.5 0H21V21h-8.5v-8.5z" fill="currentColor" />
+ <svg
+ role="img"
+ viewBox="0 0 48 48"
+ xmlns="http://www.w3.org/2000/svg"
+ height="24"
+ width="24"
+ className={`${className} external-icon-svg`}
+ >
+ <path
+ d="M20 25.026L5.011 25 5.012 37.744 20 39.818zM22 25.03L22 40.095 42.995 43 43 25.066zM20 8.256L5 10.38 5.014 23 20 23zM22 7.973L22 23 42.995 23 42.995 5z"
+ fill="currentColor"
+ />
</svg>
);
-}
\ No newline at end of file
+}
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index 559aef65..999b29c5 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -1,5 +1,7 @@
export const DATABASE_CONFIG_NOT_FOUND = "No database config present!";
export const UNAUTHORIZED_USER = "Unauthorized user!";
+export const FORBIDDEN_ACTION = "You do not have permission to perform this action.";
+export const NO_ORGANISATION_SELECTED = "No active organisation. Switch organisations to continue.";
export const MALFORMED_INPUTS = "Malformed input! Please check the docs";
export const OPERATION_FAILED = "Operation failed!";
@@ -487,6 +489,12 @@ export const AGENTS_FILTER_PROVIDER = "Provider";
export const AGENTS_FILTER_STATUS = "Status";
export const AGENTS_FILTER_STATUS_DISCOVERED = "Discovered";
export const AGENTS_FILTER_STATUS_INSTRUMENTED = "Instrumented";
+export const AGENTS_FILTER_CONTROLLER_HEALTH = "Health";
+export const AGENTS_FILTER_CONTROLLER_ACTIVE = "Active";
+export const AGENTS_FILTER_CONTROLLER_HEALTHY = "Healthy";
+export const AGENTS_FILTER_CONTROLLER_DEGRADED = "Degraded";
+export const AGENTS_FILTER_CONTROLLER_STALE = "Stale";
+export const AGENTS_FILTER_CONTROLLER_ERROR = "Error";
export const AGENTS_CLEAR_FILTERS = "Clear Filters";
export const AGENTS_APPLY_FILTERS = "Apply Filters";
export const AGENTS_SYSTEM_KUBERNETES = "Kubernetes";
@@ -495,9 +503,23 @@ export const AGENTS_SYSTEM_LINUX = "Linux";
export const AGENTS_STAT_CONTROLLERS = "Active Controllers";
export const AGENTS_STAT_DISCOVERED_SERVICES = "Discovered Agents";
export const AGENTS_STAT_INSTRUMENTED_SERVICES = "Instrumented Agents";
-export const AGENTS_TAB_SERVICES = "Agents";
+export const AGENTS_STAT_CODING_VENDORS = "Total Coding Agents";
+export const AGENTS_STAT_CODING_COST = "Total Cost";
+export const AGENTS_STAT_CODING_USERS = "Total Users";
+export const AGENTS_TAB_SERVICES = "Applications";
export const AGENTS_TAB_CONTROLLERS = "Controllers";
+export const AGENTS_TAB_CODING = "Coding Agents";
export const AGENTS_ADD_CONTROLLER = "Add Controller";
+export const AGENTS_ADD_CODING_AGENT = "Add Coding Agent";
+export const AGENTS_NO_CODING_AGENTS_DESCRIPTION = "Pick a tool to see the install snippet. The OpenLit CLI hooks into the agent and ships every session, tool call, and LLM turn to this stack — no SDK or code changes required.";
+
+// Trace-detail content-capture banner. Surfaces a one-liner the user
+// can run when prompts / responses are missing from a coding-agent
+// trace (i.e. the CLI is in metadata_only or minimal mode). Tracks the
+// OPENLIT_CODING_CONTENT_CAPTURE flag used by the CLI.
+export const CODING_AGENT_CONTENT_CAPTURE_NOTE_TITLE = "Content capture is off";
+export const CODING_AGENT_CONTENT_CAPTURE_NOTE_COMMAND =
+ "openlit configure --content-capture full";
// Agents - No Controller
export const AGENTS_NO_CONTROLLERS_TITLE = "No controllers detected";
@@ -527,6 +549,50 @@ export const AGENTS_PODS_ACK_PROGRESS = (ack: number, total: number) =>
export const AGENTS_COLUMN_SERVICE = "Name";
export const AGENTS_COLUMN_SYSTEM = "System";
export const AGENTS_COLUMN_PROVIDERS = "Providers";
+// Coding-agent stat / column labels intentionally omit a window
+// suffix (no "24h"). The underlying data is always evaluated
+// against the global filter picker's selected time range — fixed-24h
+// language would be misleading once the user picks 7D / 1M / CUSTOM.
+export const AGENTS_CODING_USERS_WINDOW_LABEL = "Active users";
+export const AGENTS_CODING_COST_WINDOW_LABEL = "Cost (USD)";
+export const AGENTS_CODING_COLUMN_VENDOR = "Vendor";
+export const AGENTS_CODING_COLUMN_SESSIONS = "Sessions";
+export const AGENTS_CODING_COLUMN_USERS = "Users";
+export const AGENTS_CODING_COLUMN_COST = "Cost";
+export const AGENTS_CODING_COLUMN_LINES = "Lines";
+export const AGENTS_CODING_COLUMN_ACCEPTANCE = "Acceptance";
+export const AGENTS_CODING_COLUMN_COMMITS = "Commits";
+export const AGENTS_CODING_COLUMN_PRS = "PRs";
+export const AGENTS_CODING_EMPTY_TITLE = "No coding agents yet";
+export const AGENTS_CODING_EMPTY_BODY =
+ "Install the openlit CLI on a teammate's machine and run a Claude Code, Cursor, or Codex session. The first hook event will surface the agent here within a minute.";
+export const AGENTS_CODING_TAB_SESSIONS = "Sessions";
+export const AGENTS_CODING_SESSIONS_EMPTY = "No sessions in the selected time range.";
+export const AGENTS_CODING_SESSIONS_SESSION = "Session";
+export const AGENTS_CODING_SESSIONS_USER = "User";
+export const AGENTS_CODING_SESSIONS_STARTED = "Started";
+export const AGENTS_CODING_SESSIONS_DURATION = "Duration";
+export const AGENTS_CODING_SESSIONS_TOOLS = "Tools";
+export const AGENTS_CODING_SESSIONS_COST = "Cost";
+export const AGENTS_CODING_SESSIONS_CODE = "Lines (+/−)";
+export const AGENTS_CODING_SESSIONS_ACCEPTANCE = "Accept %";
+export const AGENTS_CODING_SESSIONS_COMMITS = "Commits";
+export const AGENTS_CODING_SESSIONS_PRS = "PRs";
+export const AGENTS_CODING_SESSIONS_OUTCOME = "Outcome";
+export const AGENTS_CODING_SESSIONS_CLASSIFICATION = "Classification";
+export const AGENTS_CODING_SESSIONS_LABEL = "Coding sessions";
+export const AGENTS_CODING_SESSIONS_SHORT_LABEL = "Sessions";
+export const AGENTS_CODING_SESSIONS_SUMMARY = "Per-session timeline of coding-agent runs (Cursor, Claude Code, Codex).";
+export const AGENTS_CODING_USERS_LABEL = "Coding users";
+export const AGENTS_CODING_USERS_SHORT_LABEL = "Users";
+export const AGENTS_CODING_USERS_SUMMARY = "Per-user roll-up of coding-agent activity.";
+export const AGENTS_CODING_USERS_LINES = "Lines added";
+export const AGENTS_CODING_USERS_ACCEPTANCE = "Accept %";
+export const AGENTS_CODING_USERS_COMMITS = "Commits";
+export const AGENTS_CODING_USERS_PRS = "PRs";
+export const AGENTS_CODING_DASHBOARD_NOT_SEEDED =
+ "Dashboard not yet available. Restart the openlit container to run the latest seed migrations.";
+export const AGENTS_CODING_DASHBOARD_OPEN = "Open full dashboard";
export const AGENTS_COLUMN_LAST_SEEN = "Last Seen";
export const AGENTS_COLUMN_LLM_OBSERVABILITY = "LLM Observability";
export const AGENTS_COLUMN_AGENT_OBSERVABILITY = "Agent Observability";
diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsx
index 046388dd..7cc2a1a2 100644
--- a/src/client/src/constants/sidebar.tsx
+++ b/src/client/src/constants/sidebar.tsx
@@ -8,6 +8,7 @@ import {
Activity,
Home,
Key,
+ Bot,
LayoutDashboard,
MonitorCog,
MonitorPlay,
@@ -47,12 +48,12 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [
link: "/telemetry",
type: "action",
},
- // {
- // icon: <Radar className={ICON_CLASSES} />,
- // text: "Agents",
- // link: "/agents",
- // type: "action",
- // },
+ {
+ icon: <Bot className={ICON_CLASSES} />,
+ text: "Agents",
+ link: "/agents",
+ type: "action",
+ },
{
icon: <OpenTelemetrySvg className={ICON_CLASSES} />,
text: "Fleet Hub",
diff --git a/src/client/src/helpers/client/observability.ts b/src/client/src/helpers/client/observability.ts
index 1a6844d6..83e6634d 100644
--- a/src/client/src/helpers/client/observability.ts
+++ b/src/client/src/helpers/client/observability.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_SORTING } from "@/store/filter";
import { FilterConfig } from "@/types/store/filter";
export type UpdateFilterFn = (
@@ -8,6 +9,14 @@ export type UpdateFilterFn = (
export type UpdateConfigFn = (config?: FilterConfig) => void;
+// E3: when the active observability signal/tab changes (traces ↔
+// metrics ↔ logs ↔ coding-agent sessions), the previous tab's sort
+// key (e.g. "Tokens") is almost never a valid column on the new tab.
+// Leaving it set leaks ORDER BY clauses across signals and causes
+// the new tab to fall back to an inappropriate default ordering at
+// best — or a 500 at worst when the SQL column doesn't exist.
+// Reset sort and pagination alongside the existing groupBy/config
+// reset so each tab starts from a clean slate.
export function prepareObservabilitySignalChange(
updateConfig: UpdateConfigFn,
updateFilter: UpdateFilterFn
@@ -15,4 +24,6 @@ export function prepareObservabilitySignalChange(
updateConfig(undefined);
updateFilter("groupBy", null);
updateFilter("groupValue", null);
+ updateFilter("sorting", DEFAULT_SORTING);
+ updateFilter("offset", 0);
}
diff --git a/src/client/src/helpers/client/trace.ts b/src/client/src/helpers/client/trace.ts
index 956f3fdc..27d01654 100644
--- a/src/client/src/helpers/client/trace.ts
+++ b/src/client/src/helpers/client/trace.ts
@@ -312,14 +312,39 @@ export const KNOWN_SPAN_ATTR_KEYS = new Set<string>(
)
);
+/**
+ * Prefix used for the synthetic session-root node minted when a
+ * coding-agent session has no real `coding_agent.session` span (see
+ * `buildCodingSessionHierarchy` in `lib/platform/request`). Such a node
+ * has no row in `otel_traces`, so any code that fetches a span / trace
+ * by this id (span detail, AI analysis, hierarchy) MUST treat it as a
+ * non-selectable grouping node rather than a real span.
+ */
+export const SYNTHETIC_SPAN_ID_PREFIX = "synthetic-";
+
+/** True when `spanId` is a synthetic grouping node (no backing DB row). */
+export function isSyntheticSpanId(spanId?: string | null): boolean {
+ return (
+ typeof spanId === "string" && spanId.startsWith(SYNTHETIC_SPAN_ID_PREFIX)
+ );
+}
+
/**
* Get formatted duration string for a hierarchy span (e.g. "1.20s").
+ *
+ * `getNormalizedTraceAttribute` returns `requestDuration`'s (absent)
+ * defaultValue — `undefined` — for a falsy `Duration` (the numeric `0`
+ * carried by the synthetic session root and by point-in-time coding
+ * spans). `parseFloat(undefined)` is `NaN`, which used to render as
+ * the literal "NaNs" on every zero-duration node. Guard the non-finite
+ * case so those nodes read a truthful "0.00s" instead.
*/
export function getSpanDurationDisplay(span: TraceHeirarchySpan): string {
- const durationStr = parseFloat(
+ const parsed = parseFloat(
getNormalizedTraceAttribute("requestDuration", span.Duration) as string
- ).toFixed(2);
- return `${durationStr}${TraceMapping.requestDuration.valueSuffix}`;
+ );
+ const seconds = Number.isFinite(parsed) ? parsed : 0;
+ return `${seconds.toFixed(2)}${TraceMapping.requestDuration.valueSuffix}`;
}
/**
diff --git a/src/client/src/helpers/server/platform.ts b/src/client/src/helpers/server/platform.ts
index fbba221e..f22fbbdb 100644
--- a/src/client/src/helpers/server/platform.ts
+++ b/src/client/src/helpers/server/platform.ts
@@ -197,16 +197,22 @@ export const getFilterWhereCondition = (
}
if (filter.selectedConfig.providers?.length) {
+ // Mirror of the provider DISTINCT fold in
+ // lib/platform/request/index.ts: the dropdown shows
+ // values from gen_ai.system + db.system +
+ // coding_agent.client, so the WHERE check must
+ // match across the same three attributes — otherwise
+ // unticking e.g. "cursor" would have no effect on
+ // the rendered rows.
+ const providerList = filter.selectedConfig.providers
+ .map((provider) => `'${provider}'`)
+ .join(", ");
whereArray.push(
`(SpanAttributes['${getTraceMappingKeyFullPath(
"system"
- )}'] IN (${filter.selectedConfig.providers
- .map((provider) => `'${provider}'`)
- .join(", ")}) OR SpanAttributes['${getTraceMappingKeyFullPath(
+ )}'] IN (${providerList}) OR SpanAttributes['${getTraceMappingKeyFullPath(
"provider"
- )}'] IN (${filter.selectedConfig.providers
- .map((provider) => `'${provider}'`)
- .join(", ")}))`
+ )}'] IN (${providerList}) OR SpanAttributes['coding_agent.client'] IN (${providerList}))`
);
}
diff --git a/src/client/src/lib/platform/agents/index.ts b/src/client/src/lib/platform/agents/index.ts
index b49f676b..36ebec2e 100644
--- a/src/client/src/lib/platform/agents/index.ts
+++ b/src/client/src/lib/platform/agents/index.ts
@@ -25,6 +25,7 @@ import { invalidate, POLICY_DETAIL, POLICY_LIST, swr } from "./cache";
import { agentsLogger } from "./logger";
import { AGENTS_SUMMARY_TABLE } from "./table-details";
import { escapeClickHouseString } from "@/lib/clickhouse-escape";
+import { recomputeCodingAgentsForWindow } from "./materialize";
const escape = escapeClickHouseString;
@@ -74,6 +75,19 @@ function rowToAgent(row: Record<string, unknown>): UnifiedAgent {
pods_total: Number(row.pods_total || 0),
pods_pending: Number(row.pods_pending || 0),
pods_acknowledged: Number(row.pods_acknowledged || 0),
+ coding_agent_vendor:
+ (String(row.coding_agent_vendor || "") || undefined) as UnifiedAgent["coding_agent_vendor"],
+ coding_session_count_24h: Number(row.coding_session_count_24h || 0),
+ coding_cost_usd_24h: Number(row.coding_cost_usd_24h || 0),
+ coding_active_users_24h: Number(row.coding_active_users_24h || 0),
+ coding_lines_added_24h: Number(row.coding_lines_added_24h || 0),
+ coding_lines_removed_24h: Number(row.coding_lines_removed_24h || 0),
+ coding_lines_accepted_24h: Number(row.coding_lines_accepted_24h || 0),
+ coding_lines_rejected_24h: Number(row.coding_lines_rejected_24h || 0),
+ coding_edit_accept_24h: Number(row.coding_edit_accept_24h || 0),
+ coding_edit_reject_24h: Number(row.coding_edit_reject_24h || 0),
+ coding_commit_count_24h: Number(row.coding_commit_count_24h || 0),
+ coding_pr_count_24h: Number(row.coding_pr_count_24h || 0),
};
}
@@ -234,7 +248,22 @@ const SELECT_COLUMNS = `
s.last_materialized_at AS last_materialized_at,
coalesce(pod_set.pods_total, 0) AS pods_total,
coalesce(pod_actions.pods_pending, 0) AS pods_pending,
- coalesce(pod_actions.pods_acknowledged, 0) AS pods_acknowledged
+ coalesce(pod_actions.pods_acknowledged, 0) AS pods_acknowledged,
+ -- Coding-agent rollups. Only populated when source = 'coding'; always
+ -- 0/empty for other rows. Returned unconditionally so the front-end
+ -- can render uniformly without an if-coding branch on every cell.
+ s.coding_agent_vendor AS coding_agent_vendor,
+ s.coding_session_count_24h AS coding_session_count_24h,
+ s.coding_cost_usd_24h AS coding_cost_usd_24h,
+ s.coding_active_users_24h AS coding_active_users_24h,
+ s.coding_lines_added_24h AS coding_lines_added_24h,
+ s.coding_lines_removed_24h AS coding_lines_removed_24h,
+ s.coding_lines_accepted_24h AS coding_lines_accepted_24h,
+ s.coding_lines_rejected_24h AS coding_lines_rejected_24h,
+ s.coding_edit_accept_24h AS coding_edit_accept_24h,
+ s.coding_edit_reject_24h AS coding_edit_reject_24h,
+ s.coding_commit_count_24h AS coding_commit_count_24h,
+ s.coding_pr_count_24h AS coding_pr_count_24h
`;
/**
@@ -345,6 +374,25 @@ async function loadAgents(params: ListAgentsParams): Promise<ListAgentsResult> {
`(s.source != 'sdk' OR s.last_seen >= now() - INTERVAL 10 MINUTE)`
);
+ // Same problem, different source: when a coding-agent vendor stops
+ // emitting (e.g. the user disables their Claude Code plugin), the
+ // materializer doesn't tombstone the row because
+ // `discoverCodingAgents` only returns vendors with current data —
+ // no INSERT means no new `last_materialized_at`, so the previous
+ // row (with its non-zero `coding_session_count_24h` /
+ // `coding_cost_usd_24h`) lingers until the 90d TTL. The hub then
+ // shows e.g. "Claude Code · 6 sessions · 1 user" with clickthrough
+ // landing on an empty detail page because otel_traces has no
+ // matching spans. Gating on `last_materialized_at` (not
+ // `last_seen` — last_seen is the timestamp of the last hosted span
+ // at the time of materialization, NOT when we last refreshed)
+ // hides coding rows whose materializer skipped them this round.
+ // 10 minutes matches the SDK guard and gives the cron-driven
+ // materializer plenty of headroom.
+ where.push(
+ `(s.source != 'coding' OR s.last_materialized_at >= now() - INTERVAL 10 MINUTE)`
+ );
+
if (filters.source?.length) {
where.push(`s.source IN (${escapeList(filters.source)})`);
}
@@ -405,6 +453,66 @@ async function loadAgents(params: ListAgentsParams): Promise<ListAgentsResult> {
nextCursor = { last_seen: last.last_seen, agent_key: last.agent_key };
rows.length = limit;
}
+
+ // Live overlay for the Coding Agents hub card. The summary table
+ // stores `coding_session_count_24h` / `_active_users_24h` /
+ // `_cost_usd_24h` — values the materializer bakes in once a tick
+ // for the trailing 24h. That doesn't agree with what the per-tab
+ // (Sessions / Users / Dashboard) views show when the user picks a
+ // different range in the top-right time filter.
+ //
+ // To keep all four views answering the same question for the same
+ // window, we recompute coding rows live whenever this list is
+ // scoped to coding sources AND the caller passed a non-default
+ // time window. We only do this when the caller is *exclusively*
+ // asking for coding (the Coding Agents tab passes
+ // `?source=coding`), so the Apps / Controllers paths skip the
+ // extra round-trip.
+ if (
+ filters.source &&
+ filters.source.length > 0 &&
+ filters.source.every((s) => s === "coding") &&
+ (params.timeStart || params.timeEnd)
+ ) {
+ try {
+ const liveRows = await recomputeCodingAgentsForWindow(
+ {
+ timeStart: params.timeStart,
+ timeEnd: params.timeEnd,
+ },
+ params.dbConfigId
+ );
+ const overlay = new Map<string, (typeof liveRows)[number]>();
+ for (const r of liveRows) overlay.set(r.agent_key, r);
+ for (let i = 0; i < rows.length; i++) {
+ const liveRow = overlay.get(rows[i].agent_key);
+ if (!liveRow) continue;
+ rows[i] = {
+ ...rows[i],
+ coding_session_count_24h: liveRow.coding_session_count_24h,
+ coding_active_users_24h: liveRow.coding_active_users_24h,
+ coding_cost_usd_24h: liveRow.coding_cost_usd_24h,
+ coding_lines_added_24h: liveRow.coding_lines_added_24h,
+ coding_lines_removed_24h: liveRow.coding_lines_removed_24h,
+ coding_lines_accepted_24h: liveRow.coding_lines_accepted_24h,
+ coding_lines_rejected_24h: liveRow.coding_lines_rejected_24h,
+ coding_edit_accept_24h: liveRow.coding_edit_accept_24h,
+ coding_edit_reject_24h: liveRow.coding_edit_reject_24h,
+ coding_commit_count_24h: liveRow.coding_commit_count_24h,
+ coding_pr_count_24h: liveRow.coding_pr_count_24h,
+ // `last_seen` from the live recompute reflects the
+ // most recent span inside the user's window; reuse
+ // it so the "Last seen" column doesn't show a
+ // timestamp from outside the filter.
+ last_seen: liveRow.last_seen || rows[i].last_seen,
+ };
+ }
+ } catch (err) {
+ agentsLogger.error("list_agents_coding_overlay_failed", {
+ err: String(err),
+ });
+ }
+ }
return { data: rows, nextCursor };
}
diff --git a/src/client/src/lib/platform/agents/materialize.ts b/src/client/src/lib/platform/agents/materialize.ts
index 9324d728..fd6004fa 100644
--- a/src/client/src/lib/platform/agents/materialize.ts
+++ b/src/client/src/lib/platform/agents/materialize.ts
@@ -13,7 +13,7 @@ import {
CONTROLLER_DESIRED_STATES_V2_TABLE,
CONTROLLER_SERVICES_TABLE,
} from "@/lib/platform/controller/table-details";
-import type { AgentSource } from "@/types/agents";
+import type { AgentSource, CodingAgentVendor } from "@/types/agents";
import { computeAgentKey, invalidateAgent } from "./index";
import { invalidatePrefix } from "./cache";
import { agentsLogger } from "./logger";
@@ -73,6 +73,23 @@ interface DiscoveredAgent {
// table render provider logos for controller-discovered workloads
// before any GenAI trace has arrived. Empty for SDK-only rows.
controller_llm_providers: string[];
+ // Coding-agent specific rollups, populated by discoverCodingAgents()
+ // only on rows where source === 'coding'. All zero/empty for other rows.
+ coding_agent_vendor?: CodingAgentVendor;
+ coding_session_count_24h?: number;
+ coding_cost_usd_24h?: number;
+ coding_active_users_24h?: number;
+ // Per-vendor code-change 24h rollups. Same `greatest(rollup,
+ // per-edit-sum)` pattern as queries.ts so the hub agrees with
+ // the per-session Sessions list.
+ coding_lines_added_24h?: number;
+ coding_lines_removed_24h?: number;
+ coding_lines_accepted_24h?: number;
+ coding_lines_rejected_24h?: number;
+ coding_edit_accept_24h?: number;
+ coding_edit_reject_24h?: number;
+ coding_commit_count_24h?: number;
+ coding_pr_count_24h?: number;
}
const SDK_DISCOVERY_LOOKBACK_MINUTES = 30;
@@ -90,8 +107,56 @@ async function discoverAgents(
// workload_key comes from ResourceAttributes['service.workload.key'] which
// the controller injects via OTEL_RESOURCE_ATTRIBUTES on managed processes;
// SDK-only services emit it empty.
+ // Coding-agent CLI spans are deliberately kept out of SDK discovery.
+ // Three independent barriers exist; the first one a future change
+ // breaks, the others catch it. They are listed in order of how
+ // structurally robust they are:
+ //
+ // 1. Distro marker (PRIMARY). The CLI stamps
+ // telemetry.distro.name = 'openlit-cli' on every span as a
+ // resource attribute (see cli/internal/otlp/exporter.go). This
+ // identifies the entire emitting distribution -- there is
+ // nothing per-event about it; if even one span has it, every
+ // span from that process has it. A service_name that ever
+ // sets this distro inside the window is excluded entirely
+ // from SDK discovery via the cli_services anti-join below.
+ // 2. coding_agent.session.id per-span filter (LEGACY backstop).
+ // Kept so historical data emitted before the distro marker
+ // shipped doesn't suddenly start showing up here. Remove
+ // this once the retention window has rolled past the distro
+ // cutover.
+ // 3. The ReplacingMergeTree dedup on agent_key -- anything that
+ // slipped past both filters above would still end up
+ // fighting with the coding row, and we'd see the agent flip
+ // layout on every materialize tick. The user-visible symptom
+ // is "the SDK Overview tabs render on my Cursor agent"; the
+ // original bug was that only barrier #2 existed and any race
+ // or regression in the per-span stamp leaked a phantom SDK
+ // row. The structural fix is #1.
const sdkQuery = `
- WITH sdk_seen AS (
+ WITH
+ -- Any service_name that emitted a CLI span (any distro =
+ -- 'openlit-cli') inside the lookback window. This is the
+ -- positive identifier that *this process* is a coding-agent
+ -- hook, not a regular openlit-go SDK service. We exclude
+ -- the entire (service, env, cluster) tuple even if some
+ -- spans within it happen to lack coding_agent.session.id
+ -- (e.g. a CLI startup span emitted before the first hook
+ -- event, or any future leak).
+ cli_services AS (
+ SELECT DISTINCT
+ ServiceName AS service_name,
+ if(ResourceAttributes['deployment.environment'] != '', ResourceAttributes['deployment.environment'], 'default') AS environment,
+ if(ResourceAttributes['k8s.cluster.name'] != '', ResourceAttributes['k8s.cluster.name'], 'default') AS cluster_id
+ FROM ${OTEL_TRACES_TABLE_NAME}
+ WHERE Timestamp >= now() - INTERVAL ${SDK_DISCOVERY_LOOKBACK_MINUTES} MINUTE
+ AND (
+ ResourceAttributes['telemetry.distro.name'] = 'openlit-cli'
+ OR ResourceAttributes['coding_agent.session.id'] != ''
+ OR SpanAttributes['coding_agent.session.id'] != ''
+ )
+ ),
+ sdk_seen AS (
SELECT
ServiceName AS service_name,
if(ResourceAttributes['deployment.environment'] != '', ResourceAttributes['deployment.environment'], 'default') AS environment,
@@ -112,6 +177,17 @@ async function discoverAgents(
-- spans get discovered as a phantom SDK row that the workload_key dedup
-- cannot merge with the controller row (their workload_key is empty).
AND ResourceAttributes['telemetry.distro.name'] != 'opentelemetry-ebpf-instrumentation'
+ -- Barrier #1: positive distro-name exclusion.
+ AND ResourceAttributes['telemetry.distro.name'] != 'openlit-cli'
+ -- Barrier #2: legacy per-span fallback for data emitted before
+ -- the distro marker shipped. Remove after the retention window
+ -- has rolled past.
+ AND ResourceAttributes['coding_agent.session.id'] = ''
+ AND SpanAttributes['coding_agent.session.id'] = ''
+ -- Barrier #1 reinforced: even if individual spans don't have
+ -- the distro marker, the service_name as a whole must not be
+ -- one that ever emitted a CLI span in this window.
+ AND (ServiceName, if(ResourceAttributes['deployment.environment'] != '', ResourceAttributes['deployment.environment'], 'default'), if(ResourceAttributes['k8s.cluster.name'] != '', ResourceAttributes['k8s.cluster.name'], 'default')) NOT IN (SELECT service_name, environment, cluster_id FROM cli_services)
GROUP BY service_name, environment, cluster_id
)
SELECT
@@ -345,6 +421,337 @@ async function discoverAgents(
return Array.from(merged.values());
}
+/**
+ * Coding-agent discovery — separate pass so it stays decoupled from the
+ * SDK/controller path. We group raw spans by `coding_agent.client` (mirror
+ * of `gen_ai.agent.name`) and emit one summary row per vendor under the
+ * synthetic cluster id `coding`. Per-user / per-session detail lives in
+ * the dedicated coding-agent dashboards.
+ *
+ * Why one row per vendor (not per session, repo, or user): the /agents
+ * page is a fleet view. A workspace running 50 Claude Code sessions a
+ * day shouldn't crowd the page out with 50 rows; it should show one
+ * "Claude Code" row whose detail page drills into sessions/users/cost.
+ */
+/**
+ * Optional window override. When omitted (the materializer's
+ * canonical call site) the query falls back to a fixed last-24h
+ * window — what the agents-hub card has always shown.
+ *
+ * When the caller passes a window (the live recompute path used by
+ * `listAgents` when the user picks a non-default top-right time
+ * filter), we honour those bounds instead. This is what makes the
+ * hub's Sessions / Users / Cost numbers stay in sync with the
+ * Sessions / Users / Dashboard tabs once the user changes the time
+ * range.
+ */
+export interface CodingAgentDiscoveryWindow {
+ timeStart?: string;
+ timeEnd?: string;
+}
+
+function escapeTimestamp(value: string): string {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
+function buildCodingWindowClause(
+ window: CodingAgentDiscoveryWindow | undefined
+): string {
+ const start = window?.timeStart;
+ const end = window?.timeEnd;
+ if (!start && !end) {
+ return "Timestamp >= now() - INTERVAL 24 HOUR";
+ }
+ const clauses: string[] = [];
+ if (start) {
+ clauses.push(
+ `Timestamp >= parseDateTimeBestEffort('${escapeTimestamp(start)}')`
+ );
+ }
+ if (end) {
+ clauses.push(
+ `Timestamp <= parseDateTimeBestEffort('${escapeTimestamp(end)}')`
+ );
+ }
+ if (clauses.length === 0) {
+ // Caller passed an empty window — fall back to the 24h default
+ // rather than dropping the time predicate entirely (which would
+ // scan the whole table and silently inflate the rollup).
+ return "Timestamp >= now() - INTERVAL 24 HOUR";
+ }
+ return clauses.join(" AND ");
+}
+
+/**
+ * Live recompute of the hub-card Coding Agents rollup over an
+ * arbitrary time window. Used by `listAgents` when the user's
+ * top-right time filter is something other than the materializer's
+ * fixed 24h. We deliberately call into the same query path as the
+ * materializer (one row per vendor, `greatest(session.cost_usd,
+ * sum(turn.cost))` per chat) so the hub numbers can never disagree
+ * with the Sessions / Users / Dashboard tabs for the same window.
+ */
+export async function recomputeCodingAgentsForWindow(
+ window: CodingAgentDiscoveryWindow,
+ dbConfigId?: string
+): Promise<DiscoveredAgent[]> {
+ return discoverCodingAgents(dbConfigId, window);
+}
+
+async function discoverCodingAgents(
+ dbConfigId?: string,
+ window?: CodingAgentDiscoveryWindow
+): Promise<DiscoveredAgent[]> {
+ // Cost rollup notes:
+ // * `coding_agent.session.cost_usd` is only stamped on the
+ // session-root span at sessionEnd. Active / still-running
+ // sessions don't have it yet, so summing on it alone makes the
+ // hub show $0.00 even when LLM-turn spans show real cost.
+ // * `gen_ai.usage.cost` lives on per-turn LLM spans (Cursor
+ // estimates from text length × static pricing; Claude Code
+ // uses authoritative provider numbers).
+ //
+ // We sum both per session and `greatest()` them — exactly how the
+ // per-session list does it — so an authoritative session-end total
+ // wins when present and a turn-by-turn estimate keeps the row
+ // non-zero in the meantime. Active-user rollup also moves to
+ // `gen_ai.user.name` (which the CLI stamps as a resource attr) so
+ // it stops returning 0 when the per-span `user.id` isn't set.
+ // Materialize over CHAT_ID (= coalesce(parent_id, session_id)) so
+ // the hub stats agree with the Sessions list:
+ // - 1 parent chat + N subagents = 1 session in both views
+ // - cost is summed across all spans of the chat (the parent's
+ // authoritative `coding_agent.session.cost_usd` still wins
+ // when present, via greatest())
+ // - active_users stores the *raw* distinct-user count. The
+ // COHORT_K_FLOOR mask used to live here, but it ran before
+ // auth context was even resolved, so a single-developer OSS
+ // install would always read 0. The hub already requires org
+ // membership; the deeper /coding-agents views apply the floor
+ // to per-user breakdowns where it's actually a privacy boundary.
+ // Implementation note: the natural shape here is a nested rollup
+ // (per_session → per_chat → per_vendor). We tried that — but
+ // ClickHouse aggressively inlines subqueries, which made
+ // `argMax(client_version, last_seen)` collapse to
+ // `argMax(argMax(...), max(Timestamp))` and fail with
+ // `ILLEGAL_AGGREGATION`. The same inlining bites WITH-style CTEs.
+ // So we collapse to one pass: chat_id is a per-row expression
+ // (coalesce of parent_id and session_id, both raw map lookups),
+ // so we can GROUP BY (vendor, chat_id) directly. session-level
+ // aggregation isn't needed because each (chat_id, session_id)
+ // shares the same vendor, and cost is summed across all spans of
+ // the chat anyway.
+ // The chat_id rollup MUST mirror queries.ts CHAT_ID_EXPR so the hub
+ // row counts agree with the Sessions list. New vendors should fold
+ // into the per-row coalesce here, NOT introduce a second discovery
+ // pass. Claude Code's native exporter sets `session.id` (plain,
+ // without the `coding_agent.` prefix); we fall through to it so a
+ // CLAUDE_CODE_ENABLE_TELEMETRY=1-only install (no openlit plugin)
+ // still appears in the hub.
+ // Per-span vendor expression: lets us GROUP BY (chat_id, vendor)
+ // so a chat id legitimately hosting spans from two vendors (Claude
+ // Code launched inside a Cursor terminal — both hooks fire under
+ // the host's chat id) yields TWO hub rows, one per vendor. Without
+ // this split the per-vendor user/cost counts inherit whichever
+ // vendor's spans happened to dominate the chat id and the user
+ // sees Cursor traffic counted against the Claude Code agent (or
+ // vice versa). The expression must mirror queries.ts PER_SPAN_VENDOR_EXPR.
+ const perSpanVendor = `
+ coalesce(
+ nullIf(SpanAttributes['coding_agent.client'], ''),
+ nullIf(ResourceAttributes['gen_ai.agent.name'], ''),
+ nullIf(ResourceAttributes['service.name'], '')
+ )
+ `;
+ const query = `
+ SELECT
+ vendor,
+ argMax(client_version, chat_last_seen) AS client_version,
+ min(chat_first_seen) AS first_seen,
+ max(chat_last_seen) AS last_seen,
+ uniqExact(chat_id) AS session_count_24h,
+ sum(chat_cost) AS cost_usd_24h,
+ uniqExactIf(user_id, user_id != '') AS active_users_24h,
+ sum(chat_lines_added) AS lines_added_24h,
+ sum(chat_lines_removed) AS lines_removed_24h,
+ sum(chat_lines_accepted) AS lines_accepted_24h,
+ sum(chat_lines_rejected) AS lines_rejected_24h,
+ sum(chat_edit_accept) AS edit_accept_24h,
+ sum(chat_edit_reject) AS edit_reject_24h,
+ sum(chat_commit_count) AS commit_count_24h,
+ sum(chat_pr_count) AS pr_count_24h
+ FROM (
+ SELECT
+ ${perSpanVendor} AS vendor,
+ coalesce(
+ nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),
+ nullIf(SpanAttributes['coding_agent.agent.parent_id'], ''),
+ nullIf(SpanAttributes['coding_agent.session.id'], ''),
+ nullIf(ResourceAttributes['coding_agent.session.id'], ''),
+ nullIf(SpanAttributes['session.id'], ''),
+ nullIf(ResourceAttributes['session.id'], '')
+ ) AS chat_id,
+ -- session-end cost wins when present, otherwise sum of
+ -- per-turn cost estimates. Both are stamped on chat-level
+ -- spans (root and per LLM turn).
+ greatest(
+ toFloat64OrZero(any(SpanAttributes['coding_agent.session.cost_usd'])),
+ sumOrNull(toFloat64OrZero(SpanAttributes['gen_ai.usage.cost']))
+ ) AS chat_cost,
+ -- Per-chat code-change rollups. The greatest(session-
+ -- rollup-attr, per-edit-decision-sum) pattern mirrors
+ -- queries.ts (and the materializer's cost expression)
+ -- so the hub agrees with the per-session list for
+ -- both Codex (no SessionEnd) and in-flight CC / Cursor
+ -- sessions.
+ greatest(
+ toInt64OrZero(any(SpanAttributes['coding_agent.session.lines.added'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['coding_agent.edit.lines.added']),
+ SpanName = 'coding_agent.edit.decision'
+ ))
+ ) AS chat_lines_added,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['coding_agent.session.lines.removed'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['coding_agent.edit.lines.removed']),
+ SpanName = 'coding_agent.edit.decision'
+ ))
+ ) AS chat_lines_removed,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['coding_agent.session.lines.accepted'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['coding_agent.edit.lines.added']),
+ SpanName = 'coding_agent.edit.decision'
+ AND SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS chat_lines_accepted,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['coding_agent.session.lines.rejected'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['coding_agent.edit.lines.added']),
+ SpanName = 'coding_agent.edit.decision'
+ AND SpanAttributes['coding_agent.edit.decision'] = 'reject'
+ ))
+ ) AS chat_lines_rejected,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['coding_agent.session.edit.accept_count'])),
+ toInt64(countIf(
+ SpanName = 'coding_agent.edit.decision'
+ AND SpanAttributes['coding_agent.edit.decision'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS chat_edit_accept,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['coding_agent.session.edit.reject_count'])),
+ toInt64(countIf(
+ SpanName = 'coding_agent.edit.decision'
+ AND SpanAttributes['coding_agent.edit.decision'] = 'reject'
+ ))
+ ) AS chat_edit_reject,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['coding_agent.session.commit_count'])),
+ toInt64(countIf(SpanName = 'coding_agent.git.commit'))
+ ) AS chat_commit_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['coding_agent.session.pr_count'])),
+ toInt64(countIf(SpanName = 'coding_agent.git.pull_request'))
+ ) AS chat_pr_count,
+ coalesce(
+ nullIf(any(SpanAttributes['gen_ai.user.name']), ''),
+ nullIf(any(ResourceAttributes['gen_ai.user.name']), ''),
+ nullIf(any(ResourceAttributes['user.email']), ''),
+ nullIf(any(SpanAttributes['user.email']), ''),
+ ''
+ ) AS user_id,
+ min(Timestamp) AS chat_first_seen,
+ max(Timestamp) AS chat_last_seen,
+ argMax(SpanAttributes['coding_agent.client.version'], Timestamp) AS client_version
+ FROM ${OTEL_TRACES_TABLE_NAME}
+ WHERE ${buildCodingWindowClause(window)}
+ AND (
+ SpanAttributes['coding_agent.session.id'] != ''
+ OR ResourceAttributes['coding_agent.session.id'] != ''
+ -- Native Claude Code OTel: signed by service.name and
+ -- a plain session.id attribute. Without this branch a
+ -- CLAUDE_CODE_ENABLE_TELEMETRY=1-only install would
+ -- never reach the hub.
+ OR (
+ ResourceAttributes['service.name'] = 'claude-code'
+ AND (SpanAttributes['session.id'] != '' OR ResourceAttributes['session.id'] != '')
+ )
+ )
+ GROUP BY chat_id, ${perSpanVendor}
+ HAVING vendor != ''
+ ) per_chat
+ GROUP BY vendor
+ HAVING vendor != ''
+ `;
+
+ const res = await dataCollector({ query }, "query", dbConfigId);
+ if (res.err) {
+ agentsLogger.error("materializer_coding_discovery_failed", {
+ err: res.err,
+ });
+ return [];
+ }
+ const rows = (res.data as Array<{
+ vendor: string;
+ client_version: string;
+ first_seen: string;
+ last_seen: string;
+ session_count_24h: number;
+ cost_usd_24h: number;
+ active_users_24h: number;
+ lines_added_24h: number;
+ lines_removed_24h: number;
+ lines_accepted_24h: number;
+ lines_rejected_24h: number;
+ edit_accept_24h: number;
+ edit_reject_24h: number;
+ commit_count_24h: number;
+ pr_count_24h: number;
+ }>) || [];
+
+ return rows
+ .filter((row) => row.vendor)
+ .map((row) => {
+ const vendor = row.vendor as CodingAgentVendor;
+ const cluster = "coding";
+ const env = "default";
+ // Per-vendor stable agent key. The detail page derives the
+ // vendor from `service_name` since cluster is fixed.
+ const agentKey = computeAgentKey(cluster, env, vendor);
+ return {
+ agent_key: agentKey,
+ service_name: vendor,
+ environment: env,
+ cluster_id: cluster,
+ workload_key: "",
+ source: "coding" as AgentSource,
+ controller_service_id: "",
+ controller_instance_id: "",
+ sdk_version: row.client_version || "",
+ sdk_language: "",
+ first_seen: row.first_seen,
+ last_seen: row.last_seen,
+ instrumentation_status: "instrumented",
+ controller_llm_providers: [],
+ coding_agent_vendor: vendor,
+ coding_session_count_24h: Number(row.session_count_24h || 0),
+ coding_cost_usd_24h: Number(row.cost_usd_24h || 0),
+ coding_active_users_24h: Number(row.active_users_24h || 0),
+ coding_lines_added_24h: Number(row.lines_added_24h || 0),
+ coding_lines_removed_24h: Number(row.lines_removed_24h || 0),
+ coding_lines_accepted_24h: Number(row.lines_accepted_24h || 0),
+ coding_lines_rejected_24h: Number(row.lines_rejected_24h || 0),
+ coding_edit_accept_24h: Number(row.edit_accept_24h || 0),
+ coding_edit_reject_24h: Number(row.edit_reject_24h || 0),
+ coding_commit_count_24h: Number(row.commit_count_24h || 0),
+ coding_pr_count_24h: Number(row.pr_count_24h || 0),
+ };
+ });
+}
+
function earliest(a: string, b: string): string {
if (!a) return b;
if (!b) return a;
@@ -386,7 +793,21 @@ async function fetchRequestCounts(
dbConfigId?: string
): Promise<Map<string, number>> {
if (!agents.length) return new Map();
- const serviceNames = Array.from(new Set(agents.map((a) => a.service_name)));
+
+ // Split coding agents from the rest. Their request_count is the
+ // total number of spans observed under the vendor in the last 24h
+ // (rolled up at discovery time as `session_count_24h`); the
+ // classic per-service ServiceName query won't match because coding
+ // agent spans come in under whatever service_name the host
+ // pipeline reports, not the vendor identifier.
+ const map = new Map<string, number>();
+ const traditional = agents.filter((a) => a.source !== "coding");
+ for (const coding of agents.filter((a) => a.source === "coding")) {
+ map.set(coding.agent_key, coding.coding_session_count_24h || 0);
+ }
+ if (!traditional.length) return map;
+
+ const serviceNames = Array.from(new Set(traditional.map((a) => a.service_name)));
const namesList = serviceNames.map((n) => `'${escape(n)}'`).join(", ");
const query = `
SELECT
@@ -404,7 +825,7 @@ async function fetchRequestCounts(
agentsLogger.error("materializer_request_count_failed", {
err: res.err,
});
- return new Map();
+ return map;
}
const rows = (res.data as Array<{
service_name: string;
@@ -412,7 +833,6 @@ async function fetchRequestCounts(
cluster_id: string;
request_count_24h: number;
}>) || [];
- const map = new Map<string, number>();
for (const r of rows) {
const key = computeAgentKey(
r.cluster_id || "default",
@@ -454,6 +874,20 @@ interface SummaryUpsertRow {
first_seen: string;
last_seen: string;
updated_at: string;
+ // Populated only on coding-agent rows. Kept inline (not a separate
+ // table) so the existing SELECTs already get them for free.
+ coding_agent_vendor: string;
+ coding_session_count_24h: number;
+ coding_cost_usd_24h: number;
+ coding_active_users_24h: number;
+ coding_lines_added_24h: number;
+ coding_lines_removed_24h: number;
+ coding_lines_accepted_24h: number;
+ coding_lines_rejected_24h: number;
+ coding_edit_accept_24h: number;
+ coding_edit_reject_24h: number;
+ coding_commit_count_24h: number;
+ coding_pr_count_24h: number;
}
function toClickHouseTimestamp(value: string | Date | number | undefined): string {
@@ -491,37 +925,52 @@ export async function materializeAgents(
const env = scope.environment || "default";
const cluster = scope.clusterId || "default";
const key = computeAgentKey(cluster, env, scope.serviceName);
- const all = await discoverAgents(dbConfigId, scope.clusterId);
- const match = all.find((a) => a.agent_key === key);
+ // Look for the agent in BOTH discovery pipelines, not just the SDK
+ // one. The detail page's "Refresh" button calls
+ // /api/agents/[agentKey]/refresh which passes the saved scope of
+ // the agent it was viewing — for a coding agent that's
+ // (service=cursor, cluster=coding). Only checking discoverAgents
+ // here meant the SDK pipeline would (correctly) report no match,
+ // the code would fall through to the SDK placeholder branch below,
+ // and we'd insert a phantom `source='sdk'` row into
+ // openlit_agents_summary that overwrites the legitimate
+ // `source='coding'` row on the next FINAL read. The UI then
+ // renders the SDK Overview/Dashboard/Monitoring layout for what
+ // is in fact a coding agent. See coding-agents-hook.mdc §10.
+ const [sdkAll, codingAll] = await Promise.all([
+ discoverAgents(dbConfigId, scope.clusterId),
+ discoverCodingAgents(dbConfigId),
+ ]);
+ const match =
+ sdkAll.find((a) => a.agent_key === key) ||
+ codingAll.find((a) => a.agent_key === key);
if (match) {
discovered = [match];
} else {
- // Manufacture a placeholder SDK row so we can still derive a snapshot.
- discovered = [
- {
- agent_key: key,
- service_name: scope.serviceName,
- environment: env,
- cluster_id: cluster,
- workload_key: "",
- source: "sdk",
- controller_service_id: "",
- controller_instance_id: "",
- sdk_version: "",
- sdk_language: "",
- first_seen: new Date().toISOString(),
- last_seen: new Date().toISOString(),
- instrumentation_status: "instrumented",
- controller_llm_providers: [],
- },
- ];
+ // Refuse to manufacture a placeholder. The historical intent
+ // was "still derive a snapshot when a forced materialize
+ // arrives before any spans" — but in practice the API only
+ // reaches this branch for refresh calls on agents that
+ // already exist, and the placeholder's `source='sdk'`
+ // silently clobbered legitimate coding rows. If a refresh
+ // hits before any spans arrive, the caller will simply see
+ // an unchanged snapshot until the next cron tick discovers
+ // the spans — which is what the operator expects.
+ discovered = [];
}
} else if (agentKeyFilter) {
const all = await discoverAgents(dbConfigId);
- const match = all.find((a) => a.agent_key === agentKeyFilter);
+ const codingAll = await discoverCodingAgents(dbConfigId);
+ const match =
+ all.find((a) => a.agent_key === agentKeyFilter) ||
+ codingAll.find((a) => a.agent_key === agentKeyFilter);
discovered = match ? [match] : [];
} else {
- discovered = await discoverAgents(dbConfigId);
+ const [traditional, coding] = await Promise.all([
+ discoverAgents(dbConfigId),
+ discoverCodingAgents(dbConfigId),
+ ]);
+ discovered = [...traditional, ...coding];
}
if (!discovered.length) {
@@ -565,13 +1014,20 @@ export async function materializeAgents(
for (const agent of discovered) {
try {
- const snapshot = await deriveSnapshot({
- serviceName: agent.service_name,
- environment: agent.environment,
- clusterId: agent.cluster_id,
- lookbackMinutes,
- dbConfigId,
- });
+ // Coding agents don't have a versioned system prompt
+ // (their "version" is the vendor's CLI version) so we
+ // skip snapshot derivation entirely. Saves one round-trip
+ // per coding row per tick and avoids polluting
+ // agent_versions with rows that have no system_prompt.
+ const snapshot = agent.source === "coding"
+ ? null
+ : await deriveSnapshot({
+ serviceName: agent.service_name,
+ environment: agent.environment,
+ clusterId: agent.cluster_id,
+ lookbackMinutes,
+ dbConfigId,
+ });
let versionHash = "";
let versionNumber = 0;
@@ -642,6 +1098,18 @@ export async function materializeAgents(
first_seen: toClickHouseTimestamp(agent.first_seen),
last_seen: toClickHouseTimestamp(agent.last_seen),
updated_at: toClickHouseTimestamp(new Date()),
+ coding_agent_vendor: agent.coding_agent_vendor || "",
+ coding_session_count_24h: agent.coding_session_count_24h || 0,
+ coding_cost_usd_24h: agent.coding_cost_usd_24h || 0,
+ coding_active_users_24h: agent.coding_active_users_24h || 0,
+ coding_lines_added_24h: agent.coding_lines_added_24h || 0,
+ coding_lines_removed_24h: agent.coding_lines_removed_24h || 0,
+ coding_lines_accepted_24h: agent.coding_lines_accepted_24h || 0,
+ coding_lines_rejected_24h: agent.coding_lines_rejected_24h || 0,
+ coding_edit_accept_24h: agent.coding_edit_accept_24h || 0,
+ coding_edit_reject_24h: agent.coding_edit_reject_24h || 0,
+ coding_commit_count_24h: agent.coding_commit_count_24h || 0,
+ coding_pr_count_24h: agent.coding_pr_count_24h || 0,
});
processed += 1;
} catch (err) {
@@ -655,6 +1123,61 @@ export async function materializeAgents(
}
if (summaryRows.length) {
+ // Safety net for the SDK-clobbers-coding bug. Before we INSERT,
+ // check whether any of the rows we are about to write would
+ // overwrite an existing `source='coding'` row with a non-coding
+ // source under the same agent_key. The ReplacingMergeTree dedup
+ // is by agent_key alone, so a stray `source='sdk'` write wins on
+ // the next FINAL read and the detail page flips layout. If we
+ // detect this, drop the offending rows and log loudly — the
+ // upstream code path is the bug, but we refuse to corrupt state
+ // regardless. See coding-agents-hook.mdc §10 for the structural
+ // fix chain.
+ const nonCodingKeys = summaryRows
+ .filter((r) => r.source !== "coding")
+ .map((r) => r.agent_key);
+ if (nonCodingKeys.length > 0) {
+ const escaped = nonCodingKeys
+ .map((k) => `'${k.replace(/'/g, "''")}'`)
+ .join(", ");
+ const conflictRes = await dataCollector(
+ {
+ query: `
+ SELECT agent_key
+ FROM ${AGENTS_SUMMARY_TABLE} FINAL
+ WHERE agent_key IN (${escaped}) AND source = 'coding'
+ `,
+ },
+ "query",
+ dbConfigId
+ );
+ if (!conflictRes.err && Array.isArray(conflictRes.data)) {
+ const codingKeys = new Set(
+ (conflictRes.data as Array<{ agent_key: string }>).map(
+ (r) => r.agent_key
+ )
+ );
+ if (codingKeys.size > 0) {
+ const before = summaryRows.length;
+ const filtered = summaryRows.filter(
+ (r) => r.source === "coding" || !codingKeys.has(r.agent_key)
+ );
+ if (filtered.length !== before) {
+ agentsLogger.error("materializer_blocked_coding_clobber", {
+ droppedRowCount: before - filtered.length,
+ agentKeys: Array.from(codingKeys),
+ });
+ summaryRows.length = 0;
+ summaryRows.push(...filtered);
+ }
+ }
+ }
+ }
+
+ if (!summaryRows.length) {
+ return { processed, newVersions, errors };
+ }
+
const res = await dataCollector(
{ table: AGENTS_SUMMARY_TABLE, values: summaryRows },
"insert",
diff --git a/src/client/src/lib/platform/coding-agents/auth.ts b/src/client/src/lib/platform/coding-agents/auth.ts
new file mode 100644
index 00000000..b3448825
--- /dev/null
+++ b/src/client/src/lib/platform/coding-agents/auth.ts
@@ -0,0 +1,106 @@
+/**
+ * Role-gated access for the coding-agents views.
+ *
+ * Two access tiers:
+ * - "viewer" → can read aggregated views (Overview, Sessions list,
+ * Dashboard). Per-user breakdowns are k-anonymized
+ * via COHORT_K_FLOOR.
+ * - "admin" → can additionally read raw per-user / per-session
+ * detail, file dispute claims, and configure
+ * classification policy.
+ *
+ * v1 maps these onto the existing organisation roles:
+ * - owner → admin
+ * - admin → admin
+ * - member → viewer
+ * - <none> → unauthorized
+ *
+ * Returning a CodingAgentAuth value (rather than a boolean) keeps the
+ * privacy posture explicit at every callsite — queries take it as a
+ * required argument instead of relying on ambient permission checks.
+ */
+
+import { getCurrentUser } from "@/lib/session";
+import { getCurrentOrganisation } from "@/lib/organisation";
+import prisma from "@/lib/prisma";
+import getMessage from "@/constants/messages";
+
+export type CodingAgentRole = "viewer" | "admin";
+
+export interface CodingAgentAuth {
+ userId: string;
+ organizationId: string;
+ role: CodingAgentRole;
+ /** Underlying organisation_users.role; useful for finer-grained UI gating. */
+ rawRole: string;
+}
+
+export class CodingAgentUnauthorizedError extends Error {
+ constructor(message?: string) {
+ super(message || getMessage().UNAUTHORIZED_USER);
+ this.name = "CodingAgentUnauthorizedError";
+ }
+}
+
+/**
+ * Resolve the current user's coding-agents role for the active org.
+ * Throws CodingAgentUnauthorizedError if the user has no current org
+ * or is not a member of it. Callers should let it bubble up; the
+ * Next route handler converts it to a 401/403 response.
+ */
+export async function requireCodingAgentAuth(): Promise<CodingAgentAuth> {
+ const user = await getCurrentUser();
+ if (!user) {
+ throw new CodingAgentUnauthorizedError();
+ }
+
+ const org = await getCurrentOrganisation();
+ if (!org?.id) {
+ throw new CodingAgentUnauthorizedError(
+ getMessage().NO_ORGANISATION_SELECTED ||
+ "No active organisation. Switch organisations to continue."
+ );
+ }
+
+ const [membership, organisation] = await Promise.all([
+ prisma.organisationUser.findUnique({
+ where: {
+ organisationId_userId: {
+ organisationId: org.id,
+ userId: user.id,
+ },
+ },
+ select: { role: true },
+ }),
+ prisma.organisation.findUnique({
+ where: { id: org.id },
+ select: { createdByUserId: true },
+ }),
+ ]);
+
+ if (!membership) {
+ throw new CodingAgentUnauthorizedError();
+ }
+
+ // Promote the org creator to admin even if their membership row
+ // says `member`. Older deployments seeded the creator without an
+ // explicit role; a one-line migration backfilled the column but
+ // the seed itself didn't, so a fresh setup ended up locking the
+ // owner out of admin-only views (incl. the cohort-floor bypass for
+ // coding-agents). Re-deriving from createdByUserId here makes the
+ // auth check resilient to data drift.
+ const isCreator = organisation?.createdByUserId === user.id;
+ const role: CodingAgentRole =
+ isCreator ||
+ membership.role === "owner" ||
+ membership.role === "admin"
+ ? "admin"
+ : "viewer";
+
+ return {
+ userId: user.id,
+ organizationId: org.id,
+ role,
+ rawRole: isCreator && membership.role === "member" ? "owner" : membership.role,
+ };
+}
diff --git a/src/client/src/lib/platform/coding-agents/classifier.ts b/src/client/src/lib/platform/coding-agents/classifier.ts
new file mode 100644
index 00000000..29e6359d
--- /dev/null
+++ b/src/client/src/lib/platform/coding-agents/classifier.ts
@@ -0,0 +1,120 @@
+/**
+ * Personal-vs-work classification metadata + UI helpers.
+ *
+ * The classification itself is stamped on every coding-agent span at
+ * hook-time by the openlit CLI (see `cli/internal/coding/classify`).
+ * This module exposes:
+ *
+ * - The canonical enum values, so UI components, queries, and tests
+ * stay in sync with the CLI.
+ * - Human-readable labels for the Governance board.
+ * - The shape of the dispute payload submitted via the API.
+ *
+ * No ClickHouse access lives here — that's `queries.ts`. No prisma
+ * access either — those reads happen behind the API route to keep
+ * this file safe to import from the client (e.g. for badge labels).
+ */
+
+export type CodingAgentClassification =
+ | "personal"
+ | "work"
+ | "disputed"
+ | "unknown";
+
+export type CodingAgentClassificationReason =
+ | "api_key_allowlist"
+ | "repo_origin_allowlist"
+ | "repo_origin_blocklist"
+ | "user_dispute"
+ | "no_signal";
+
+export const CODING_AGENT_CLASSIFICATION_LABELS: Record<
+ CodingAgentClassification,
+ string
+> = {
+ personal: "Personal",
+ work: "Work",
+ disputed: "Disputed",
+ unknown: "Unknown",
+};
+
+export const CODING_AGENT_CLASSIFICATION_DESCRIPTIONS: Record<
+ CodingAgentClassification,
+ string
+> = {
+ personal:
+ "Session originated outside the org's API-key/repo allowlist. Not counted in work spend.",
+ work:
+ "Session matched the API-key allowlist or a repo on an allowlisted origin.",
+ disputed:
+ "User filed a dispute on the auto-classification. Awaiting admin review.",
+ unknown:
+ "No classification signal was available — usually because the CLI ran without an API key or in a fresh repo.",
+};
+
+export const CODING_AGENT_CLASSIFICATION_REASON_LABELS: Record<
+ CodingAgentClassificationReason,
+ string
+> = {
+ api_key_allowlist: "Matched an API key on the org allowlist",
+ repo_origin_allowlist: "Repository origin is on the org allowlist",
+ repo_origin_blocklist: "Repository origin is on the org blocklist",
+ user_dispute: "Reclassified by user via dispute",
+ no_signal: "No classification signal available",
+};
+
+export interface CodingAgentClassificationDispute {
+ sessionId: string;
+ currentClassification: CodingAgentClassification;
+ requestedClassification: CodingAgentClassification;
+ rationale: string;
+}
+
+/**
+ * Validate a dispute payload before we persist it. Returns an error
+ * string if invalid; null otherwise. Kept synchronous so it can be
+ * reused on the client for form-level validation.
+ */
+export function validateClassificationDispute(
+ input: Partial<CodingAgentClassificationDispute>
+): string | null {
+ if (!input.sessionId || typeof input.sessionId !== "string") {
+ return "sessionId is required.";
+ }
+ if (
+ !input.currentClassification ||
+ !isCodingAgentClassification(input.currentClassification)
+ ) {
+ return "currentClassification is invalid.";
+ }
+ if (
+ !input.requestedClassification ||
+ !isCodingAgentClassification(input.requestedClassification)
+ ) {
+ return "requestedClassification is invalid.";
+ }
+ if (input.requestedClassification === input.currentClassification) {
+ return "Requested classification must differ from the current one.";
+ }
+ if (input.requestedClassification === "disputed") {
+ return "Cannot dispute toward 'disputed' — choose work, personal, or unknown.";
+ }
+ if (typeof input.rationale !== "string" || input.rationale.trim().length < 4) {
+ return "A short rationale (at least 4 characters) is required.";
+ }
+ if (input.rationale.length > 1000) {
+ return "Rationale must be 1000 characters or fewer.";
+ }
+ return null;
+}
+
+export function isCodingAgentClassification(
+ value: unknown
+): value is CodingAgentClassification {
+ return (
+ value === "personal" ||
+ value === "work" ||
+ value === "disputed" ||
+ value === "unknown"
+ );
+}
diff --git a/src/client/src/lib/platform/coding-agents/queries.ts b/src/client/src/lib/platform/coding-agents/queries.ts
new file mode 100644
index 00000000..0e9bc971
--- /dev/null
+++ b/src/client/src/lib/platform/coding-agents/queries.ts
@@ -0,0 +1,2042 @@
+/**
+ * Read-only ClickHouse helpers for the coding-agents views.
+ *
+ * Every helper takes a CodingAgentAuth value so the org filter is
+ * never optional. We intentionally don't accept a free-form
+ * `organizationId` — pass the auth bag, which the API route gets from
+ * `requireCodingAgentAuth()`.
+ *
+ * For v1 we only need the read paths used by:
+ * - /agents detail page (overview + sessions list)
+ * - /api/coding-agents/sessions[/id]
+ *
+ * Aggregated views (governance board, top-N) live in the seeded
+ * dashboard JSON and run through the dashboard widget executor; we
+ * don't need to duplicate them here.
+ *
+ * Privacy guardrails:
+ * - viewer-tier callers cannot read the per-session `gen_ai.user.name`
+ * when the session count for that user is below COHORT_K_FLOOR.
+ * We enforce that in `listSessions`/`getSession` by replacing the
+ * value with the literal string 'low_cohort'.
+ */
+
+import { dataCollector } from "@/lib/platform/common";
+import {
+ CODING_AGENT_AUDIT_LOG_TABLE,
+ CODING_AGENT_DISPUTES_TABLE,
+} from "@/clickhouse/migrations/create-coding-agents-audit-migration";
+import {
+ CODING_AGENT_ATTR,
+ CODING_AGENT_SPAN_EDIT_DECISION,
+ CODING_AGENT_SPAN_GIT_COMMIT,
+ CODING_AGENT_SPAN_GIT_PR,
+ CODING_AGENT_SPAN_LLM_TURN,
+ CODING_AGENT_SPAN_NAMES,
+ CODING_AGENT_SPAN_SESSION,
+ CODING_AGENT_SPAN_SUBAGENT,
+ CODING_AGENT_SPAN_TOOL_CALL,
+ COHORT_K_FLOOR,
+ GEN_AI_ATTR,
+ OTEL_TRACES_TABLE,
+ VCS_ATTR,
+} from "./table-details";
+import type { CodingAgentAuth } from "./auth";
+import type {
+ CodingAgentClassification,
+ CodingAgentClassificationDispute,
+} from "./classifier";
+import { buildSessionsHaving, escape } from "./query-builders";
+
+export { buildSessionsHaving } from "./query-builders";
+
+// Wire-format sort keys for the Sessions tab. Mapped to ClickHouse
+// columns via SESSIONS_SORT_COLUMNS below; `latest` is the default
+// and matches the historic ORDER BY started_at DESC behaviour.
+export type CodingSessionsSortBy =
+ | "latest"
+ | "duration"
+ | "cost"
+ | "tokens"
+ | "tool_calls";
+
+const SESSIONS_SORT_COLUMNS: Record<CodingSessionsSortBy, string> = {
+ latest: "started_at",
+ duration: "duration_ms",
+ cost: "cost_usd",
+ tokens: "total_tokens",
+ tool_calls: "tool_call_count",
+};
+
+export interface ListSessionsOptions {
+ limit?: number;
+ cursor?: string | null;
+ vendor?: string | null;
+ user?: string | null;
+ classification?: CodingAgentClassification | null;
+ since?: Date | null;
+ until?: Date | null;
+ // `offset` is the alternative pagination model used by the new
+ // telemetry signal-list (it sends `offset/limit` rather than the
+ // cursor convention). When set, `cursor` is ignored.
+ offset?: number;
+ // When `withTotal` is true the helper runs an extra count(*) query
+ // so the caller can render a total badge on the table.
+ withTotal?: boolean;
+ // Sort surface for the Sessions tab toolbar. Keys map to columns
+ // of the `sessions_raw` CTE — see `SESSIONS_SORT_COLUMNS`.
+ sortBy?: CodingSessionsSortBy;
+ sortDir?: "asc" | "desc";
+ // Subagent rows (Cursor background agents, Codex subagents) are
+ // folded under the parent chat in the trace-detail view. By
+ // default we also hide them from the top-level Sessions list so
+ // one chat = one row. Setting this to true brings them back —
+ // useful for debugging linkage gaps or when a user explicitly
+ // wants to see every emitted session row.
+ includeSubagents?: boolean;
+}
+
+
+export interface CodingAgentSessionRow {
+ session_id: string;
+ vendor: string;
+ user: string;
+ started_at: string;
+ ended_at: string | null;
+ duration_ms: number;
+ tool_call_count: number;
+ cost_usd: number;
+ outcome: string;
+ classification: CodingAgentClassification;
+ classification_reason: string;
+ repo_url: string;
+ repo_dirty: boolean;
+ // Branch name (`vcs.ref.head.name`). Lets the session row show
+ // "openlit/openlit @ feature/x" without opening the trace detail.
+ branch: string;
+ // Top model used in the session (most-recent gen_ai.request.model
+ // across the session's spans). Empty when no LLM/tool span carried
+ // a model attribute.
+ model: string;
+ // Aggregate token totals — sumed across LLM-turn spans. Most CLI
+ // adapters set both halves; Cursor only emits output tokens for
+ // some events so input may be 0 when the upstream payload didn't
+ // include it.
+ input_tokens: number;
+ output_tokens: number;
+ total_tokens: number;
+ // `trace_id` is the OTel TraceId every span in this session shares.
+ // The CLI derives it deterministically from (session_id, vendor)
+ // so all spans for the same (chat, vendor) pair land in the same
+ // trace across separate hook processes.
+ trace_id: string;
+ // `session_root_span_id` is the SpanId we open in TraceDetailView.
+ // The CLI stamps a deterministic SpanId on the `coding_agent.session`
+ // root span; this column prefers that span and falls back to the
+ // chronologically-first child if no root span was emitted yet.
+ session_root_span_id: string;
+ // Latest permission mode (Cursor's composer_mode: agent / ask /
+ // plan; Claude Code: default / plan / acceptEdits / etc.). The
+ // value is the most recent observed across the session, so a
+ // row's mode chip reflects what the agent is currently set to.
+ permission_mode: string;
+ // Working folder (cwd) the agent is operating in. Surfaced as a
+ // short trailing path (`/openlit/src`) on the row and as a full
+ // pill on the trace-detail header.
+ working_dir: string;
+ working_dir_label: string;
+ // Per-session code-change rollups. The query prefers the
+ // session-rollup attribute (stamped on the session-root span at
+ // SessionEnd) and falls back to summing the per-edit-decision
+ // spans when the session is still in progress / never fired
+ // SessionEnd (Codex; long-running CC sessions that closed
+ // without /exit). `acceptance_pct` is computed at query time
+ // from accepted / (accepted + rejected); 0 when both are zero
+ // so the row renders "—" instead of NaN.
+ lines_added: number;
+ lines_removed: number;
+ lines_accepted: number;
+ lines_rejected: number;
+ edit_accept_count: number;
+ edit_reject_count: number;
+ acceptance_pct: number;
+ commit_count: number;
+ pr_count: number;
+ // True when the chat is a subagent of another chat — i.e. any span
+ // in the rollup has `coding_agent.agent.parent_id` set or the CLI
+ // stamped `coding_agent.session.is_subagent`. listSessions hides
+ // these by default; they fold under the parent chat via the
+ // CHAT_ID_EXPR coalesce.
+ is_subagent: 0 | 1;
+}
+
+/**
+ * Cost is rolled up two ways:
+ * - the session-level `coding_agent.session.cost_usd` attribute (set by
+ * Claude Code from transcript JSONL with realized prices)
+ * - sum of `gen_ai.usage.cost` across all child spans (used by Cursor,
+ * where we estimate cost from token-length heuristics on the
+ * LLM-turn spans because Cursor's hooks don't surface tokens).
+ *
+ * We take whichever is greater so a vendor's authoritative number wins
+ * when present. Tool-call counts work the same way: prefer the session
+ * attribute when present, otherwise count `coding_agent.tool.call`
+ * spans.
+ */
+// User identity. The CLI hook subcommand resolves the canonical
+// email-shaped identity BEFORE booting the OTel SDK (Cursor's
+// `user_email`, Claude Code's `~/.claude.json#oauthAccount.emailAddress`,
+// Codex's `~/.codex/auth.json` JWT, or `git config user.email`) and
+// stamps it as `gen_ai.user.name` on every emitted span. We also
+// accept Claude Code's native `user.email` resource attribute (set
+// when `CLAUDE_CODE_ENABLE_TELEMETRY=1`) for users who haven't
+// installed the openlit plugin.
+//
+// We deliberately do NOT fall through to `service.name` here — that
+// would surface an agent identifier ("claude-code") in the user
+// column when identity resolution misses, which produced confusing
+// "claude-code" user rows in the hub.
+const USER_EXPR = `
+ coalesce(
+ nullIf(any(SpanAttributes['${GEN_AI_ATTR.userName}']), ''),
+ nullIf(any(ResourceAttributes['${GEN_AI_ATTR.userName}']), ''),
+ nullIf(any(ResourceAttributes['user.email']), ''),
+ nullIf(any(SpanAttributes['user.email']), ''),
+ 'unknown'
+ )
+`;
+
+// Per-span vendor expression: resolves a SINGLE span to its agent
+// identity. Used in the GROUP BY so a chat id that legitimately
+// hosts spans from two vendors (e.g. Claude Code launched inside a
+// Cursor terminal — both hooks fire under the host's chat id) folds
+// into TWO rows, one per vendor, instead of one collapsed row whose
+// "winning" vendor depends on which side emitted more spans. The
+// user-facing contract is "cursor chat in cursor sessions, claude
+// code chats in claude code sessions no matter the terminal".
+//
+// Order:
+// 1. SpanAttributes['coding_agent.client'] — the per-span stamp
+// adapters set on every emitted span (canonical).
+// 2. ResourceAttributes['gen_ai.agent.name'] — SDK-style stamp.
+// 3. ResourceAttributes['service.name'] — Claude Code's native OTel
+// exporter sets this to "claude-code"; recognise it so users
+// who only enable `CLAUDE_CODE_ENABLE_TELEMETRY=1` (no openlit
+// plugin installed) still show up in the hub.
+const PER_SPAN_VENDOR_EXPR = `
+ coalesce(
+ nullIf(SpanAttributes['${CODING_AGENT_ATTR.client}'], ''),
+ nullIf(ResourceAttributes['${GEN_AI_ATTR.agentName}'], ''),
+ nullIf(ResourceAttributes['service.name'], ''),
+ 'unknown'
+ )
+`;
+// VENDOR_EXPR resolves the AGGREGATED vendor for a session group
+// after the GROUP BY (chat_id, per_span_vendor) split. Inside the
+// group every span has the same vendor by construction, so any()
+// is enough — we keep the coalesce only as defence-in-depth against
+// a single malformed span in the bucket.
+const VENDOR_EXPR = `
+ coalesce(
+ nullIf(any(SpanAttributes['${CODING_AGENT_ATTR.client}']), ''),
+ nullIf(any(ResourceAttributes['${GEN_AI_ATTR.agentName}']), ''),
+ nullIf(any(ResourceAttributes['service.name']), ''),
+ 'unknown'
+ )
+`;
+
+// E1 deferral note: a coding_agent_sessions ReplacingMergeTree
+// materialized view would speed up the Sessions list at ~1M+ spans
+// per day, but in beta we don't have that volume yet and the GROUP BY
+// over `otel_traces` is fast enough (sub-second on the dev set). When
+// we ship the MV, change `OTEL_TRACES_TABLE` to point at it and rely
+// on the chat-id rollup already in SESSION_BASE_COLUMNS.
+
+// CHAT_ID_EXPR resolves a span to its chat-thread identifier. We try
+// the fields in order of stability so one chat-thread = one chat row,
+// even when the vendor exposes multiple ids per event:
+// 1. If a parent_id resource attribute is set, this span is from a
+// subagent and we fold it under the parent's chat. The CLI stamps
+// `coding_agent.agent.parent_id` as a resource attribute on every
+// hook process that knows it's running inside a subagent (Cursor
+// reports `parent_conversation_id` on subagent payloads).
+// 2. `gen_ai.conversation.id` — the chat-thread id, stamped by the
+// CLI from Cursor's `conversation_id`. Stable across plan-mode
+// toggles and Cursor process restarts within one chat. We prefer
+// it over `coding_agent.session.id` because Cursor's session_id
+// can be absent on some events (forcing a fallback to
+// conversation_id mid-chat) which would otherwise split one chat
+// across multiple chat-id values.
+// 3. `coding_agent.session.id` — fallback when no conversation id is
+// stamped (Claude Code / Codex, where session_id IS the chat).
+// 4. `session.id` — Claude Code's native OTel exporter (when
+// `CLAUDE_CODE_ENABLE_TELEMETRY=1`) puts its identifier here
+// directly. We fall through to it so native-only installs still
+// get a stable chat row.
+// Used in tandem with PER_SPAN_VENDOR_EXPR as the (chat_id, vendor)
+// rollup key: two vendors firing under the same chat id (Claude Code
+// launched inside a Cursor terminal) fold into TWO rows so each
+// agent's chat shows up under its own vendor regardless of which
+// editor hosted it.
+const CHAT_ID_EXPR = `
+ coalesce(
+ nullIf(ResourceAttributes['${CODING_AGENT_ATTR.agentParentId}'], ''),
+ nullIf(SpanAttributes['${CODING_AGENT_ATTR.agentParentId}'], ''),
+ nullIf(ResourceAttributes['gen_ai.conversation.id'], ''),
+ nullIf(SpanAttributes['gen_ai.conversation.id'], ''),
+ nullIf(SpanAttributes['${CODING_AGENT_ATTR.sessionId}'], ''),
+ nullIf(ResourceAttributes['${CODING_AGENT_ATTR.sessionId}'], ''),
+ nullIf(SpanAttributes['session.id'], ''),
+ nullIf(ResourceAttributes['session.id'], '')
+ )
+`;
+
+const SESSION_BASE_COLUMNS = `
+ ${CHAT_ID_EXPR} AS session_id,
+ ${VENDOR_EXPR} AS vendor,
+ ${USER_EXPR} AS user,
+ -- Explicit 'UTC' timezone — the literal 'Z' in the format string
+ -- was previously a lie when ClickHouse was running with a non-UTC
+ -- local timezone. The 3-arg form forces the output to be UTC,
+ -- matching the trailing 'Z' marker.
+ formatDateTime(min(Timestamp), '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS started_at,
+ formatDateTime(max(Timestamp), '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS ended_at,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionDurationMs}'])),
+ toInt64(toUnixTimestamp64Milli(max(Timestamp)) - toUnixTimestamp64Milli(min(Timestamp)))
+ ) AS duration_ms,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionToolCallCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_TOOL_CALL}'))
+ ) AS tool_call_count,
+ -- Cost rollup. Two source paths exist:
+ -- (1) The session-root span stamps coding_agent.session.cost_usd
+ -- (CLI-specific rollup) AND gen_ai.usage.cost (per OTel
+ -- GenAI conventions on the root) at SessionEnd.
+ -- (2) Every llm.turn child span stamps gen_ai.usage.cost per turn.
+ -- A naive sum(gen_ai.usage.cost) double-counts ended sessions
+ -- because the root span also carries it. We prefer the
+ -- authoritative session_cost_usd on the root when present and
+ -- only sum **child** spans otherwise.
+ coalesce(
+ nullIf(toFloat64OrZero(anyIf(
+ SpanAttributes['${CODING_AGENT_ATTR.sessionCostUsd}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toFloat64OrZero(SpanAttributes['${GEN_AI_ATTR.usageCost}']),
+ 0
+ ))
+ ) AS cost_usd,
+ -- Outcome: pick the LATEST non-empty value, not just any(). Stop
+ -- events on Claude Code and Codex stamp "completed" once per turn,
+ -- and SessionEnd (when it fires on CC) stamps the terminal verdict
+ -- like "abandoned_with_change" / "cancelled". We want the terminal
+ -- verdict to win — that only happens if we sort by Timestamp. With
+ -- plain any() the row could permanently latch onto an early
+ -- "completed" even after the user cancelled.
+ coalesce(
+ nullIf(
+ argMaxIf(
+ SpanAttributes['${CODING_AGENT_ATTR.sessionOutcome}'],
+ Timestamp,
+ notEmpty(SpanAttributes['${CODING_AGENT_ATTR.sessionOutcome}'])
+ ),
+ ''
+ ),
+ 'unknown'
+ ) AS outcome,
+ coalesce(nullIf(any(SpanAttributes['${CODING_AGENT_ATTR.userClassification}']), ''), 'unknown') AS classification,
+ coalesce(nullIf(any(SpanAttributes['${CODING_AGENT_ATTR.userClassificationReason}']), ''), 'no_signal') AS classification_reason,
+ -- VCS metadata. We surface the LATEST non-empty value across the
+ -- session (argMax by Timestamp), preferring the span attribute —
+ -- which carries the live per-turn value (Cursor's git_branch
+ -- payload, Claude Code's transcript gitBranch) — over the resource
+ -- attribute, which is the per-process session-start snapshot. This
+ -- way a mid-session branch / repo switch shows the current value on
+ -- the row instead of latching onto whichever span any() happened to
+ -- pick. Falls through to the resource attr for spans (llm.turn /
+ -- tool.call) that never stamped a span-level VCS attribute.
+ coalesce(
+ nullIf(argMaxIf(SpanAttributes['${VCS_ATTR.repoUrl}'], Timestamp, notEmpty(SpanAttributes['${VCS_ATTR.repoUrl}'])), ''),
+ nullIf(argMaxIf(ResourceAttributes['${VCS_ATTR.repoUrl}'], Timestamp, notEmpty(ResourceAttributes['${VCS_ATTR.repoUrl}'])), '')
+ ) AS repo_url,
+ coalesce(
+ nullIf(argMaxIf(SpanAttributes['${VCS_ATTR.headRef}'], Timestamp, notEmpty(SpanAttributes['${VCS_ATTR.headRef}'])), ''),
+ nullIf(argMaxIf(ResourceAttributes['${VCS_ATTR.headRef}'], Timestamp, notEmpty(ResourceAttributes['${VCS_ATTR.headRef}'])), '')
+ ) AS branch,
+ if(any(SpanAttributes['${CODING_AGENT_ATTR.vcsDirty}']) = 'true', 1, 0) AS repo_dirty,
+ -- Latest model used by the session (argMax keeps the most recent
+ -- non-empty value across all child spans).
+ argMaxIf(
+ SpanAttributes['${GEN_AI_ATTR.requestModel}'],
+ Timestamp,
+ notEmpty(SpanAttributes['${GEN_AI_ATTR.requestModel}'])
+ ) AS model,
+ -- Token rollups. Same shape as cost above: the session root
+ -- stamps gen_ai.usage.*_tokens at SessionEnd (rolled-up across the
+ -- whole session, per OTel GenAI conventions), AND every llm.turn
+ -- child span stamps its own per-turn count. A naive sum across
+ -- all spans double-counts ended sessions. Prefer the authoritative
+ -- root value when present and only sum **child** spans otherwise.
+ toInt64(coalesce(
+ nullIf(toInt64OrZero(anyIf(
+ SpanAttributes['${GEN_AI_ATTR.usageInputTokens}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']),
+ 0
+ ))
+ )) AS input_tokens,
+ toInt64(coalesce(
+ nullIf(toInt64OrZero(anyIf(
+ SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}']),
+ 0
+ ))
+ )) AS output_tokens,
+ toInt64(coalesce(
+ nullIf(toInt64OrZero(anyIf(
+ SpanAttributes['${GEN_AI_ATTR.usageTotalTokens}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}']),
+ 0
+ ))
+ )) AS total_tokens,
+ -- TraceId for the session. The CLI derives it deterministically
+ -- from (session_id, vendor) so every span in the same (chat,
+ -- vendor) group shares one TraceId — any() picks the same value
+ -- across the group. We still prefer the session-root span's
+ -- TraceId explicitly so reads stay deterministic if a future
+ -- regression breaks the deterministic derivation for child spans.
+ coalesce(
+ nullIf(anyIf(TraceId, SpanName = '${CODING_AGENT_SPAN_SESSION}'), ''),
+ argMax(TraceId, Timestamp)
+ ) AS trace_id,
+ -- SpanId we open in TraceDetailView. Prefer the explicit
+ -- session-root span when present; otherwise fall back to the
+ -- chronologically-first child span so the detail page is always
+ -- reachable, even when sessionEnd never fired.
+ coalesce(
+ nullIf(anyIf(SpanId, SpanName = '${CODING_AGENT_SPAN_SESSION}'), ''),
+ argMin(SpanId, Timestamp)
+ ) AS session_root_span_id,
+ -- Latest permission mode seen in the session (composer_mode for
+ -- Cursor, permission_mode for Claude Code). argMaxIf keeps the
+ -- most recent non-empty value across all child spans, so a
+ -- mid-session toggle is reflected on the row immediately.
+ -- Fall through to the resource attribute the CLI stamps for
+ -- short-lived hook invocations where the session-root span isn't
+ -- in this batch.
+ coalesce(
+ nullIf(
+ argMaxIf(
+ SpanAttributes['${CODING_AGENT_ATTR.policyPermissionMode}'],
+ Timestamp,
+ notEmpty(SpanAttributes['${CODING_AGENT_ATTR.policyPermissionMode}'])
+ ),
+ ''
+ ),
+ nullIf(any(ResourceAttributes['${CODING_AGENT_ATTR.policyPermissionMode}']), ''),
+ ''
+ ) AS permission_mode,
+ -- Working folder. The session-root span carries it directly; we
+ -- fall through to any tool-call span's code.cwd and finally to
+ -- the resource attribute the CLI stamps on every span in the
+ -- same process so child spans expose it too. The label is just
+ -- the trailing 2 path segments so the row stays compact.
+ coalesce(
+ nullIf(anyIf(SpanAttributes['code.cwd'], SpanName = '${CODING_AGENT_SPAN_SESSION}'), ''),
+ nullIf(anyIf(SpanAttributes['code.cwd'], notEmpty(SpanAttributes['code.cwd'])), ''),
+ nullIf(any(ResourceAttributes['code.cwd']), ''),
+ ''
+ ) AS working_dir,
+ arrayStringConcat(
+ arraySlice(
+ arrayFilter(s -> s != '', splitByChar('/',
+ coalesce(
+ nullIf(anyIf(SpanAttributes['code.cwd'], SpanName = '${CODING_AGENT_SPAN_SESSION}'), ''),
+ nullIf(anyIf(SpanAttributes['code.cwd'], notEmpty(SpanAttributes['code.cwd'])), ''),
+ nullIf(any(ResourceAttributes['code.cwd']), ''),
+ ''
+ )
+ )),
+ -2
+ ),
+ '/'
+ ) AS working_dir_label,
+ -- Per-session code-change rollups. Each pair takes the greater
+ -- of the session-rollup attribute (stamped on the session-root
+ -- span at SessionEnd) and the sum of per-edit-decision span
+ -- attrs. The fallback handles two cases:
+ -- 1. Codex sessions, which have no SessionEnd hook — the
+ -- session-root span never gets the rollup, so we sum the
+ -- per-edit spans instead.
+ -- 2. In-flight Claude Code / Cursor sessions that haven't
+ -- fired SessionEnd yet (the UI is allowed to show partial
+ -- data during a live session).
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesAdded}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ ))
+ ) AS lines_added,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesRemoved}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesRemoved}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ ))
+ ) AS lines_removed,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesAccepted}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS lines_accepted,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesRejected}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ ) AS lines_rejected,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditAcceptCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS edit_accept_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditRejectCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ ) AS edit_reject_count,
+ -- acceptance_pct is computed downstream of the greatest()
+ -- pairs above so it stays consistent with the displayed
+ -- accept / reject totals (otherwise a SessionEnd that
+ -- under-counted vs the per-edit sum would skew the %).
+ if(
+ (greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditAcceptCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) + greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditRejectCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ )) = 0,
+ toFloat64(0),
+ round(
+ toFloat64(greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditAcceptCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ )) * 100 /
+ toFloat64(greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditAcceptCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) + greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditRejectCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ )),
+ 2
+ )
+ ) AS acceptance_pct,
+ -- Commit / PR rollups. Same dual-source pattern: prefer the
+ -- session-rollup attribute, fall back to counting the
+ -- per-commit / per-PR spans.
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionCommitCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_GIT_COMMIT}'))
+ ) AS commit_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionPrCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_GIT_PR}'))
+ ) AS pr_count,
+ -- Is this chat a subagent of another chat? True when ANY span in
+ -- the group has a non-empty parent_id (resource OR span attr) OR
+ -- the CLI explicitly stamped coding_agent.session.is_subagent
+ -- on the session-root resource. listSessions hides these by
+ -- default - they fold under the parent chat via CHAT_ID_EXPR.
+ -- The check is intentionally lenient so a partial linkage (e.g.
+ -- parent_id only on a few spans, missing on the root) still
+ -- classifies the chat as a subagent.
+ if(
+ max(
+ notEmpty(SpanAttributes['${CODING_AGENT_ATTR.agentParentId}']) OR
+ notEmpty(ResourceAttributes['${CODING_AGENT_ATTR.agentParentId}']) OR
+ ResourceAttributes['coding_agent.session.is_subagent'] = 'true' OR
+ SpanAttributes['coding_agent.session.is_subagent'] = 'true'
+ ),
+ 1,
+ 0
+ ) AS is_subagent
+`;
+
+/**
+ * The shared filter shared by every read in this module. Notes:
+ * - `ResourceAttributes['organization.id']` is the convention we
+ * plan to set in the materializer migration; for v1 we don't yet
+ * populate it, so the filter degrades into a per-database-config
+ * query (the dataCollector already scopes to the user's
+ * databaseConfigId via session). We still emit the WHERE so we
+ * don't have to migrate every consumer when v2 lights it up.
+ * - Span name in CODING_AGENT_SPAN_NAMES so unrelated traces don't
+ * leak in.
+ */
+// whereScope is the canonical WHERE block for every coding-agents
+// read query. Org isolation today happens at the ClickHouse layer
+// (one DB per org, picked by `dataCollector`), so we don't emit an
+// `organization.id = ...` filter here unless the CLI has started
+// stamping the resource attribute AND the deployment has opted
+// into the extra filter via `OPENLIT_REQUIRE_ORG_FILTER=1`.
+//
+// E5 placeholder: passing `auth` lets callers stamp the extra
+// filter the day the CLI ships the resource attribute, without
+// another query rewrite. The `requireOrgFilter` gate keeps the
+// behaviour identical for existing self-host deployments where the
+// CLI hasn't been upgraded yet (those would otherwise return zero
+// rows for sessions emitted before the CLI started stamping).
+const ORG_ID_RESOURCE_ATTR = "openlit.organization.id";
+function whereScope(opts?: {
+ since?: Date | null;
+ until?: Date | null;
+ auth?: CodingAgentAuth | null;
+}) {
+ const since = opts?.since
+ ? `AND Timestamp >= parseDateTimeBestEffort('${escape(opts.since.toISOString())}')`
+ : "";
+ const until = opts?.until
+ ? `AND Timestamp <= parseDateTimeBestEffort('${escape(opts.until.toISOString())}')`
+ : "";
+
+ const requireOrgFilter =
+ process.env.OPENLIT_REQUIRE_ORG_FILTER === "1" ||
+ process.env.OPENLIT_REQUIRE_ORG_FILTER === "true";
+ const orgId = opts?.auth?.organizationId;
+ const orgScope =
+ requireOrgFilter && orgId
+ ? `AND coalesce(
+ nullIf(ResourceAttributes['${ORG_ID_RESOURCE_ATTR}'], ''),
+ nullIf(SpanAttributes['${ORG_ID_RESOURCE_ATTR}'], ''),
+ ''
+ ) = '${escape(orgId)}'`
+ : "";
+
+ return `
+ WHERE SpanName IN (${CODING_AGENT_SPAN_NAMES.map((n) => `'${n}'`).join(", ")})
+ AND notEmpty(SpanAttributes['${CODING_AGENT_ATTR.sessionId}'])
+ ${since}
+ ${until}
+ ${orgScope}
+ `;
+}
+
+/**
+ * List recent coding-agent sessions for the active org/database.
+ * Cursor is the started_at timestamp of the last row (descending paging).
+ * Pass `offset` instead of `cursor` to get classic pagination (the new
+ * `<ObservabilitySignalList>` uses offset/limit).
+ */
+export async function listSessions(
+ auth: CodingAgentAuth,
+ opts: ListSessionsOptions = {}
+): Promise<{
+ rows: CodingAgentSessionRow[];
+ nextCursor: string | null;
+ total: number | null;
+}> {
+ const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
+ const offset = Math.max(opts.offset ?? 0, 0);
+ const useOffset = typeof opts.offset === "number";
+ const cursorClause = !useOffset && opts.cursor
+ ? `WHERE started_at < '${escape(opts.cursor)}'`
+ : "";
+ const havingClause = buildSessionsHaving(opts);
+
+ // Cursor pagination presumes a stable order on `started_at` —
+ // we only honor a custom sort when callers use offset pagination.
+ const sortBy: CodingSessionsSortBy = useOffset
+ ? opts.sortBy || "latest"
+ : "latest";
+ const sortDir = opts.sortDir === "asc" ? "ASC" : "DESC";
+ const orderColumn = SESSIONS_SORT_COLUMNS[sortBy] || "started_at";
+ const orderClause = `ORDER BY ${orderColumn} ${sortDir}, started_at DESC`;
+
+ const sessionsRawCte = `
+ WITH sessions_raw AS (
+ SELECT
+ ${SESSION_BASE_COLUMNS}
+ FROM ${OTEL_TRACES_TABLE}
+ ${whereScope({
+ since: opts.since ?? null,
+ until: opts.until ?? null,
+ auth,
+ })}
+ GROUP BY ${CHAT_ID_EXPR}, ${PER_SPAN_VENDOR_EXPR}
+ ${havingClause}
+ )
+ `;
+
+ const dataQuery = useOffset
+ ? `
+ ${sessionsRawCte}
+ SELECT *
+ FROM sessions_raw
+ ${cursorClause}
+ ${orderClause}
+ LIMIT ${limit}
+ OFFSET ${offset}
+ `
+ : `
+ ${sessionsRawCte}
+ SELECT *
+ FROM sessions_raw
+ ${cursorClause}
+ ORDER BY started_at DESC
+ LIMIT ${limit + 1}
+ `;
+
+ const dataPromise = dataCollector({ query: dataQuery });
+ const totalPromise = opts.withTotal
+ ? dataCollector({
+ query: `
+ ${sessionsRawCte}
+ SELECT toInt64(count()) AS total FROM sessions_raw
+ `,
+ })
+ : Promise.resolve({ data: [] as Array<{ total: number }>, err: null });
+
+ const [{ data, err }, { data: totalData }] = await Promise.all([
+ dataPromise,
+ totalPromise,
+ ]);
+ if (err) throw err;
+ const rawRows = (data || []) as CodingAgentSessionRow[];
+
+ let sliced: CodingAgentSessionRow[];
+ let nextCursor: string | null;
+ if (useOffset) {
+ sliced = rawRows;
+ nextCursor = null;
+ } else {
+ sliced = rawRows.slice(0, limit);
+ nextCursor =
+ rawRows.length > limit
+ ? sliced[sliced.length - 1]?.started_at || null
+ : null;
+ }
+
+ const projected = await applyCohortFloor(auth, sliced, {
+ since: opts.since ?? null,
+ until: opts.until ?? null,
+ });
+ const totalRow = (totalData as Array<{ total: number | string }>) ?? [];
+ const total = opts.withTotal
+ ? Number(totalRow[0]?.total ?? 0)
+ : null;
+
+ return {
+ rows: projected,
+ nextCursor,
+ total,
+ };
+}
+
+/**
+ * Lightweight per-session rollup. Returns just the code-impact
+ * counters the trace-detail header pills need (lines added/removed,
+ * commits, edit accept/reject totals, PRs, acceptance pct), without
+ * fetching the heavy turn/tool/MCP joins `getSession` does.
+ *
+ * Why this exists separately: the trace-detail page renders for
+ * EVERY span the operator clicks on, including child spans like
+ * `coding_agent.llm.turn` and `coding_agent.tool.call`. Those child
+ * spans don't carry the session-level rollup attributes (the CLI
+ * stamps them on the session-root span at SessionEnd only), so the
+ * pills used to render empty on anything but the root. This helper
+ * lets the UI ask "what are this session's totals?" by session_id
+ * with a single tiny query so the pills stay populated regardless
+ * of which span the developer is looking at.
+ */
+export interface CodingSessionDigest {
+ session_id: string;
+ lines_added: number;
+ lines_removed: number;
+ lines_accepted: number;
+ lines_rejected: number;
+ edit_accept_count: number;
+ edit_reject_count: number;
+ commit_count: number;
+ pr_count: number;
+ acceptance_pct: number;
+ // Session-level usage rollups. These are populated by the same
+ // dedupe pattern SESSION_BASE_COLUMNS uses (prefer the session-root
+ // rollup attr when present; fall back to summing child llm.turn
+ // spans for in-flight sessions). The trace-detail top cards
+ // consume them so a still-running session's Tokens / Cost /
+ // Duration / Model don't render as zero just because the user is
+ // looking at a child span.
+ total_tokens: number;
+ input_tokens: number;
+ output_tokens: number;
+ cost_usd: number;
+ duration_ms: number;
+ model: string;
+ // VCS / workspace context, resolved as the LATEST non-empty value
+ // across the session (argMax by Timestamp, span attr preferred over
+ // resource attr). A developer who switches branch / repo / folder
+ // mid-session sees the current value in the header instead of the
+ // session-start snapshot that the chronologically-first span (which
+ // the detail view opens on) carries.
+ repo_url: string;
+ branch: string;
+ working_dir: string;
+ working_dir_label: string;
+}
+
+// SESSION_DIGEST_LOOKBACK_DAYS bounds how far back the per-session
+// digest will scan `otel_traces`. Without it, every trace-detail
+// page load triggered a full-history scan for a single session_id —
+// fine on a fresh install, expensive once retention grows. 90 days
+// matches the dispute-existence lookup window and is comfortably
+// longer than the default ClickHouse retention most OSS installs
+// run with.
+const SESSION_DIGEST_LOOKBACK_DAYS = 90;
+
+export async function getCodingSessionDigest(
+ auth: CodingAgentAuth,
+ sessionId: string,
+): Promise<CodingSessionDigest | null> {
+ if (!sessionId) return null;
+
+ const sid = escape(sessionId);
+ const chatScope = `(${CHAT_ID_EXPR}) = '${sid}'`;
+ // The 90-day lookback bounds the worst-case full-history scan.
+ // Coupled with the deterministic SpanID, a session's spans land
+ // within a tight window anyway — the digest filters them out
+ // via chatScope. The lookback is intentionally generous so a
+ // long-running chat resumed weeks later still resolves.
+ const lookbackClause = `AND Timestamp >= now() - INTERVAL ${SESSION_DIGEST_LOOKBACK_DAYS} DAY`;
+ // We reuse the same greatest(rollup-attr, per-edit-sum) dual-source
+ // pattern as `SESSION_BASE_COLUMNS` so this digest can never
+ // disagree with the Sessions list or the full session detail
+ // view — Codex (no SessionEnd hook) and in-flight sessions fall
+ // back to the per-edit-span sums, completed Cursor/Claude Code
+ // sessions use the session-rollup attribute. See the long
+ // comment at line ~509 for the rationale.
+ //
+ // We also project the session owner via USER_EXPR so we can run
+ // the cohort-floor check below without a second user-resolution
+ // query. The route comment promised privacy enforcement; this
+ // makes it actually true.
+ const query = `
+ SELECT
+ ${CHAT_ID_EXPR} AS session_id,
+ ${USER_EXPR} AS user,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesAdded}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ ))
+ ) AS lines_added,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesRemoved}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesRemoved}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ ))
+ ) AS lines_removed,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesAccepted}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS lines_accepted,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesRejected}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ ) AS lines_rejected,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditAcceptCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS edit_accept_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditRejectCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ ) AS edit_reject_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionCommitCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_GIT_COMMIT}'))
+ ) AS commit_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionPrCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_GIT_PR}'))
+ ) AS pr_count,
+ -- Session-level usage rollups. Mirrors SESSION_BASE_COLUMNS
+ -- so the trace-detail header reads exactly what the
+ -- Sessions list shows for the same session_id. The dedupe
+ -- (anyIf-root, sumIf-non-root) is critical: the session
+ -- root carries gen_ai.usage.* per OTel GenAI conventions
+ -- AND every llm.turn child does the same, so a naive sum
+ -- across all spans double-counts ended sessions.
+ coalesce(
+ nullIf(toFloat64OrZero(anyIf(
+ SpanAttributes['${CODING_AGENT_ATTR.sessionCostUsd}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toFloat64OrZero(SpanAttributes['${GEN_AI_ATTR.usageCost}']),
+ 0
+ ))
+ ) AS cost_usd,
+ toInt64(coalesce(
+ nullIf(toInt64OrZero(anyIf(
+ SpanAttributes['${GEN_AI_ATTR.usageInputTokens}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']),
+ 0
+ ))
+ )) AS input_tokens,
+ toInt64(coalesce(
+ nullIf(toInt64OrZero(anyIf(
+ SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}']),
+ 0
+ ))
+ )) AS output_tokens,
+ toInt64(coalesce(
+ nullIf(toInt64OrZero(anyIf(
+ SpanAttributes['${GEN_AI_ATTR.usageTotalTokens}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}']),
+ 0
+ ))
+ )) AS total_tokens,
+ -- Wall-clock session duration. Same shape as Sessions row:
+ -- prefer the SessionEnd-stamped duration; fall back to
+ -- (max - min) Timestamp across spans for in-flight
+ -- sessions where SessionEnd hasn't fired yet. No
+ -- double-count risk here (any() + max-min, not a sum).
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionDurationMs}'])),
+ toInt64(toUnixTimestamp64Milli(max(Timestamp)) - toUnixTimestamp64Milli(min(Timestamp)))
+ ) AS duration_ms,
+ -- Predominant model: the latest non-empty
+ -- gen_ai.request.model across the session's child spans.
+ -- argMax picks the most recent value by Timestamp so a
+ -- model swap mid-session reflects the latest.
+ argMaxIf(
+ SpanAttributes['${GEN_AI_ATTR.requestModel}'],
+ Timestamp,
+ notEmpty(SpanAttributes['${GEN_AI_ATTR.requestModel}'])
+ ) AS model,
+ -- VCS / workspace context: LATEST non-empty value across the
+ -- session. We prefer the span attribute (which carries the
+ -- per-turn/live value — e.g. Cursor's git_branch payload and
+ -- Claude Code's transcript gitBranch) and only fall back to
+ -- the resource attribute (the per-process session-start
+ -- snapshot) when no span ever stamped one. argMaxIf keeps the
+ -- most recent value by Timestamp so a mid-session branch /
+ -- repo / folder change wins over the chronologically-first
+ -- span the detail view opens on.
+ coalesce(
+ nullIf(argMaxIf(SpanAttributes['${VCS_ATTR.repoUrl}'], Timestamp, notEmpty(SpanAttributes['${VCS_ATTR.repoUrl}'])), ''),
+ nullIf(argMaxIf(ResourceAttributes['${VCS_ATTR.repoUrl}'], Timestamp, notEmpty(ResourceAttributes['${VCS_ATTR.repoUrl}'])), ''),
+ ''
+ ) AS repo_url,
+ coalesce(
+ nullIf(argMaxIf(SpanAttributes['${VCS_ATTR.headRef}'], Timestamp, notEmpty(SpanAttributes['${VCS_ATTR.headRef}'])), ''),
+ nullIf(argMaxIf(ResourceAttributes['${VCS_ATTR.headRef}'], Timestamp, notEmpty(ResourceAttributes['${VCS_ATTR.headRef}'])), ''),
+ ''
+ ) AS branch,
+ coalesce(
+ nullIf(argMaxIf(SpanAttributes['code.cwd'], Timestamp, notEmpty(SpanAttributes['code.cwd'])), ''),
+ nullIf(argMaxIf(ResourceAttributes['code.cwd'], Timestamp, notEmpty(ResourceAttributes['code.cwd'])), ''),
+ ''
+ ) AS working_dir,
+ arrayStringConcat(
+ arraySlice(
+ arrayFilter(s -> s != '', splitByChar('/',
+ coalesce(
+ nullIf(argMaxIf(SpanAttributes['code.cwd'], Timestamp, notEmpty(SpanAttributes['code.cwd'])), ''),
+ nullIf(argMaxIf(ResourceAttributes['code.cwd'], Timestamp, notEmpty(ResourceAttributes['code.cwd'])), ''),
+ ''
+ )
+ )),
+ -2
+ ),
+ '/'
+ ) AS working_dir_label
+ FROM ${OTEL_TRACES_TABLE}
+ ${whereScope({ auth })}
+ ${lookbackClause}
+ AND ${chatScope}
+ GROUP BY ${CHAT_ID_EXPR}
+ LIMIT 1
+ `;
+
+ const { data, err } = await dataCollector({ query });
+ if (err) throw err;
+ const row = (data as Array<Record<string, unknown>> | undefined)?.[0];
+ if (!row) return null;
+
+ // Cohort floor enforcement. For non-admin viewers, we suppress
+ // the digest if the session's owner has fewer than
+ // COHORT_K_FLOOR sessions in the same lookback window — the
+ // same rule getCodingUserDigest applies on the per-user page,
+ // extended to the per-session pills so a known session_id
+ // doesn't become a side channel for low-volume users' metrics.
+ // Sessions where we couldn't resolve a user fall through
+ // (nothing identifying to protect).
+ if (auth.role !== "admin") {
+ const ownerRaw = row.user;
+ const owner = typeof ownerRaw === "string" ? ownerRaw : "";
+ if (owner && owner !== "unknown") {
+ const cohortCount = await countUserSessionsForCohort(
+ auth,
+ owner,
+ SESSION_DIGEST_LOOKBACK_DAYS,
+ );
+ if (cohortCount < COHORT_K_FLOOR) {
+ return null;
+ }
+ }
+ }
+
+ const accepts = Number(row.edit_accept_count || 0);
+ const rejects = Number(row.edit_reject_count || 0);
+ const decisions = accepts + rejects;
+ return {
+ session_id: String(row.session_id || sessionId),
+ lines_added: Number(row.lines_added || 0),
+ lines_removed: Number(row.lines_removed || 0),
+ lines_accepted: Number(row.lines_accepted || 0),
+ lines_rejected: Number(row.lines_rejected || 0),
+ edit_accept_count: accepts,
+ edit_reject_count: rejects,
+ commit_count: Number(row.commit_count || 0),
+ pr_count: Number(row.pr_count || 0),
+ acceptance_pct: decisions
+ ? Math.round((accepts * 10000) / decisions) / 100
+ : 0,
+ total_tokens: Number(row.total_tokens || 0),
+ input_tokens: Number(row.input_tokens || 0),
+ output_tokens: Number(row.output_tokens || 0),
+ cost_usd: Number(row.cost_usd || 0),
+ duration_ms: Number(row.duration_ms || 0),
+ model: typeof row.model === "string" ? row.model : "",
+ repo_url: typeof row.repo_url === "string" ? row.repo_url : "",
+ branch: typeof row.branch === "string" ? row.branch : "",
+ working_dir: typeof row.working_dir === "string" ? row.working_dir : "",
+ working_dir_label:
+ typeof row.working_dir_label === "string" ? row.working_dir_label : "",
+ };
+}
+
+// countUserSessionsForCohort returns the number of distinct
+// coding-agent sessions a user owned in the trailing `windowDays`.
+// Used solely to gate getCodingSessionDigest behind COHORT_K_FLOOR
+// for non-admin viewers. Kept intentionally narrow — same expression
+// chain as USER_EXPR / CHAT_ID_EXPR so it agrees with what the rest
+// of the platform considers "the same user / the same session".
+async function countUserSessionsForCohort(
+ auth: CodingAgentAuth,
+ userName: string,
+ windowDays: number,
+): Promise<number> {
+ const safeUser = escape(userName);
+ const lookback = `AND Timestamp >= now() - INTERVAL ${windowDays} DAY`;
+ const query = `
+ SELECT toInt64(count()) AS sessions
+ FROM (
+ SELECT ${CHAT_ID_EXPR} AS sid
+ FROM ${OTEL_TRACES_TABLE}
+ ${whereScope({ auth })}
+ ${lookback}
+ GROUP BY ${CHAT_ID_EXPR}, ${PER_SPAN_VENDOR_EXPR}
+ HAVING ${USER_EXPR} = '${safeUser}'
+ )
+ `;
+ const { data, err } = await dataCollector({ query });
+ if (err) {
+ // On error, fail closed: treat as below-floor for safety.
+ // A spurious 404 is preferable to leaking the digest.
+ console.error("coding_agent.session.cohort_lookup_failed", err);
+ return 0;
+ }
+ const rows = data as Array<{ sessions?: number | string }> | undefined;
+ return Number(rows?.[0]?.sessions ?? 0);
+}
+
+export interface CodingUserDigest {
+ user: string;
+ first_seen: string;
+ last_seen: string;
+ session_count: number;
+ tool_call_count: number;
+ cost_usd: number;
+ classification_work: number;
+ classification_personal: number;
+ classification_unknown: number;
+ classification_disputed: number;
+ top_vendors: Array<{ vendor: string; sessions: number }>;
+ // Per-user code-change rollups, summed across the user's
+ // sessions in the working window. `acceptance_pct` is computed
+ // at digest time from accepted / (accepted + rejected); 0 when
+ // both are zero so the dashboard renders "—" instead of NaN.
+ lines_added: number;
+ lines_removed: number;
+ lines_accepted: number;
+ lines_rejected: number;
+ edit_accept_count: number;
+ edit_reject_count: number;
+ acceptance_pct: number;
+ commit_count: number;
+ pr_count: number;
+}
+
+export interface CodingUserRow {
+ user: string;
+ last_seen: string;
+ session_count: number;
+ tool_call_count: number;
+ cost_usd: number;
+ // Sum of input + output gen_ai tokens across the user's sessions.
+ // Used by the directory's "tokens" sort and surfaced as a token
+ // chip on the row.
+ total_tokens: number;
+ top_vendor: string;
+ classification_work: number;
+ classification_personal: number;
+ // Per-user code-change rollups. Same `greatest(rollup, sum)`
+ // dual-source pattern used in the Sessions list — the digest
+ // only diverges in that it sums across all of the user's
+ // sessions instead of one.
+ lines_added: number;
+ lines_accepted: number;
+ lines_rejected: number;
+ acceptance_pct: number;
+ commit_count: number;
+ pr_count: number;
+}
+
+/**
+ * Sort modes the Users directory exposes. The wire format matches
+ * what `<CodingUsersTab>` sends in `runFilters.sortBy`.
+ */
+export type CodingUsersSortBy =
+ | "last_seen"
+ | "sessions"
+ | "tool_calls"
+ | "cost"
+ | "tokens"
+ | "work";
+
+interface UserDigestOptions {
+ since?: Date | null;
+ until?: Date | null;
+}
+
+/**
+ * Build a single user's roll-up suitable for the per-user page header.
+ * Respects the cohort floor — when the requested user has fewer than
+ * COHORT_K_FLOOR sessions and the caller is not an admin, we return
+ * `null` so the route can render a 404. We deliberately do NOT mask
+ * the user as "low_cohort" here because the caller already knows the
+ * exact user id; rendering a digest for it would defeat the floor.
+ */
+export async function getCodingUserDigest(
+ auth: CodingAgentAuth,
+ userName: string,
+ opts: UserDigestOptions = {}
+): Promise<CodingUserDigest | null> {
+ if (!userName) return null;
+ const safeUser = escape(userName);
+
+ // Match the row by the same coalesced user expression the
+ // projector uses, so we find users keyed by the request-user or
+ // service-name fallback in addition to the canonical user.name.
+ // We do this by aggregating once per chat (= parent_id ?? session_id),
+ // computing the user using USER_EXPR, then keeping rows where it
+ // matches. Grouping by CHAT_ID_EXPR rather than raw session_id is
+ // what listSessions / listCodingUsers / the dashboard widgets do,
+ // so the per-user header card agrees with all of them — previously
+ // subagent spawns inflated this digest's session_count vs the list.
+ //
+ // IMPORTANT: we materialize the per-session aggregation as a
+ // subquery, NOT a `WITH per_session AS (...)` CTE. ClickHouse's
+ // CTE inliner aggressively collapses `WITH ... AS` into the outer
+ // SELECT, which then exposes the inner aggregates (greatest(any(),
+ // countIf()) and friends) as direct arguments of the outer
+ // sumOrNull / countIf / argMax calls. The planner correctly
+ // rejects that as "aggregate inside aggregate". The sibling
+ // `listCodingUsers` function ran into the same trap — see the
+ // extended comment at the top of `baseSubquery` for the full
+ // playbook. Wrapping the inner SELECT in a subquery keeps the
+ // plan opaque and lets the outer aggregates run against
+ // pre-materialised columns.
+ const sessionsSubquery = `
+ (
+ SELECT
+ ${CHAT_ID_EXPR} AS sid,
+ ${USER_EXPR} AS user,
+ min(Timestamp) AS first_seen,
+ max(Timestamp) AS last_seen,
+ countIf(SpanName = '${CODING_AGENT_SPAN_TOOL_CALL}') AS tool_calls,
+ -- Canonical per-session cost. Mirrors the dedupe in
+ -- SESSION_BASE_COLUMNS: prefer the authoritative
+ -- root rollup; only sum **child** turn spans
+ -- otherwise. Naively summing across all spans
+ -- double-counts ended sessions because the root
+ -- also carries gen_ai.usage.cost per OTel GenAI
+ -- conventions.
+ coalesce(
+ nullIf(toFloat64OrZero(anyIf(
+ SpanAttributes['${CODING_AGENT_ATTR.sessionCostUsd}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toFloat64OrZero(SpanAttributes['${GEN_AI_ATTR.usageCost}']),
+ 0
+ ))
+ ) AS cost,
+ -- Per-session code-change rollups. The same
+ -- greatest(rollup-attr, per-edit-sum) dual-source
+ -- pattern the Sessions list uses; see the
+ -- SESSION_BASE_COLUMNS comment for the full
+ -- rationale (Codex / in-flight sessions).
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesAdded}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ ))
+ ) AS lines_added,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesRemoved}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesRemoved}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ ))
+ ) AS lines_removed,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesAccepted}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS lines_accepted,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesRejected}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ ) AS lines_rejected,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditAcceptCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS edit_accept_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditRejectCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ ) AS edit_reject_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionCommitCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_GIT_COMMIT}'))
+ ) AS commit_count,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionPrCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_GIT_PR}'))
+ ) AS pr_count,
+ coalesce(nullIf(any(SpanAttributes['${CODING_AGENT_ATTR.userClassification}']), ''), 'unknown') AS classification,
+ ${VENDOR_EXPR} AS vendor
+ FROM ${OTEL_TRACES_TABLE}
+ ${whereScope({
+ since: opts.since ?? null,
+ until: opts.until ?? null,
+ auth,
+ })}
+ GROUP BY ${CHAT_ID_EXPR}, ${PER_SPAN_VENDOR_EXPR}
+ )
+ `;
+
+ // Two-stage aggregation. The inner SELECT does ALL the aggregate
+ // work and the outer SELECT only does scalar arithmetic on its
+ // columns. Why split it: ClickHouse 24.x resolves a bare
+ // `edit_accept_count` inside the outer SELECT to the aliased
+ // expression `sumOrNull(edit_accept_count) AS edit_accept_count`
+ // if the alias was declared on the same row (default
+ // `prefer_column_name_to_alias=0`). That turns
+ // `if(... sumOrNull(edit_accept_count) ...)` into
+ // `if(... sumOrNull(sumOrNull(edit_accept_count)) ...)`, which
+ // the planner correctly rejects as a nested aggregate. Putting
+ // the aggregates one layer down dodges the alias shadowing
+ // entirely and keeps the outer SELECT pure scalar.
+ const digestQuery = `
+ SELECT
+ user,
+ first_seen,
+ last_seen,
+ session_count,
+ tool_call_count,
+ cost_usd,
+ classification_work,
+ classification_personal,
+ classification_disputed,
+ classification_unknown,
+ lines_added,
+ lines_removed,
+ lines_accepted,
+ lines_rejected,
+ edit_accept_count,
+ edit_reject_count,
+ commit_count,
+ pr_count,
+ if(
+ (edit_accept_count + edit_reject_count) = 0,
+ toFloat64(0),
+ round(
+ toFloat64(edit_accept_count) * 100 /
+ toFloat64(edit_accept_count + edit_reject_count),
+ 2
+ )
+ ) AS acceptance_pct
+ FROM (
+ SELECT
+ '${safeUser}' AS user,
+ formatDateTime(min(first_seen), '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS first_seen,
+ formatDateTime(max(last_seen), '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS last_seen,
+ toInt64(count()) AS session_count,
+ toInt64(sum(tool_calls)) AS tool_call_count,
+ round(sumOrNull(cost), 4) AS cost_usd,
+ toInt64(countIf(classification = 'work')) AS classification_work,
+ toInt64(countIf(classification = 'personal')) AS classification_personal,
+ toInt64(countIf(classification = 'disputed')) AS classification_disputed,
+ toInt64(countIf(classification = 'unknown')) AS classification_unknown,
+ toInt64(sumOrNull(lines_added)) AS lines_added,
+ toInt64(sumOrNull(lines_removed)) AS lines_removed,
+ toInt64(sumOrNull(lines_accepted)) AS lines_accepted,
+ toInt64(sumOrNull(lines_rejected)) AS lines_rejected,
+ toInt64(sumOrNull(edit_accept_count)) AS edit_accept_count,
+ toInt64(sumOrNull(edit_reject_count)) AS edit_reject_count,
+ toInt64(sumOrNull(commit_count)) AS commit_count,
+ toInt64(sumOrNull(pr_count)) AS pr_count
+ FROM ${sessionsSubquery} AS per_session
+ WHERE user = '${safeUser}'
+ ) totals
+ `;
+
+ const vendorsQuery = `
+ SELECT vendor, toInt64(count()) AS sessions
+ FROM ${sessionsSubquery} AS per_session
+ WHERE user = '${safeUser}'
+ GROUP BY vendor
+ HAVING vendor != '' AND vendor != 'unknown'
+ ORDER BY sessions DESC
+ LIMIT 5
+ `;
+
+ const [{ data: digestData, err: digestErr }, { data: vendorsData }] =
+ await Promise.all([
+ dataCollector({ query: digestQuery }),
+ dataCollector({ query: vendorsQuery }),
+ ]);
+ if (digestErr) throw digestErr;
+ const digestRow = (digestData as CodingUserDigest[] | undefined)?.[0];
+ if (!digestRow || !Number(digestRow.session_count)) return null;
+
+ const sessionCount = Number(digestRow.session_count || 0);
+ if (auth.role !== "admin" && sessionCount < COHORT_K_FLOOR) {
+ // Privacy floor — don't reveal a profile for a user who barely
+ // shows up. Treated as "not found" by the route.
+ return null;
+ }
+
+ return {
+ ...digestRow,
+ session_count: sessionCount,
+ tool_call_count: Number(digestRow.tool_call_count || 0),
+ cost_usd: Number(digestRow.cost_usd || 0),
+ classification_work: Number(digestRow.classification_work || 0),
+ classification_personal: Number(digestRow.classification_personal || 0),
+ classification_unknown: Number(digestRow.classification_unknown || 0),
+ classification_disputed: Number(digestRow.classification_disputed || 0),
+ lines_added: Number(digestRow.lines_added || 0),
+ lines_removed: Number(digestRow.lines_removed || 0),
+ lines_accepted: Number(digestRow.lines_accepted || 0),
+ lines_rejected: Number(digestRow.lines_rejected || 0),
+ edit_accept_count: Number(digestRow.edit_accept_count || 0),
+ edit_reject_count: Number(digestRow.edit_reject_count || 0),
+ commit_count: Number(digestRow.commit_count || 0),
+ pr_count: Number(digestRow.pr_count || 0),
+ acceptance_pct: Number(digestRow.acceptance_pct || 0),
+ top_vendors: ((vendorsData as Array<{ vendor: string; sessions: number | string }>) || []).map(
+ (row) => ({
+ vendor: row.vendor,
+ sessions: Number(row.sessions || 0),
+ })
+ ),
+ };
+}
+
+/**
+ * Org-wide list of coding-agent users. The directory tab uses this; we
+ * apply the same cohort floor — users below COHORT_K_FLOOR are
+ * collapsed into a single `low_cohort` row when the viewer isn't admin
+ * (matches the behavior of the sessions list).
+ */
+export interface ListCodingUsersOptions {
+ limit?: number;
+ offset?: number;
+ since?: Date | null;
+ until?: Date | null;
+ vendor?: string | null;
+ withTotal?: boolean;
+ sortBy?: CodingUsersSortBy;
+ sortDir?: "asc" | "desc";
+}
+
+// Maps the user-facing `sortBy` enum to the column expression in the
+// `users_raw` CTE. Centralised so it stays in lock-step with the
+// SELECT clause.
+const USERS_SORT_COLUMNS: Record<CodingUsersSortBy, string> = {
+ last_seen: "last_seen",
+ sessions: "session_count",
+ tool_calls: "tool_call_count",
+ cost: "cost_usd",
+ tokens: "total_tokens",
+ work: "classification_work",
+};
+
+export async function listCodingUsers(
+ auth: CodingAgentAuth,
+ opts: ListCodingUsersOptions = {}
+): Promise<{ rows: CodingUserRow[]; total: number | null }> {
+ const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
+ const offset = Math.max(opts.offset ?? 0, 0);
+ const vendorClause = opts.vendor
+ ? `AND vendor = '${escape(opts.vendor)}'`
+ : "";
+
+ const sortBy: CodingUsersSortBy = opts.sortBy || "last_seen";
+ const sortDir = opts.sortDir === "asc" ? "ASC" : "DESC";
+ const orderColumn = USERS_SORT_COLUMNS[sortBy] || "last_seen";
+ // Always tie-break by last_seen so "0 sessions" rows don't shuffle
+ // arbitrarily between requests.
+ const orderClause = `ORDER BY ${orderColumn} ${sortDir}, last_seen DESC`;
+
+ // Cohort floor applied IN SQL for non-admins. Previously this ran
+ // after LIMIT/OFFSET in JS, which meant low-volume users could
+ // land on page 1 then collapse into `low_cohort` after, skewing
+ // totals + pagination. Doing it inside the CTE keeps the page,
+ // total, and sort order consistent for the viewer.
+ const isAdmin = auth.role === "admin";
+ const cohortProjectExpr = isAdmin
+ ? "user"
+ : `if(session_count < ${COHORT_K_FLOOR} AND user NOT IN ('unknown', ''), 'low_cohort', user)`;
+
+ // Two-stage CTE: compute one row per chat thread with the coalesced
+ // user/vendor identity, then aggregate by user. We bucket by
+ // chat_id (= parent_id when this is a subagent, else session_id)
+ // so a parent + N subagents counts as ONE session for the user,
+ // matching what the Sessions list shows them.
+ // Implementation note: ClickHouse inlines `WITH ... AS` CTEs and
+ // then bans aggregate-inside-aggregate (`max(formatDateTime(max(...)))`,
+ // `argMax(top_vendor, max(last_ts))`). We dodge this by:
+ // 1. Carrying the raw `max(Timestamp)` through as a plain
+ // DateTime column (`*_last_ts`) and only formatting at the
+ // outermost SELECT.
+ // 2. Aliasing each layer's aggregates with distinct names so the
+ // inliner can't collapse them into nested aggregates.
+ // 3. Using subqueries instead of `WITH` so the plan stays
+ // explicit even on older ClickHouse versions that inline
+ // aggressively.
+ // The cohort collapse stays in SQL so it applies *before* LIMIT —
+ // otherwise low-volume users could land on page 1 then disappear
+ // after JS masking, breaking pagination.
+ const baseSubquery = `
+ FROM (
+ SELECT
+ ${cohortProjectExpr} AS user,
+ max(per_user_last_ts) AS user_last_ts,
+ toInt64(sum(per_user_session_count)) AS session_count,
+ toInt64(sum(per_user_tool_calls)) AS tool_call_count,
+ round(sumOrNull(per_user_cost), 4) AS cost_usd,
+ toInt64(sum(per_user_tokens)) AS total_tokens,
+ argMax(per_user_top_vendor, per_user_last_ts) AS top_vendor,
+ toInt64(sum(per_user_class_work)) AS classification_work,
+ toInt64(sum(per_user_class_personal)) AS classification_personal,
+ toInt64(sum(per_user_lines_added)) AS lines_added,
+ toInt64(sum(per_user_lines_accepted)) AS lines_accepted,
+ toInt64(sum(per_user_lines_rejected)) AS lines_rejected,
+ toInt64(sum(per_user_edit_accept)) AS edit_accept_count,
+ toInt64(sum(per_user_edit_reject)) AS edit_reject_count,
+ toInt64(sum(per_user_commits)) AS commit_count,
+ toInt64(sum(per_user_prs)) AS pr_count
+ FROM (
+ SELECT
+ user AS user,
+ max(session_last_ts) AS per_user_last_ts,
+ toInt64(count()) AS per_user_session_count,
+ toInt64(sum(tool_calls)) AS per_user_tool_calls,
+ round(sumOrNull(cost), 4) AS per_user_cost,
+ toInt64(sumOrNull(tokens)) AS per_user_tokens,
+ argMax(vendor, session_last_ts) AS per_user_top_vendor,
+ toInt64(countIf(classification = 'work')) AS per_user_class_work,
+ toInt64(countIf(classification = 'personal')) AS per_user_class_personal,
+ toInt64(sumOrNull(lines_added)) AS per_user_lines_added,
+ toInt64(sumOrNull(lines_accepted)) AS per_user_lines_accepted,
+ toInt64(sumOrNull(lines_rejected)) AS per_user_lines_rejected,
+ toInt64(sumOrNull(edit_accept)) AS per_user_edit_accept,
+ toInt64(sumOrNull(edit_reject)) AS per_user_edit_reject,
+ toInt64(sumOrNull(commits)) AS per_user_commits,
+ toInt64(sumOrNull(prs)) AS per_user_prs
+ FROM (
+ SELECT
+ ${CHAT_ID_EXPR} AS sid,
+ ${USER_EXPR} AS user,
+ ${VENDOR_EXPR} AS vendor,
+ max(Timestamp) AS session_last_ts,
+ countIf(SpanName = '${CODING_AGENT_SPAN_TOOL_CALL}') AS tool_calls,
+ -- Canonical per-session cost: same dedupe as
+ -- listSessions / getCodingUserDigest. Without
+ -- this the Users tab would silently lag
+ -- behind the authoritative session-end total
+ -- AND double-count ended sessions (root +
+ -- per-turn both carry gen_ai.usage.cost per
+ -- OTel GenAI conventions).
+ coalesce(
+ nullIf(toFloat64OrZero(anyIf(
+ SpanAttributes['${CODING_AGENT_ATTR.sessionCostUsd}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toFloat64OrZero(SpanAttributes['${GEN_AI_ATTR.usageCost}']),
+ 0
+ ))
+ ) AS cost,
+ -- Tokens: same dedupe as cost (root carries
+ -- gen_ai.usage.*_tokens at SessionEnd; child
+ -- turn spans carry per-turn counts).
+ coalesce(
+ nullIf(toInt64OrZero(anyIf(
+ SpanAttributes['${GEN_AI_ATTR.usageTotalTokens}'],
+ SpanName = '${CODING_AGENT_SPAN_SESSION}'
+ )), 0),
+ sumOrNull(if(
+ SpanName != '${CODING_AGENT_SPAN_SESSION}',
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}']),
+ 0
+ ))
+ ) AS tokens,
+ -- Per-session code-change rollups (same
+ -- dual-source pattern as listSessions /
+ -- getCodingUserDigest). The user-list page
+ -- only renders summed metrics, so we don't
+ -- emit lines_removed here.
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesAdded}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ ))
+ ) AS lines_added,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesAccepted}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS lines_accepted,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionLinesRejected}'])),
+ toInt64(sumIf(
+ toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.editLinesAdded}']),
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ ) AS lines_rejected,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditAcceptCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] IN ('accept', 'auto_accepted')
+ ))
+ ) AS edit_accept,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionEditRejectCount}'])),
+ toInt64(countIf(
+ SpanName = '${CODING_AGENT_SPAN_EDIT_DECISION}'
+ AND SpanAttributes['${CODING_AGENT_ATTR.editDecision}'] = 'reject'
+ ))
+ ) AS edit_reject,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionCommitCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_GIT_COMMIT}'))
+ ) AS commits,
+ greatest(
+ toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionPrCount}'])),
+ toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_GIT_PR}'))
+ ) AS prs,
+ coalesce(nullIf(any(SpanAttributes['${CODING_AGENT_ATTR.userClassification}']), ''), 'unknown') AS classification
+ FROM ${OTEL_TRACES_TABLE}
+ ${whereScope({
+ since: opts.since ?? null,
+ until: opts.until ?? null,
+ auth,
+ })}
+ GROUP BY sid, ${PER_SPAN_VENDOR_EXPR}
+ ) per_session
+ WHERE user != ''
+ ${vendorClause}
+ GROUP BY user
+ HAVING user != ''
+ ) per_user
+ GROUP BY 1
+ ) users_raw
+ `;
+
+ // users_raw exposes user_last_ts as a raw DateTime; format here so
+ // the ORDER BY can still sort on the raw column without triggering
+ // nested aggregates in the planner.
+ const dataQuery = `
+ SELECT
+ user,
+ formatDateTime(user_last_ts, '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS last_seen,
+ session_count,
+ tool_call_count,
+ cost_usd,
+ total_tokens,
+ top_vendor,
+ classification_work,
+ classification_personal,
+ lines_added,
+ lines_accepted,
+ lines_rejected,
+ commit_count,
+ pr_count,
+ if(
+ (edit_accept_count + edit_reject_count) = 0,
+ toFloat64(0),
+ round(toFloat64(edit_accept_count) * 100 / toFloat64(edit_accept_count + edit_reject_count), 2)
+ ) AS acceptance_pct
+ ${baseSubquery}
+ ${orderClause.replace(/last_seen/g, "user_last_ts")}
+ LIMIT ${limit}
+ OFFSET ${offset}
+ `;
+
+ const totalPromise = opts.withTotal
+ ? dataCollector({
+ query: `SELECT toInt64(count()) AS total ${baseSubquery}`,
+ })
+ : Promise.resolve({ data: [] as Array<{ total: number }>, err: null });
+
+ const [{ data, err }, { data: totalData }] = await Promise.all([
+ dataCollector({ query: dataQuery }),
+ totalPromise,
+ ]);
+ if (err) throw err;
+
+ // Cohort floor is applied in SQL above; we just normalize types.
+ const rows = ((data as CodingUserRow[]) || []).map((row) => ({
+ ...row,
+ session_count: Number(row.session_count || 0),
+ tool_call_count: Number(row.tool_call_count || 0),
+ cost_usd: Number(row.cost_usd || 0),
+ total_tokens: Number(row.total_tokens || 0),
+ classification_work: Number(row.classification_work || 0),
+ classification_personal: Number(row.classification_personal || 0),
+ lines_added: Number(row.lines_added || 0),
+ lines_accepted: Number(row.lines_accepted || 0),
+ lines_rejected: Number(row.lines_rejected || 0),
+ acceptance_pct: Number(row.acceptance_pct || 0),
+ commit_count: Number(row.commit_count || 0),
+ pr_count: Number(row.pr_count || 0),
+ }));
+
+ const totalRow = (totalData as Array<{ total: number | string }>) ?? [];
+ const total = opts.withTotal ? Number(totalRow[0]?.total ?? 0) : null;
+
+ return { rows, total };
+}
+
+/**
+ * Replace `user` with the literal "low_cohort" when the user shows up
+ * fewer than COHORT_K_FLOOR times in the working window AND the
+ * caller is not an admin. Admin can always see the raw value (the
+ * audit log captures the access).
+ *
+ * Phase B3: the cohort window is bounded to the same `since`/`until`
+ * the caller asked about (default: 24h). Previously this scanned all
+ * of `otel_traces` which was both a privacy hazard (users active a
+ * month ago could be re-identified by a recent session) and a scale
+ * cost (full-table scan per list page).
+ *
+ * For v1 we run a single rollup count query once per call rather
+ * than per-row to keep latency down.
+ */
+async function applyCohortFloor<T extends { user: string }>(
+ auth: CodingAgentAuth,
+ rows: T[],
+ opts: { since?: Date | null; until?: Date | null } = {}
+): Promise<T[]> {
+ if (auth.role === "admin" || rows.length === 0) return rows;
+
+ // Distinct user values to look up. We also exclude the
+ // "unknown" sentinel — it's already a privacy bucket; suppressing
+ // it further would just hide all rows for orgs whose CLI is
+ // pre-user-emit. Admin still sees raw rows above.
+ const distinctUsers = Array.from(
+ new Set(
+ rows
+ .map((r) => r.user)
+ .filter((u) => Boolean(u) && u !== "unknown" && u !== "low_cohort")
+ )
+ );
+ if (distinctUsers.length === 0) return rows;
+
+ const inList = distinctUsers.map((u) => `'${escape(u)}'`).join(", ");
+ // We count chat threads, not raw spans, using the SAME chat-id
+ // rollup the projector uses (parent_id → session_id). A user with
+ // 4 small subagents under 1 parent counts as 1 session, matching
+ // what the UI shows them.
+ const query = `
+ WITH per_session AS (
+ SELECT
+ ${USER_EXPR} AS user,
+ ${CHAT_ID_EXPR} AS sid
+ FROM ${OTEL_TRACES_TABLE}
+ ${whereScope({
+ since: opts.since ?? null,
+ until: opts.until ?? null,
+ auth,
+ })}
+ GROUP BY sid, ${PER_SPAN_VENDOR_EXPR}
+ )
+ SELECT user, CAST(count() AS INTEGER) AS sessions
+ FROM per_session
+ WHERE user IN (${inList})
+ GROUP BY user
+ `;
+ const { data, err } = await dataCollector({ query });
+ if (err) throw err;
+ const counts = new Map<string, number>();
+ for (const row of (data || []) as { user: string; sessions: number }[]) {
+ counts.set(row.user, Number(row.sessions || 0));
+ }
+
+ return rows.map((r) => {
+ if (!r.user || r.user === "unknown" || r.user === "low_cohort") return r;
+ const c = counts.get(r.user) ?? 0;
+ if (c < COHORT_K_FLOOR) {
+ return { ...r, user: "low_cohort" } as T;
+ }
+ return r;
+ });
+}
+
+/**
+ * Persist a classification dispute and emit an audit log entry. The
+ * dispute table holds the full lifecycle (open → accepted/rejected/withdrawn);
+ * the audit log captures the submission as a discrete event so we can
+ * paginate "recent governance activity" without scanning the disputes
+ * table.
+ *
+ * Both writes are best-effort sequential: if the audit insert fails
+ * we still keep the dispute (the dispute table is the source of truth
+ * for downstream review), but we log loudly. The reverse — dispute
+ * fail, audit succeed — is rejected up front by throwing the dispute
+ * error before we attempt the audit row.
+ */
+// E4 hardening constants. Numbers are intentionally generous for
+// beta — the goal is to block trivial scripted abuse without
+// throttling legitimate UI activity. Tune downward if we observe
+// abuse in production.
+const DISPUTE_RATE_LIMIT_WINDOW_MIN = 60;
+const DISPUTE_RATE_LIMIT_MAX_PER_WINDOW = 20;
+
+export class DisputeError extends Error {
+ readonly code: "not_found" | "duplicate" | "rate_limited";
+ readonly status: number;
+ constructor(
+ code: DisputeError["code"],
+ status: number,
+ message: string
+ ) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ }
+}
+
+// sessionExists checks whether the chat-id rolled-up
+// session is actually visible. Org scoping is enforced by
+// `dataCollector` picking the per-org ClickHouse database (see
+// `whereScope` for the explanation), so we don't need to wrap the
+// org id in the SQL. We do still constrain to coding-agent span
+// names so a request can't probe arbitrary trace ids.
+async function disputeSessionExists(
+ _auth: CodingAgentAuth,
+ sessionId: string
+): Promise<boolean> {
+ const sid = escape(sessionId);
+ const query = `
+ SELECT 1 AS hit
+ FROM ${OTEL_TRACES_TABLE}
+ WHERE SpanName IN (${CODING_AGENT_SPAN_NAMES.map((n) => `'${n}'`).join(", ")})
+ AND Timestamp >= now() - INTERVAL 90 DAY
+ AND (
+ SpanAttributes['${CODING_AGENT_ATTR.sessionId}'] = '${sid}'
+ OR ${CHAT_ID_EXPR.trim()} = '${sid}'
+ )
+ LIMIT 1
+ `;
+ const { data, err } = await dataCollector({ query });
+ if (err) {
+ // Treat lookup failure as "not present" — better to reject a
+ // dispute than to accept one that points at a non-existent
+ // session and leave the audit log polluted.
+ console.error("coding_agent.dispute.session_lookup_failed", err);
+ return false;
+ }
+ return Array.isArray(data) && data.length > 0;
+}
+
+// disputeAlreadyExists guards against duplicate open disputes from
+// the same user on the same session. We allow resubmission once a
+// previous dispute has been resolved (the admin reviewed and either
+// accepted or rejected it) so users can re-dispute after a policy
+// change, but not while one is still open.
+async function disputeAlreadyExists(
+ auth: CodingAgentAuth,
+ sessionId: string
+): Promise<boolean> {
+ const orgId = escape(auth.organizationId);
+ const userId = escape(auth.userId);
+ const sid = escape(sessionId);
+ const query = `
+ SELECT 1 AS hit
+ FROM ${CODING_AGENT_DISPUTES_TABLE}
+ WHERE organization_id = '${orgId}'
+ AND user_id = '${userId}'
+ AND session_id = '${sid}'
+ AND status = 'open'
+ LIMIT 1
+ `;
+ const { data, err } = await dataCollector({ query });
+ if (err) {
+ // Fail-closed: a lookup failure here means we can't tell if an
+ // open dispute already exists. The cost of a false-positive
+ // ("you already have an open dispute") is one extra click for
+ // the user, but the cost of a false-negative is a duplicate
+ // open dispute that pollutes the audit + governance queues.
+ // Surface as "exists" so the caller blocks the new write.
+ console.error("coding_agent.dispute.dedupe_lookup_failed", err);
+ return true;
+ }
+ return Array.isArray(data) && data.length > 0;
+}
+
+// disputeRateLimitExceeded asks ClickHouse rather than holding
+// in-memory state because the API runs on multiple Next.js workers
+// and an in-memory counter would be per-worker. The audit log is
+// the right place to count from — it's already append-only and
+// indexed on (organization_id, created_at).
+async function disputeRateLimitExceeded(
+ auth: CodingAgentAuth
+): Promise<boolean> {
+ const orgId = escape(auth.organizationId);
+ const userId = escape(auth.userId);
+ const query = `
+ SELECT count() AS n
+ FROM ${CODING_AGENT_AUDIT_LOG_TABLE}
+ WHERE organization_id = '${orgId}'
+ AND user_id = '${userId}'
+ AND action = 'coding_agent.classification.dispute'
+ AND created_at >= now() - INTERVAL ${DISPUTE_RATE_LIMIT_WINDOW_MIN} MINUTE
+ `;
+ const { data, err } = await dataCollector({ query });
+ if (err) {
+ // Fail-closed: a lookup failure must NOT degrade into "no rate
+ // limit applied" — that turns this guard into a bypass-on-error
+ // vector. We reject the new dispute so a temporary ClickHouse
+ // blip can't let a script flood the audit log. The user can
+ // retry once telemetry is back; in practice this fires <0.1%
+ // of submissions.
+ console.error("coding_agent.dispute.rate_limit_lookup_failed", err);
+ return true;
+ }
+ const rows = data as Array<{ n?: number | string }> | undefined;
+ const n = Number(rows?.[0]?.n ?? 0);
+ return n >= DISPUTE_RATE_LIMIT_MAX_PER_WINDOW;
+}
+
+export async function submitClassificationDispute(
+ auth: CodingAgentAuth,
+ input: CodingAgentClassificationDispute
+): Promise<{ id: string }> {
+ // Order matters: existence first (cheap rejection of probes),
+ // dedupe next (prevents flooding the table), rate limit last
+ // (most expensive query, only run if the request is otherwise
+ // valid).
+ const exists = await disputeSessionExists(auth, input.sessionId);
+ if (!exists) {
+ throw new DisputeError(
+ "not_found",
+ 404,
+ "Session does not exist or is outside your access scope"
+ );
+ }
+
+ const duplicate = await disputeAlreadyExists(auth, input.sessionId);
+ if (duplicate) {
+ throw new DisputeError(
+ "duplicate",
+ 409,
+ "An open dispute already exists for this session"
+ );
+ }
+
+ const limited = await disputeRateLimitExceeded(auth);
+ if (limited) {
+ throw new DisputeError(
+ "rate_limited",
+ 429,
+ `Too many disputes in the last ${DISPUTE_RATE_LIMIT_WINDOW_MIN} minutes`
+ );
+ }
+
+ const id = crypto.randomUUID();
+
+ const { err: disputeErr } = await dataCollector(
+ {
+ table: CODING_AGENT_DISPUTES_TABLE,
+ values: [
+ {
+ id,
+ organization_id: auth.organizationId,
+ session_id: input.sessionId,
+ user_id: auth.userId,
+ current_classification: input.currentClassification,
+ requested_classification: input.requestedClassification,
+ rationale: input.rationale,
+ status: "open",
+ },
+ ],
+ },
+ "insert"
+ );
+ if (disputeErr) throw disputeErr;
+
+ await writeAuditLog(auth, {
+ action: "coding_agent.classification.dispute",
+ subject: input.sessionId,
+ payload: JSON.stringify({
+ disputeId: id,
+ from: input.currentClassification,
+ to: input.requestedClassification,
+ }),
+ });
+
+ return { id };
+}
+
+export async function writeAuditLog(
+ auth: CodingAgentAuth,
+ entry: { action: string; subject?: string; payload?: string }
+): Promise<void> {
+ const { err } = await dataCollector(
+ {
+ table: CODING_AGENT_AUDIT_LOG_TABLE,
+ values: [
+ {
+ organization_id: auth.organizationId,
+ user_id: auth.userId,
+ action: entry.action,
+ subject: entry.subject || "",
+ payload: entry.payload || "",
+ },
+ ],
+ },
+ "insert"
+ );
+ if (err) {
+ // We don't throw on audit failure — the user-visible action
+ // already succeeded, and surfacing a 500 here would falsely
+ // imply data loss. Instead we surface to server logs so SRE
+ // can detect and replay.
+ console.error("coding_agent.audit_log.insert_failed", err);
+ }
+}
+
diff --git a/src/client/src/lib/platform/coding-agents/query-builders.ts b/src/client/src/lib/platform/coding-agents/query-builders.ts
new file mode 100644
index 00000000..7d1c4634
--- /dev/null
+++ b/src/client/src/lib/platform/coding-agents/query-builders.ts
@@ -0,0 +1,86 @@
+/**
+ * Pure SQL-builder helpers for the coding-agents query layer.
+ *
+ * This file is split out from `queries.ts` so the helpers can be
+ * unit-tested without importing the database / session / auth
+ * surface that the runtime callers depend on. Anything in here
+ * must remain dependency-free of:
+ *
+ * - `next-auth` (pulls in openid-client during jest module init)
+ * - the ClickHouse client / db-config plumbing
+ * - any browser-only utilities
+ *
+ * If you're adding a function with side effects (e.g. it runs a
+ * query) it belongs in `queries.ts`, not here.
+ */
+
+/**
+ * escape encodes a string for safe interpolation into a single-
+ * quoted ClickHouse literal. We escape backslashes first (so the
+ * later apostrophe substitution doesn't double-escape its own
+ * output) and then escape single quotes with a backslash, matching
+ * the historical helper that lived inline in `queries.ts`.
+ *
+ * Callers should still prefer parameterized query helpers wherever
+ * they exist — this escape is the floor, not the ceiling.
+ */
+export function escape(value: string): string {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
+/**
+ * SessionsHavingOptions is the narrow shape of the options object
+ * that `buildSessionsHaving` cares about. We don't import the full
+ * `ListSessionsOptions` to keep this file dependency-free; the
+ * runtime caller passes the full struct and we only read the
+ * filter-relevant subset.
+ *
+ * The string fields accept `null` as well as `undefined` because
+ * the real `ListSessionsOptions` in `queries.ts` is sourced from
+ * URL search params that explicitly pass `null` to mean "no
+ * filter" (the API request layer treats `undefined` as
+ * "untouched"). Narrowing to `string | undefined` here would
+ * force every caller into a `?? undefined` dance and was the
+ * source of the docker-build typecheck regression that prompted
+ * this comment.
+ */
+export interface SessionsHavingOptions {
+ vendor?: string | null;
+ user?: string | null;
+ classification?: string | null;
+ includeSubagents?: boolean;
+}
+
+/**
+ * buildSessionsHaving composes the HAVING clause for `listSessions`'s
+ * post-aggregation filter set.
+ *
+ * Filters are applied AFTER aggregation so the coalesced
+ * vendor/user values are filtered correctly (the same coalesce
+ * chain that produces the row is what we filter on). This avoids
+ * a regression where filtering on user='alice' rejected rows
+ * where alice's identity only lived on `user.email` or fell
+ * through to the `service.name` fallback.
+ */
+export function buildSessionsHaving(opts: SessionsHavingOptions): string {
+ const havingClauses: string[] = [];
+ if (opts.vendor) {
+ havingClauses.push(`vendor = '${escape(opts.vendor)}'`);
+ }
+ if (opts.user) {
+ havingClauses.push(`user = '${escape(opts.user)}'`);
+ }
+ if (opts.classification) {
+ havingClauses.push(`classification = '${escape(opts.classification)}'`);
+ }
+ // Hide subagent rows by default: they fold under the parent chat
+ // via CHAT_ID_EXPR; listing them at the top level produces
+ // duplicate-looking rows for one user-perceived chat. Callers
+ // debugging linkage gaps can opt back in.
+ if (!opts.includeSubagents) {
+ havingClauses.push(`is_subagent = 0`);
+ }
+ return havingClauses.length
+ ? `HAVING ${havingClauses.join(" AND ")}`
+ : "";
+}
diff --git a/src/client/src/lib/platform/coding-agents/table-details.ts b/src/client/src/lib/platform/coding-agents/table-details.ts
new file mode 100644
index 00000000..6d144120
--- /dev/null
+++ b/src/client/src/lib/platform/coding-agents/table-details.ts
@@ -0,0 +1,124 @@
+/**
+ * Coding-agent ClickHouse table/column references.
+ *
+ * Coding-agent telemetry rides the existing `otel_traces` pipeline. We
+ * keep dedicated constants here (rather than scatter literal strings
+ * across queries) so renames or schema bumps stay localized.
+ */
+
+export const OTEL_TRACES_TABLE = "otel_traces";
+
+/**
+ * Span names emitted by the openlit CLI normalizer (mirrors
+ * sdk/go/semconv/coding_agent.go::CodingAgentSpan*). Dashboards and
+ * APIs filter on these so they never accidentally pull in non-coding
+ * gen_ai traffic.
+ */
+export const CODING_AGENT_SPAN_SESSION = "coding_agent.session";
+export const CODING_AGENT_SPAN_TOOL_CALL = "coding_agent.tool.call";
+export const CODING_AGENT_SPAN_EDIT_DECISION = "coding_agent.edit.decision";
+export const CODING_AGENT_SPAN_SUBAGENT = "coding_agent.subagent";
+export const CODING_AGENT_SPAN_LLM_TURN = "coding_agent.llm.turn";
+export const CODING_AGENT_SPAN_GIT_COMMIT = "coding_agent.git.commit";
+export const CODING_AGENT_SPAN_GIT_PR = "coding_agent.git.pull_request";
+
+/** All coding-agent span names in a single tuple — handy for `IN (...)` clauses. */
+export const CODING_AGENT_SPAN_NAMES = [
+ CODING_AGENT_SPAN_SESSION,
+ CODING_AGENT_SPAN_TOOL_CALL,
+ CODING_AGENT_SPAN_EDIT_DECISION,
+ CODING_AGENT_SPAN_SUBAGENT,
+ CODING_AGENT_SPAN_LLM_TURN,
+ CODING_AGENT_SPAN_GIT_COMMIT,
+ CODING_AGENT_SPAN_GIT_PR,
+] as const;
+
+/**
+ * Frequently-read attribute keys. These align 1:1 with constants in
+ * `sdk/go/semconv/coding_agent.go` so the wire-format is the only
+ * source of truth. Update in lockstep when bumping the schema.
+ */
+export const CODING_AGENT_ATTR = {
+ sessionId: "coding_agent.session.id",
+ client: "coding_agent.client",
+ clientVersion: "coding_agent.client.version",
+ sessionOutcome: "coding_agent.session.outcome",
+ sessionDurationMs: "coding_agent.session.duration_ms",
+ sessionToolCallCount: "coding_agent.session.tool_call_count",
+ sessionCostUsd: "coding_agent.session.cost_usd",
+ userClassification: "coding_agent.user.classification",
+ userClassificationReason: "coding_agent.user.classification.reason",
+ policyPermissionMode: "coding_agent.policy.permission_mode",
+ contentCaptureMode: "coding_agent.content_capture_mode",
+ editDecision: "coding_agent.edit.decision",
+ editDecisionSource: "coding_agent.edit.decision.source",
+ editLinesAdded: "coding_agent.edit.lines.added",
+ editLinesRemoved: "coding_agent.edit.lines.removed",
+ editLanguage: "coding_agent.edit.language",
+ editToolName: "coding_agent.edit.tool.name",
+ // Per-session code-change rollups. Stamped on the
+ // `coding_agent.session` root span at SessionEnd by the otlp
+ // emitter — these are the dashboard's primary source of truth
+ // for "what did this session change". The query layer falls
+ // back to summing the per-edit-decision spans when the session
+ // is still in progress (Codex; in-flight Cursor / CC sessions
+ // that haven't fired SessionEnd yet).
+ sessionLinesAdded: "coding_agent.session.lines.added",
+ sessionLinesRemoved: "coding_agent.session.lines.removed",
+ sessionLinesAccepted: "coding_agent.session.lines.accepted",
+ sessionLinesRejected: "coding_agent.session.lines.rejected",
+ sessionEditAcceptCount: "coding_agent.session.edit.accept_count",
+ sessionEditRejectCount: "coding_agent.session.edit.reject_count",
+ sessionCommitCount: "coding_agent.session.commit_count",
+ sessionPrCount: "coding_agent.session.pr_count",
+ // Git commit / pull-request span attributes.
+ gitCommitSha: "coding_agent.git.commit.sha",
+ gitCommitMessage: "coding_agent.git.commit.message",
+ gitPrUrl: "coding_agent.git.pull_request.url",
+ gitPrNumber: "coding_agent.git.pull_request.number",
+ gitPrTitle: "coding_agent.git.pull_request.title",
+ mcpServerName: "coding_agent.mcp.server.name",
+ mcpScope: "coding_agent.mcp.scope",
+ mcpTransport: "coding_agent.mcp.transport",
+ vcsDirty: "coding_agent.vcs.dirty",
+ hookEvent: "coding_agent.hook.event",
+ // Subagent linkage. CLI stamps `coding_agent.agent.parent_id` as a
+ // resource attribute on every hook process that knows it's running
+ // inside a subagent (Cursor exposes `parent_conversation_id` on
+ // subagent payloads). The UI uses it as the chat-thread rollup key
+ // so subagents fold under their parent row instead of polluting
+ // the Sessions list.
+ agentId: "coding_agent.agent.id",
+ agentParentId: "coding_agent.agent.parent_id",
+ sessionIsSubagent: "coding_agent.session.is_subagent",
+} as const;
+
+/** OTel `gen_ai.*` keys we read on coding-agent spans. */
+export const GEN_AI_ATTR = {
+ agentName: "gen_ai.agent.name",
+ userName: "gen_ai.user.name",
+ requestModel: "gen_ai.request.model",
+ usageCost: "gen_ai.usage.cost",
+ usageInputTokens: "gen_ai.usage.input_tokens",
+ usageOutputTokens: "gen_ai.usage.output_tokens",
+ usageTotalTokens: "gen_ai.usage.total_tokens",
+ conversationId: "gen_ai.conversation.id",
+ toolName: "gen_ai.tool.name",
+} as const;
+
+/** OTel `vcs.*` keys we read on coding-agent spans. */
+export const VCS_ATTR = {
+ repoUrl: "vcs.repository.url.full",
+ headRevision: "vcs.ref.head.revision",
+ headRef: "vcs.ref.head.name",
+} as const;
+
+/**
+ * Cohort floor used by aggregate-only views (top users, classification
+ * boards). Below this threshold, we suppress per-user breakdowns to
+ * protect individual contributors' privacy on small teams.
+ *
+ * Tunable per-org once we ship policy controls; v1 ships a single
+ * conservative default.
+ */
+export const COHORT_K_FLOOR = 5;
diff --git a/src/client/src/lib/platform/controller/health.ts b/src/client/src/lib/platform/controller/health.ts
new file mode 100644
index 00000000..c7b2dd01
--- /dev/null
+++ b/src/client/src/lib/platform/controller/health.ts
@@ -0,0 +1,22 @@
+import type { ControllerHealth, ControllerInstance } from "@/types/controller";
+
+/** Heartbeat recency thresholds — keep in sync with getControllerInstances. */
+export const CONTROLLER_HEARTBEAT_ACTIVE_MINUTES = 2;
+export const CONTROLLER_HEARTBEAT_DEGRADED_MINUTES = 10;
+
+/**
+ * Resolve the health label shown in the UI. Prefer heartbeat-derived
+ * `computed_status` (active / degraded / inactive) over the stored
+ * self-reported `status` (healthy / degraded / error from poll).
+ */
+export function resolveControllerHealth(
+ instance: Pick<ControllerInstance, "computed_status" | "status">
+): ControllerHealth {
+ return instance.computed_status || instance.status;
+}
+
+export function isControllerStale(
+ instance: Pick<ControllerInstance, "computed_status" | "status">
+): boolean {
+ return resolveControllerHealth(instance) === "inactive";
+}
diff --git a/src/client/src/lib/platform/manage-dashboard/board.ts b/src/client/src/lib/platform/manage-dashboard/board.ts
index 37d261eb..38557cc1 100644
--- a/src/client/src/lib/platform/manage-dashboard/board.ts
+++ b/src/client/src/lib/platform/manage-dashboard/board.ts
@@ -57,11 +57,27 @@ export function getBoards(isHome?: boolean) {
export async function createBoard(board: Board, databaseConfigId?: string) {
const sanitizedBoard = Sanitizer.sanitizeObject(board);
+ // Generate the board id client-side so the post-insert readback
+ // can deterministically lookup THIS row by primary key. The
+ // previous implementation read back the most-recently-created
+ // row by `ORDER BY created_at DESC LIMIT 1` — that races whenever
+ // two boards are inserted within the same second-precision tick
+ // (notably, dashboard seeding inserts 4 boards back-to-back). On
+ // fresh stacks this caused widget attachment to land on the wrong
+ // board (or the readback returned an empty result, which then
+ // threw `Cannot read property 'id' of undefined` upstream).
+ const boardId =
+ (sanitizedBoard.id as string | undefined) ||
+ (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
+ ? crypto.randomUUID()
+ : fallbackUUID());
+
const { err, data } = await dataCollector(
{
table: OPENLIT_BOARD_TABLE_NAME,
values: [
{
+ id: boardId,
title: sanitizedBoard.title,
description: sanitizedBoard.description,
parent_id: sanitizedBoard.parentId,
@@ -75,19 +91,44 @@ export async function createBoard(board: Board, databaseConfigId?: string) {
databaseConfigId
);
- if (err || !(data as { query_id: string }).query_id)
- return { err: getMessage().BOARD_CREATE_FAILED };
+ // Older ClickHouse builds returned a query_id on every insert; the
+ // version we ship in dev (24.4) sometimes returns an empty string.
+ // Treat the absence of `err` as the source of truth and only use
+ // query_id as a defensive check for legacy callers — this keeps the
+ // dashboard seed reliable regardless of CH minor version skew.
+ if (err) return { err: getMessage().BOARD_CREATE_FAILED };
+
+ // We already know the inserted row's id (we generated it client-
+ // side and supplied it in the INSERT). Skipping the post-insert
+ // readback both avoids the eventual-consistency race AND removes
+ // the need for a database-config lookup on this code path —
+ // important because the dashboard seed runs at server startup with
+ // no current user, and the prior readback was issuing a
+ // `getDBConfigByUser()` lookup that always failed with
+ // "Unauthorized user!", causing the seed to silently bail with
+ // "Board create failed!" even though the INSERT had succeeded.
+ return {
+ data: {
+ id: boardId,
+ title: sanitizedBoard.title,
+ description: sanitizedBoard.description,
+ parentId: sanitizedBoard.parentId,
+ isMainDashboard: sanitizedBoard.isMainDashboard,
+ isPinned: sanitizedBoard.isPinned,
+ tags: sanitizedBoard.tags,
+ },
+ };
+}
- const { data: data_board, err: err_board } = await dataCollector({
- query: `Select * from ${OPENLIT_BOARD_TABLE_NAME} order by created_at desc limit 1`,
+function fallbackUUID(): string {
+ // RFC4122-ish v4 UUID, used only when crypto.randomUUID is
+ // unavailable (very old runtimes). Not security-sensitive — these
+ // ids are public identifiers in the board table.
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
+ const r = Math.floor(Math.random() * 16);
+ const v = c === "x" ? r : (r & 0x3) | 0x8;
+ return v.toString(16);
});
-
-
- if (err_board) {
- return { err: getMessage().BOARD_CREATE_FAILED };
- }
-
- return { data: (data_board as any[])[0] };
}
export async function updateBoard(board: Board & { updateParent?: boolean }) {
@@ -427,7 +468,30 @@ export async function getMainDashboard(layout?: boolean, databaseConfigId?: stri
}
// TODO: fix the type of data
-export async function importBoardLayout(data: any, databaseConfigId?: string) {
+export async function importBoardLayout(
+ data: any,
+ databaseConfigId?: string,
+ options?: {
+ // When true, widget ids from `data.widgets` are kept verbatim
+ // instead of being replaced with freshly generated UUIDs.
+ //
+ // Defaults to FALSE -- user-driven imports (the public
+ // `/api/manage-dashboard/board/layout/import` endpoint and the
+ // UI explorer that wraps it) must regenerate ids because the
+ // incoming JSON could carry widget ids that already exist in
+ // the table (re-importing the same exported dashboard, or two
+ // users importing a shared template).
+ //
+ // The seed path (`CreateCustomDashboardsSeed`) opts in by
+ // passing `true`. Its JSON ships stable, owned UUIDs that we
+ // also want to use as the in-table widget ids so that
+ // `syncWidgetSqlFromSeed` can update widgets by id on every
+ // boot when a built-in widget's SQL or properties change in
+ // the seed file. Without preservation those by-id updates
+ // silently match zero rows.
+ preserveWidgetIds?: boolean;
+ }
+) {
const mainDashboard = await getMainDashboard(false, databaseConfigId);
const boardData: Partial<Board> = {
@@ -453,15 +517,18 @@ export async function importBoardLayout(data: any, databaseConfigId?: string) {
widgets: data.widgets
};
+ const preserveWidgetIds = options?.preserveWidgetIds === true;
const widgetIdMap = new Map();
const updatedWidgets = Object.values(layoutConfig.widgets).map((widget: any) => {
- const newWidgetId = crypto.randomUUID();
- widgetIdMap.set(widget.id, newWidgetId);
+ const nextWidgetId = preserveWidgetIds
+ ? widget.id
+ : crypto.randomUUID();
+ widgetIdMap.set(widget.id, nextWidgetId);
return {
...widget,
- id: newWidgetId,
+ id: nextWidgetId,
};
});
@@ -525,4 +592,31 @@ export async function isBoardTableEmpty(databaseConfigId?: string) {
}
return { data: (boardCount as any[])[0].count === 0, err: null };
+}
+
+/**
+ * Returns true when at least one board with the given title already
+ * exists. Used by the seed runner to "fill in" newly added seeded
+ * boards on stacks that already have other boards (the table-empty
+ * check would otherwise short-circuit and skip them forever).
+ */
+export async function boardExistsByTitle(
+ title: string,
+ databaseConfigId?: string
+) {
+ const safe = title.replace(/'/g, "''");
+ const query = `
+ SELECT CAST(COUNT(*) AS INTEGER) as count
+ FROM ${OPENLIT_BOARD_TABLE_NAME}
+ WHERE title = '${safe}'
+ `;
+ const { data, err } = await dataCollector(
+ { query },
+ "query",
+ databaseConfigId
+ );
+ if (err) {
+ return { err, data: false };
+ }
+ return { data: ((data as any[])?.[0]?.count ?? 0) > 0, err: null };
}
\ No newline at end of file
diff --git a/src/client/src/lib/platform/manage-dashboard/widget.ts b/src/client/src/lib/platform/manage-dashboard/widget.ts
index a12b0954..71d3fd1a 100644
--- a/src/client/src/lib/platform/manage-dashboard/widget.ts
+++ b/src/client/src/lib/platform/manage-dashboard/widget.ts
@@ -84,18 +84,20 @@ export async function createWidget(widget: Widget, databaseConfigId?: string) {
databaseConfigId
);
- // Extract the ID from the response
- const queryId = (data as { query_id: string })?.query_id;
-
- if (err || !queryId) {
+ if (err) {
return { err: err || getMessage().WIDGET_CREATE_FAILED };
}
- // Get the created widget to return its ID
- if (queryId) {
+ // Look up the widget we just inserted by id (we generated the id
+ // client-side and supplied it). The previous implementation
+ // searched by `ORDER BY created_at DESC LIMIT 1`, which raced
+ // during dashboard seeding (multiple widgets inserted in the same
+ // second-precision tick) and could return the wrong row.
+ if (sanitizedWidget.id) {
const result = await dataCollector({
query: `SELECT id, title, description, widget_type AS type, created_at AS createdAt, properties,
- config, updated_at AS updatedAt FROM ${OPENLIT_WIDGET_TABLE_NAME} ORDER BY created_at DESC LIMIT 1`,
+ config, updated_at AS updatedAt FROM ${OPENLIT_WIDGET_TABLE_NAME}
+ WHERE id = '${sanitizedWidget.id}' LIMIT 1`,
}, "query", databaseConfigId);
if (
@@ -112,7 +114,25 @@ export async function createWidget(widget: Widget, databaseConfigId?: string) {
}
}
- return { err: getMessage().WIDGET_CREATE_FAILED };
+ // Insert succeeded (we already checked `err`) but the readback
+ // returned empty — most likely ClickHouse async commit hasn't
+ // surfaced the row yet, or this code path is running before a
+ // db-config is bound (e.g. seed at server startup). Either way,
+ // the widget IS in the table; return the normalized widget we
+ // just inserted so the caller can move on. Skipping the
+ // readback failure makes seeding deterministic.
+ return {
+ data: normalizeWidgetToClient({
+ id: sanitizedWidget.id as string,
+ title: sanitizedWidget.title || "",
+ description: sanitizedWidget.description || "",
+ widget_type: sanitizedWidget.type || "",
+ properties: JSON.stringify(sanitizedWidget.properties || {}),
+ config: JSON.stringify(sanitizedWidget.config || {}),
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ } as DatabaseWidget),
+ };
}
export async function updateWidget(widget: Widget) {
diff --git a/src/client/src/lib/platform/pricing/index.ts b/src/client/src/lib/platform/pricing/index.ts
index 0f5c0266..529d268b 100644
--- a/src/client/src/lib/platform/pricing/index.ts
+++ b/src/client/src/lib/platform/pricing/index.ts
@@ -202,8 +202,16 @@ export async function autoUpdatePricing(payload: AutoPricingPayload) {
const lastRunTime = await getLastRunCronLogByCronId(payload.cronId);
- // Only LLM-type spans with tokens recorded
+ // Only LLM-type spans with tokens recorded. Crucially, we skip
+ // any span that already carries a `gen_ai.usage.cost` from the
+ // instrumentation/hook. Vendor-emitted cost is authoritative
+ // (Cursor / Codex / Claude Code stamp the provider's actual
+ // billed price, which may differ from list pricing for enterprise
+ // tiers); recomputing would silently overwrite that with our
+ // pricing-table estimate. This makes auto-pricing a true *backfill*
+ // path — it only writes when nothing was captured at ingest.
const typeKeyPath = `SpanAttributes['${TYPE_KEY}']`;
+ const costKeyPath = `SpanAttributes['${COST_KEY}']`;
const operationList = SUPPORTED_EVALUATION_OPERATIONS.map(
(op) => `'${op}'`
).join(", ");
@@ -212,6 +220,7 @@ export async function autoUpdatePricing(payload: AutoPricingPayload) {
SELECT SpanId, Timestamp, SpanAttributes
FROM ${OTEL_TRACES_TABLE_NAME}
WHERE ${typeKeyPath} IN (${operationList})
+ AND (${costKeyPath} = '' OR toFloat64OrZero(${costKeyPath}) = 0)
${
lastRunTime
? `AND Timestamp >= parseDateTimeBestEffort('${lastRunTime}')`
diff --git a/src/client/src/lib/platform/providers/default-models.ts b/src/client/src/lib/platform/providers/default-models.ts
index 69299f32..5934069e 100644
--- a/src/client/src/lib/platform/providers/default-models.ts
+++ b/src/client/src/lib/platform/providers/default-models.ts
@@ -171,6 +171,161 @@ export const DEFAULT_MODELS_BY_PROVIDER: Record<string, DefaultModelEntry[]> = {
outputPricePerMToken: 1.5,
capabilities: ["function-calling", "streaming"],
},
+ // GPT-5 family: shipped late 2025 with the same per-token rates
+ // across the base and codex variants ($1.25 input / $10 output).
+ // We seed the codex SKUs explicitly because the coding-agents
+ // hook stamps `gen_ai.request.model = gpt-5-codex` (etc.) and the
+ // auto-pricer otherwise skips them with "model not found". Each
+ // generation gets its own row so the picker/recompute paths can
+ // match the exact model id the agent reports.
+ {
+ id: "gpt-5",
+ displayName: "GPT-5",
+ contextWindow: 400000,
+ inputPricePerMToken: 1.25,
+ outputPricePerMToken: 10.0,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "gpt-5-codex",
+ displayName: "GPT-5 Codex",
+ contextWindow: 400000,
+ inputPricePerMToken: 1.25,
+ outputPricePerMToken: 10.0,
+ capabilities: ["function-calling", "streaming"],
+ },
+ {
+ id: "gpt-5-mini",
+ displayName: "GPT-5 Mini",
+ contextWindow: 400000,
+ inputPricePerMToken: 0.25,
+ outputPricePerMToken: 2.0,
+ capabilities: ["function-calling", "streaming"],
+ },
+ {
+ id: "gpt-5-nano",
+ displayName: "GPT-5 Nano",
+ contextWindow: 400000,
+ inputPricePerMToken: 0.05,
+ outputPricePerMToken: 0.4,
+ capabilities: ["function-calling", "streaming"],
+ },
+ {
+ id: "gpt-5-pro",
+ displayName: "GPT-5 Pro",
+ contextWindow: 400000,
+ inputPricePerMToken: 15.0,
+ outputPricePerMToken: 120.0,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "gpt-5.1",
+ displayName: "GPT-5.1",
+ contextWindow: 400000,
+ inputPricePerMToken: 1.25,
+ outputPricePerMToken: 10.0,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "gpt-5.1-codex",
+ displayName: "GPT-5.1 Codex",
+ contextWindow: 400000,
+ inputPricePerMToken: 1.25,
+ outputPricePerMToken: 10.0,
+ capabilities: ["function-calling", "streaming"],
+ },
+ {
+ id: "gpt-5.1-codex-max",
+ displayName: "GPT-5.1 Codex Max",
+ contextWindow: 1000000,
+ inputPricePerMToken: 1.25,
+ outputPricePerMToken: 10.0,
+ capabilities: ["function-calling", "streaming"],
+ },
+ {
+ id: "gpt-5.2",
+ displayName: "GPT-5.2",
+ contextWindow: 400000,
+ inputPricePerMToken: 1.75,
+ outputPricePerMToken: 14.0,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "gpt-5.2-codex",
+ displayName: "GPT-5.2 Codex",
+ contextWindow: 400000,
+ inputPricePerMToken: 1.75,
+ outputPricePerMToken: 14.0,
+ capabilities: ["function-calling", "streaming"],
+ },
+ {
+ id: "gpt-5.3-codex",
+ displayName: "GPT-5.3 Codex",
+ contextWindow: 400000,
+ inputPricePerMToken: 1.75,
+ outputPricePerMToken: 14.0,
+ capabilities: ["function-calling", "streaming"],
+ },
+ // GPT-5.4 uses breakpoint pricing above 272K context; we seed
+ // the standard tier here (the over-272K tier kicks in for the
+ // minority of users running long prompts and is recomputed via
+ // the manage-models UI if needed).
+ {
+ id: "gpt-5.4",
+ displayName: "GPT-5.4",
+ contextWindow: 1100000,
+ inputPricePerMToken: 2.5,
+ outputPricePerMToken: 15.0,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "gpt-5.4-mini",
+ displayName: "GPT-5.4 Mini",
+ contextWindow: 1100000,
+ inputPricePerMToken: 0.75,
+ outputPricePerMToken: 4.5,
+ capabilities: ["function-calling", "streaming"],
+ },
+ {
+ id: "gpt-5.4-nano",
+ displayName: "GPT-5.4 Nano",
+ contextWindow: 1100000,
+ inputPricePerMToken: 0.2,
+ outputPricePerMToken: 1.25,
+ capabilities: ["function-calling", "streaming"],
+ },
+ {
+ id: "gpt-5.5",
+ displayName: "GPT-5.5",
+ contextWindow: 400000,
+ inputPricePerMToken: 5.0,
+ outputPricePerMToken: 30.0,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "o3",
+ displayName: "OpenAI o3",
+ contextWindow: 200000,
+ inputPricePerMToken: 2.0,
+ outputPricePerMToken: 8.0,
+ capabilities: ["function-calling", "reasoning", "streaming"],
+ },
+ {
+ id: "o3-mini",
+ displayName: "OpenAI o3 mini",
+ contextWindow: 200000,
+ inputPricePerMToken: 1.1,
+ outputPricePerMToken: 4.4,
+ capabilities: ["function-calling", "reasoning", "streaming"],
+ },
+ {
+ id: "o4-mini",
+ displayName: "OpenAI o4 mini",
+ contextWindow: 200000,
+ inputPricePerMToken: 1.1,
+ outputPricePerMToken: 4.4,
+ capabilities: ["function-calling", "reasoning", "streaming"],
+ },
],
anthropic: [
{
@@ -181,6 +336,22 @@ export const DEFAULT_MODELS_BY_PROVIDER: Record<string, DefaultModelEntry[]> = {
outputPricePerMToken: 15.0,
capabilities: ["function-calling", "vision", "streaming"],
},
+ {
+ id: "claude-3-5-sonnet-20241022",
+ displayName: "Claude 3.5 Sonnet (2024-10)",
+ contextWindow: 200000,
+ inputPricePerMToken: 3.0,
+ outputPricePerMToken: 15.0,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "claude-3-5-haiku-20241022",
+ displayName: "Claude 3.5 Haiku",
+ contextWindow: 200000,
+ inputPricePerMToken: 0.8,
+ outputPricePerMToken: 4.0,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
{
id: "claude-3-haiku-20240307",
displayName: "Claude 3 Haiku",
@@ -197,6 +368,145 @@ export const DEFAULT_MODELS_BY_PROVIDER: Record<string, DefaultModelEntry[]> = {
outputPricePerMToken: 15.0,
capabilities: ["function-calling", "vision", "streaming"],
},
+ {
+ id: "claude-3-7-sonnet-20250219",
+ displayName: "Claude 3.7 Sonnet",
+ contextWindow: 200000,
+ inputPricePerMToken: 3.0,
+ outputPricePerMToken: 15.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ // Claude 4 family. Cursor/Claude Code stamp the bare id
+ // (`claude-opus-4-7`) and Cursor also surfaces thinking-mode
+ // variants under SKU-style suffixes (`-thinking-xhigh`, etc.).
+ // We seed every variant we've observed in the wild so the
+ // auto-pricer can match without falling back to the helper
+ // JSON path. Opus 4 / 4.1 use the legacy $15/$75 rate; 4.5+
+ // drops to $5/$25 per Anthropic's 2025-10 price change.
+ {
+ id: "claude-haiku-4-5",
+ displayName: "Claude Haiku 4.5",
+ contextWindow: 200000,
+ inputPricePerMToken: 1.0,
+ outputPricePerMToken: 5.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-haiku-4-5-20251001",
+ displayName: "Claude Haiku 4.5 (2025-10)",
+ contextWindow: 200000,
+ inputPricePerMToken: 1.0,
+ outputPricePerMToken: 5.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-sonnet-4-0",
+ displayName: "Claude Sonnet 4",
+ contextWindow: 200000,
+ inputPricePerMToken: 3.0,
+ outputPricePerMToken: 15.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-sonnet-4-5",
+ displayName: "Claude Sonnet 4.5",
+ contextWindow: 1000000,
+ inputPricePerMToken: 3.0,
+ outputPricePerMToken: 15.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-sonnet-4-6",
+ displayName: "Claude Sonnet 4.6",
+ contextWindow: 1000000,
+ inputPricePerMToken: 3.0,
+ outputPricePerMToken: 15.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-sonnet-4-7",
+ displayName: "Claude Sonnet 4.7",
+ contextWindow: 1000000,
+ inputPricePerMToken: 3.0,
+ outputPricePerMToken: 15.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-opus-4-0",
+ displayName: "Claude Opus 4",
+ contextWindow: 200000,
+ inputPricePerMToken: 15.0,
+ outputPricePerMToken: 75.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-opus-4-1",
+ displayName: "Claude Opus 4.1",
+ contextWindow: 200000,
+ inputPricePerMToken: 15.0,
+ outputPricePerMToken: 75.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-opus-4-5",
+ displayName: "Claude Opus 4.5",
+ contextWindow: 200000,
+ inputPricePerMToken: 5.0,
+ outputPricePerMToken: 25.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-opus-4-6",
+ displayName: "Claude Opus 4.6",
+ contextWindow: 1000000,
+ inputPricePerMToken: 5.0,
+ outputPricePerMToken: 25.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-opus-4-7",
+ displayName: "Claude Opus 4.7",
+ contextWindow: 1000000,
+ inputPricePerMToken: 5.0,
+ outputPricePerMToken: 25.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ // Cursor thinking-mode SKUs — the model is still Opus 4.7
+ // under the hood (same token rate), but the surface id Cursor
+ // stamps on coding_agent.llm.turn varies, so each gets its own
+ // row to avoid auto-pricer misses.
+ {
+ id: "claude-opus-4-7-thinking-low",
+ displayName: "Claude Opus 4.7 (thinking low)",
+ contextWindow: 1000000,
+ inputPricePerMToken: 5.0,
+ outputPricePerMToken: 25.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-opus-4-7-thinking-medium",
+ displayName: "Claude Opus 4.7 (thinking medium)",
+ contextWindow: 1000000,
+ inputPricePerMToken: 5.0,
+ outputPricePerMToken: 25.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-opus-4-7-thinking-high",
+ displayName: "Claude Opus 4.7 (thinking high)",
+ contextWindow: 1000000,
+ inputPricePerMToken: 5.0,
+ outputPricePerMToken: 25.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "claude-opus-4-7-thinking-xhigh",
+ displayName: "Claude Opus 4.7 (thinking xhigh)",
+ contextWindow: 1000000,
+ inputPricePerMToken: 5.0,
+ outputPricePerMToken: 25.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
],
google: [
{
@@ -223,6 +533,67 @@ export const DEFAULT_MODELS_BY_PROVIDER: Record<string, DefaultModelEntry[]> = {
outputPricePerMToken: 1.5,
capabilities: ["function-calling", "streaming"],
},
+ // Gemini 2.0 / 2.5 / 3.x families — Coding agents (Cursor sub-agent
+ // planners, Codex w/ Gemini backend, etc.) routinely emit these
+ // model ids. We seed the ≤200K standard tier; if the request goes
+ // long, the auto-pricer underestimates by ~2x but never zero, which
+ // is closer to the truth than skipping.
+ {
+ id: "gemini-2.0-flash",
+ displayName: "Gemini 2.0 Flash",
+ contextWindow: 1000000,
+ inputPricePerMToken: 0.1,
+ outputPricePerMToken: 0.4,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "gemini-2.5-pro",
+ displayName: "Gemini 2.5 Pro",
+ contextWindow: 2000000,
+ inputPricePerMToken: 1.25,
+ outputPricePerMToken: 10.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "gemini-2.5-flash",
+ displayName: "Gemini 2.5 Flash",
+ contextWindow: 1000000,
+ inputPricePerMToken: 0.3,
+ outputPricePerMToken: 2.5,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "gemini-2.5-flash-lite",
+ displayName: "Gemini 2.5 Flash-Lite",
+ contextWindow: 1000000,
+ inputPricePerMToken: 0.1,
+ outputPricePerMToken: 0.4,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "gemini-3-flash",
+ displayName: "Gemini 3 Flash",
+ contextWindow: 1000000,
+ inputPricePerMToken: 0.5,
+ outputPricePerMToken: 3.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
+ {
+ id: "gemini-3.1-flash-lite",
+ displayName: "Gemini 3.1 Flash-Lite",
+ contextWindow: 1000000,
+ inputPricePerMToken: 0.25,
+ outputPricePerMToken: 1.5,
+ capabilities: ["function-calling", "vision", "streaming"],
+ },
+ {
+ id: "gemini-3.1-pro",
+ displayName: "Gemini 3.1 Pro",
+ contextWindow: 2000000,
+ inputPricePerMToken: 2.0,
+ outputPricePerMToken: 12.0,
+ capabilities: ["function-calling", "vision", "streaming", "thinking"],
+ },
],
mistral: [
{
diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.ts
index 77da3cc0..e323908c 100644
--- a/src/client/src/lib/platform/request/index.ts
+++ b/src/client/src/lib/platform/request/index.ts
@@ -3,6 +3,8 @@ import {
getTraceMappingKeyFullPath,
buildHierarchy,
} from "@/helpers/server/trace";
+import { SYNTHETIC_SPAN_ID_PREFIX } from "@/helpers/client/trace";
+import { CODING_AGENT_ATTR } from "@/lib/platform/coding-agents/table-details";
import {
dateTruncGroupingLogic,
getFilterPreviousParams,
@@ -142,6 +144,18 @@ export async function getAverageRequestDuration(params: MetricParams) {
export async function getRequestsConfig(params: MetricParams) {
const select: string[] = [];
+ // Provider filter source list. Folds three attribute namespaces
+ // into one flat set so the "Provider" dropdown in the filter bar
+ // can act as a universal traffic-shaper:
+ // • gen_ai.system — LLM provider on regular GenAI spans
+ // • db.system — vector-DB provider on retrieval spans
+ // • coding_agent.client — coding-agent vendor (cursor / codex /
+ // claude_code) on every span we emit from the CLI hook. We
+ // surface it here (rather than building a separate "Vendor"
+ // filter) so operators can untick e.g. "cursor" to hide all
+ // of that vendor's telemetry from any view — the user asked
+ // for vendor visibility without a new control. The WHERE
+ // side of this fold lives in helpers/server/platform.ts.
select.push(
`arrayConcat(
arrayFilter(x -> x != '', groupArray(DISTINCT SpanAttributes['${getTraceMappingKeyFullPath(
@@ -149,7 +163,8 @@ export async function getRequestsConfig(params: MetricParams) {
)}'])),
arrayFilter(x -> x != '', groupArray(DISTINCT SpanAttributes['${getTraceMappingKeyFullPath(
"system"
- )}']))
+ )}'])),
+ arrayFilter(x -> x != '', groupArray(DISTINCT SpanAttributes['coding_agent.client']))
) AS providers`
);
@@ -234,8 +249,9 @@ export async function getRequests(params: MetricParams) {
}
export async function getRequestViaSpanId(spanId: string) {
+ const safeSpanId = escapeClickHouseString(String(spanId ?? ""));
const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}
- WHERE SpanId='${spanId}'`;
+ WHERE SpanId='${safeSpanId}'`;
const { data, err } = await dataCollector({ query });
return {
@@ -245,9 +261,10 @@ export async function getRequestViaSpanId(spanId: string) {
}
export async function getRequestViaTraceId(traceId: string) {
+ const safeTraceId = escapeClickHouseString(String(traceId ?? ""));
const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME} WHERE ${getTraceMappingKeyFullPath(
"id"
- )}='${traceId}'`;
+ )}='${safeTraceId}'`;
const { data, err } = await dataCollector({ query });
return {
@@ -257,27 +274,63 @@ export async function getRequestViaTraceId(traceId: string) {
}
export async function getHeirarchyViaSpanId(spanId: string) {
- // Step 1: Get the TraceId for this span
- const traceIdQuery = `
- SELECT ${getTraceMappingKeyFullPath("id")}
+ // Step 1: resolve the source span. We need:
+ // - TraceId (the usual "show every span in the trace" path)
+ // - coding_agent.session.id (so coding-agent sessions whose CLI
+ // emitted multiple independent traces still render as one
+ // conversation)
+ // - coding_agent.agent.parent_id (resource attr, set on subagent
+ // hooks). When this is set, the chat we should display is the
+ // PARENT's chat — fold this subagent's spans into the parent
+ // trace, and union with the parent's own session_id, and with
+ // all sibling subagents.
+ const safeSpanId = escapeClickHouseString(String(spanId ?? ""));
+ const sourceSpanQuery = `
+ SELECT
+ TraceId,
+ SpanAttributes['coding_agent.session.id'] AS CodingSessionId,
+ coalesce(
+ nullIf(ResourceAttributes['coding_agent.agent.parent_id'], ''),
+ nullIf(SpanAttributes['coding_agent.agent.parent_id'], '')
+ ) AS CodingParentId
FROM ${OTEL_TRACES_TABLE_NAME}
- WHERE SpanId = '${spanId}'
+ WHERE SpanId = '${safeSpanId}'
LIMIT 1`;
- const { data: traceIdData, err: traceIdErr } = await dataCollector({
- query: traceIdQuery,
+ const { data: sourceData, err: sourceErr } = await dataCollector({
+ query: sourceSpanQuery,
});
- if (traceIdErr || !Array.isArray(traceIdData) || traceIdData.length === 0) {
+ if (sourceErr || !Array.isArray(sourceData) || sourceData.length === 0) {
return { err: "Span not found", record: {} };
}
- const traceId = traceIdData[0].TraceId;
- if (!traceId) {
+ const traceId = sourceData[0].TraceId as string | undefined;
+ const ownSessionId = (sourceData[0].CodingSessionId || "") as string;
+ const parentId = (sourceData[0].CodingParentId || "") as string;
+ // The chat id we display is the parent's id when the source span
+ // is a subagent's; otherwise it's the source span's own session.
+ const codingSessionId = parentId || ownSessionId;
+ if (!traceId && !codingSessionId) {
return { err: "TraceId not found for span", record: {} };
}
- // Step 2: Fetch ALL spans belonging to this trace (include SpanAttributes for chat view)
+ // Step 2: fetch every span we care about. For coding-agent sessions
+ // we union three sources:
+ // - this trace (TraceId match — same hook invocation)
+ // - all spans whose own session_id == chat id (the parent's own
+ // spans when we opened from a subagent, or any spans that
+ // share the chat id directly)
+ // - all subagent spans pointing at this chat id (resource OR
+ // span attribute parent_id match — folds subagents into the
+ // parent's chat thread regardless of which session emitted them)
+ const safeTraceId = escapeClickHouseString(String(traceId ?? ""));
+ const filterClause = codingSessionId
+ ? `(${getTraceMappingKeyFullPath(
+ "id"
+ )} = '${safeTraceId}' OR SpanAttributes['coding_agent.session.id'] = '${escapeClickHouseString(codingSessionId)}' OR ResourceAttributes['coding_agent.agent.parent_id'] = '${escapeClickHouseString(codingSessionId)}' OR SpanAttributes['coding_agent.agent.parent_id'] = '${escapeClickHouseString(codingSessionId)}')`
+ : `${getTraceMappingKeyFullPath("id")} = '${safeTraceId}'`;
+
const allSpansQuery = `
SELECT
${getTraceMappingKeyFullPath("id")},
@@ -299,8 +352,9 @@ export async function getHeirarchyViaSpanId(spanId: string) {
Events,
Links
FROM ${OTEL_TRACES_TABLE_NAME}
- WHERE ${getTraceMappingKeyFullPath("id")} = '${traceId}'
- ORDER BY Timestamp ASC`;
+ WHERE ${filterClause}
+ ORDER BY Timestamp ASC
+ LIMIT 5000`;
const { data: allSpans, err: allSpansErr } = await dataCollector({
query: allSpansQuery,
@@ -310,7 +364,24 @@ export async function getHeirarchyViaSpanId(spanId: string) {
return { err: "Failed to fetch trace spans", record: {} };
}
- // Step 3: Build the hierarchy tree in JS
+ // Step 3: Build the hierarchy tree in JS.
+ // - For coding-agent sessions, prefer the explicit `coding_agent.session`
+ // span as the root (synthesizing one if absent), then attach every
+ // other span as a child. This works whether the CLI emitted one
+ // shared TraceId or many independent traces.
+ // - For other traces, fall back to the regular ParentSpanId-based
+ // buildHierarchy.
+ if (codingSessionId) {
+ const heirarchy = buildCodingSessionHierarchy(
+ allSpans as any[],
+ codingSessionId
+ );
+ if (!heirarchy) {
+ return { err: "Error building hierarchy", record: {} };
+ }
+ return { err: null, record: heirarchy };
+ }
+
const heirarchy = buildHierarchy(allSpans as any[]);
if (!heirarchy) {
@@ -320,6 +391,87 @@ export async function getHeirarchyViaSpanId(spanId: string) {
return { err: null, record: heirarchy };
}
+/**
+ * Coding-agent sessions span ≥ 1 trace because each hook invocation
+ * historically produced its own trace. The session-detail UI needs a
+ * single tree, so we synthesize one:
+ * - prefer the `coding_agent.session` span as the root when present,
+ * - otherwise mint a synthetic root node carrying the session id,
+ * - attach every other span as a direct child of the root.
+ *
+ * We deliberately don't try to honor ParentSpanId across traces — the
+ * chat view flattens the tree anyway, and the timeline / tree views
+ * still get a clean chronological list.
+ */
+function buildCodingSessionHierarchy(spans: any[], sessionId: string) {
+ if (spans.length === 0) return null;
+ const sessionSpan = spans.find(
+ (s) => s.SpanName === "coding_agent.session"
+ );
+ const earliest = spans.reduce((acc, s) => {
+ const ts = s.Timestamp ? new Date(s.Timestamp).getTime() : 0;
+ const accTs = acc?.Timestamp ? new Date(acc.Timestamp).getTime() : 0;
+ return !acc || ts < accTs ? s : acc;
+ }, undefined as any);
+ // Whole-session wall-clock duration, mirroring `getCodingSessionDigest`'s
+ // `greatest(reported coding_agent.session.duration_ms, max(start) - min(start))`.
+ // The raw `coding_agent.session` span Duration is unreliable (frequently 0,
+ // or just one hook invocation's slice), which is why the root node's time
+ // didn't match the detail header's session Duration. We recompute it here so
+ // the tree/timeline/graph root reflects the full session and matches the
+ // header. The header itself sources its value from `sessionDigest`, so this
+ // override is display-only for the hierarchy and can't regress it.
+ const sessionDurationNs = (() => {
+ let minTs = Number.POSITIVE_INFINITY;
+ let maxTs = Number.NEGATIVE_INFINITY;
+ let reportedMs = 0;
+ for (const s of spans) {
+ const ts = s.Timestamp ? new Date(s.Timestamp).getTime() : NaN;
+ if (Number.isFinite(ts)) {
+ if (ts < minTs) minTs = ts;
+ if (ts > maxTs) maxTs = ts;
+ }
+ const reported = Number(
+ s?.SpanAttributes?.[CODING_AGENT_ATTR.sessionDurationMs] || 0
+ );
+ if (Number.isFinite(reported) && reported > reportedMs) {
+ reportedMs = reported;
+ }
+ }
+ const wallClockMs =
+ Number.isFinite(minTs) && Number.isFinite(maxTs) ? maxTs - minTs : 0;
+ // ms → ns: `Duration` is nanoseconds (requestDuration offset is 1e-9).
+ return Math.max(reportedMs, wallClockMs, 0) * 1e6;
+ })();
+ const root = sessionSpan
+ ? { ...sessionSpan, Duration: sessionDurationNs, children: [] as any[] }
+ : {
+ SpanId: `${SYNTHETIC_SPAN_ID_PREFIX}${sessionId}`,
+ ParentSpanId: "",
+ SpanName: "coding_agent.session",
+ TraceId: earliest?.TraceId || "",
+ Timestamp: earliest?.Timestamp || "",
+ Duration: sessionDurationNs,
+ Cost: 0,
+ StatusCode: "",
+ SpanAttributes: {
+ "coding_agent.session.id": sessionId,
+ },
+ ResourceAttributes: earliest?.ResourceAttributes || {},
+ children: [] as any[],
+ };
+ const sorted = [...spans].sort((a, b) => {
+ const ta = a.Timestamp ? new Date(a.Timestamp).getTime() : 0;
+ const tb = b.Timestamp ? new Date(b.Timestamp).getTime() : 0;
+ return ta - tb;
+ });
+ for (const span of sorted) {
+ if (span.SpanId === root.SpanId) continue;
+ root.children.push({ ...span, children: [] });
+ }
+ return root;
+}
+
export async function getRequestExist() {
const query = `SELECT COUNT(*) AS total_requests FROM ${OTEL_TRACES_TABLE_NAME}`;
return dataCollector({ query });
diff --git a/src/client/src/store/filter.ts b/src/client/src/store/filter.ts
index 0d5858fb..24eacb9f 100644
--- a/src/client/src/store/filter.ts
+++ b/src/client/src/store/filter.ts
@@ -31,7 +31,7 @@ export const DEFAULT_TIME_RANGE = "24H";
const DEFAULT_LIMIT = 25;
-const DEFAULT_SORTING: FilterSorting = {
+export const DEFAULT_SORTING: FilterSorting = {
type: "Timestamp",
direction: "desc",
};
diff --git a/src/client/src/store/page.ts b/src/client/src/store/page.ts
index 1890230a..aa8b02cb 100644
--- a/src/client/src/store/page.ts
+++ b/src/client/src/store/page.ts
@@ -56,6 +56,35 @@ export const pageStoreSlice: PageStore = lens((setStore, getStore) => ({
status: true,
}
},
+ codingAgentSessions: {
+ visibilityColumns: {
+ session: true,
+ user: true,
+ started: true,
+ duration: true,
+ model: true,
+ tools: true,
+ tokens: true,
+ cost: true,
+ outcome: true,
+ classification: true,
+ // Code-impact columns. All four default ON because
+ // they're the signal columns this feature is shipped
+ // for — operators can hide them via the visibility
+ // menu if they want a more compact view.
+ code: true,
+ acceptance: true,
+ commits: true,
+ prs: true,
+ // `coding_users` table reuses the same page store
+ sessions: true,
+ topVendor: true,
+ mix: true,
+ lastSeen: true,
+ // Users table columns
+ lines: true,
+ },
+ },
header: {
title: "",
breadcrumbs: [],
diff --git a/src/client/src/types/agents.ts b/src/client/src/types/agents.ts
index ab4138dd..0033b869 100644
--- a/src/client/src/types/agents.ts
+++ b/src/client/src/types/agents.ts
@@ -5,7 +5,28 @@
* controller can act on the row.
*/
-export type AgentSource = "controller" | "sdk" | "both";
+/**
+ * Where this agent originated from:
+ * - `controller` — discovered by the OpenLit controller (Docker/K8s/systemd).
+ * - `sdk` — instrumented via openlit-sdk in user code.
+ * - `both` — discovered AND instrumented (`controller` + `sdk` rolled up).
+ * - `coding` — AI coding-agent client (Claude Code, Cursor, Codex, …)
+ * sending telemetry through the openlit CLI's hook
+ * subcommand. Distinguished here because the
+ * detail page renders a different set of tabs and the
+ * list page shows a vendor logo + label.
+ */
+export type AgentSource = "controller" | "sdk" | "both" | "coding";
+
+/**
+ * Vendor identifier for `source === "coding"` rows. Mirrors
+ * `coding_agent.client` / `gen_ai.agent.name` from sdk/go/semconv.
+ */
+export type CodingAgentVendor =
+ | "claude-code"
+ | "cursor"
+ | "codex"
+ | "windsurf";
export type AgentInstrumentationStatus = "discovered" | "instrumented";
@@ -95,6 +116,38 @@ export interface UnifiedAgent {
pods_total: number;
pods_pending: number;
pods_acknowledged: number;
+
+ /**
+ * Coding-agent vendor identifier. Set iff `source === "coding"`. Used by
+ * the list page to render the vendor logo and by the detail page to
+ * branch into the coding-agent tab set.
+ */
+ coding_agent_vendor?: CodingAgentVendor;
+
+ /**
+ * Per-coding-agent rollups (last 24h, materialized server-side). All
+ * fields default to 0 for non-coding rows so dashboard widgets can
+ * filter on `source = 'coding'` without conditionalizing every read.
+ */
+ coding_session_count_24h?: number;
+ coding_cost_usd_24h?: number;
+ coding_active_users_24h?: number;
+ /**
+ * Code-impact rollups (last 24h). `lines_*` are LOC sums across
+ * accepted/rejected/total edits; `edit_*` are decision counts that
+ * power the acceptance % derivation. `commit_count_24h` and
+ * `pr_count_24h` come from detected `git commit` / `gh pr`
+ * invocations parsed out of shell/Bash hooks. All default to 0
+ * for non-coding rows.
+ */
+ coding_lines_added_24h?: number;
+ coding_lines_removed_24h?: number;
+ coding_lines_accepted_24h?: number;
+ coding_lines_rejected_24h?: number;
+ coding_edit_accept_24h?: number;
+ coding_edit_reject_24h?: number;
+ coding_commit_count_24h?: number;
+ coding_pr_count_24h?: number;
}
export interface AgentListCursor {
@@ -159,4 +212,5 @@ export interface AgentListFilters {
environments?: string[];
providers?: string[];
statuses?: Array<"discovered" | "instrumented" | "sdk">;
+ codingVendors?: CodingAgentVendor[];
}
diff --git a/src/client/src/types/store/page.ts b/src/client/src/types/store/page.ts
index ca429a78..9051ea8a 100644
--- a/src/client/src/types/store/page.ts
+++ b/src/client/src/types/store/page.ts
@@ -19,7 +19,8 @@ export type PAGE =
| "exception"
| "observabilityLogs"
| "observabilityMetrics"
- | "fleethub";
+ | "fleethub"
+ | "codingAgentSessions";
export type PageHeader = {
title: string;
@@ -49,6 +50,9 @@ export type PageStore = {
fleethub: {
visibilityColumns: Record<string, boolean>;
};
+ codingAgentSessions: {
+ visibilityColumns: Record<string, boolean>;
+ };
setData: (p: PAGE, keyPath: string, value: unknown) => void;
header: PageHeader,
setHeader: (header: PageHeader) => void;
diff --git a/src/client/src/types/trace.ts b/src/client/src/types/trace.ts
index fb2e3397..7bc90d3d 100644
--- a/src/client/src/types/trace.ts
+++ b/src/client/src/types/trace.ts
@@ -167,6 +167,9 @@ export interface TraceHeirarchySpan {
ScopeVersion?: string;
Cost?: number;
SpanAttributes?: Record<string, string | number>;
+ // ResourceAttributes carry per-process facts (e.g. `coding_agent.agent.parent_id`
+ // for Cursor/Claude Code subagents whose parent linkage isn't stamped at the
+ // span level). Optional because legacy SDK paths may omit them.
ResourceAttributes?: Record<string, string | number>;
Events?: {
Timestamp?: Date | string;
diff --git a/src/client/src/utils/breadcrumbs.ts b/src/client/src/utils/breadcrumbs.ts
index 7e58c0b5..8250bc83 100644
--- a/src/client/src/utils/breadcrumbs.ts
+++ b/src/client/src/utils/breadcrumbs.ts
@@ -53,7 +53,18 @@ export function extractRouteParams(pathname: string, regex: RegExp): Record<stri
params.id = parts[idIndex];
}
}
-
+
+ // Coding-agents per-user detail: /coding-agents/users/<userId>.
+ // `userId` is URL-encoded (emails contain `@` etc.) so we leave
+ // decoding to the caller (the route config calls
+ // decodeURIComponent before rendering the breadcrumb title).
+ if (pathname.startsWith('/coding-agents/users/')) {
+ const parts = pathname.split('/').filter(Boolean);
+ if (parts.length >= 3) {
+ params.userId = parts[2];
+ }
+ }
+
return params;
}
@@ -301,6 +312,26 @@ export const ROUTE_CONFIGS: RouteConfig[] = [
],
},
+ // Coding Agents — per-user drilldown.
+ //
+ // The per-user page lives under `/coding-agents/users/[userId]` (not
+ // under `/agents/<key>` like the per-vendor detail page) because it
+ // rolls up across vendors. Without an explicit route config the
+ // breadcrumb generator falls through to the path-tail fallback,
+ // which yields "Home › [email protected]" — useless context for
+ // the operator. We thread back through the Coding Agents tab on
+ // the unified Agents hub so the user can backtrack out.
+ {
+ regex: /^\/coding-agents\/users\/[^/]+$/,
+ getTitle: (_pathname, params) =>
+ params?.userId ? decodeURIComponent(params.userId) : "User",
+ getBreadcrumbs: () => [
+ { title: "Agents", href: "/agents" },
+ { title: getMessage().AGENTS_TAB_CODING, href: "/agents?tab=coding" },
+ { title: "Users", href: "/agents?tab=coding&codingTab=users" },
+ ],
+ },
+
// Chat
{
regex: /^\/chat$/,