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(coding-agents): add OpenCode integration (#1591)

Steven Huang6b97612e58d1
diff --git a/.github/workflows/ci-cli.yml b/.github/workflows/ci-cli.yml
index ae3f9d2e..0186df9c 100644
--- a/.github/workflows/ci-cli.yml
+++ b/.github/workflows/ci-cli.yml
@@ -92,6 +92,13 @@ jobs:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.ref || github.sha }}
+ - uses: actions/setup-node@v6
+ with:
+ node-version: '22'
+ - name: Test OpenCode plugin queue
+ run: >
+ node --experimental-strip-types --test
+ cli/internal/coding/install/testdata/opencode_queue.test.mjs
- name: Sync into a temp dir and diff
run: |
set -euo pipefail
diff --git a/README.md b/README.md
index 06e68ba0..e9ba20fc 100644
--- a/README.md
+++ b/README.md
@@ -136,7 +136,7 @@ Open your dashboard and start exploring your AI application's traces, metrics, c
---
-# πŸ€– Coding agent observability: Claude Code, Cursor, Codex & Windsurf
+# πŸ€– Coding agent observability: Claude Code, Cursor, Codex, Windsurf & OpenCode
AI coding agents are powerful β€” but understanding what they actually did can be difficult.
@@ -174,6 +174,7 @@ Or install individual integrations:
openlit coding install --vendor=cursor
openlit coding install --vendor=claude-code
openlit coding install --vendor=codex
+openlit coding install --vendor=opencode
```
Check your installation:
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 00000000..28511ebe
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,35 @@
+# Third-Party Notices
+
+This file records notices for third-party material included in this repository.
+
+## OpenCode logo
+
+The OpenCode logo geometry used by `OpenCodeIcon` in
+`src/client/src/components/svg/coding-agents.tsx` is adapted from:
+
+https://github.com/anomalyco/opencode/blob/e3471526f4c71b2c4ee00117e125e179da01e6e2/packages/console/app/src/asset/brand/opencode-logo-light-square.svg
+
+The adaptation removes the clip and mask wrappers, folds their horizontal
+translation into the two paths, and changes the fills to `currentColor`.
+
+MIT License
+
+Copyright (c) 2025 opencode
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/agent-guides/coding-agents-convention.md b/agent-guides/coding-agents-convention.md
index 858d91f1..6d1942d8 100644
--- a/agent-guides/coding-agents-convention.md
+++ b/agent-guides/coding-agents-convention.md
@@ -16,7 +16,7 @@ Everything OpenLit reads or rolls up speaks one of two namespaces:
**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`.
+2. Adapters MUST stamp `coding_agent.client` (vendor identifier) on every span. Allowed values: `cursor`, `claude-code`, `codex`, `opencode`, `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.
@@ -89,6 +89,10 @@ For sessions where the rollup is missing (Codex never emits a
the query layer falls back to per-event aggregation with the
`greatest(rollup, sum)` pattern documented in `queries.ts`.
+**Non-terminal session snapshot spans** (`coding_agent.session.snapshot.start`, `coding_agent.session.snapshot`):
+
+These are the narrow exception for a vendor such as OpenCode that has no true session-end signal. They are allowed only in `minimal` capture mode. The start snapshot establishes visibility; each idle snapshot carries per-snapshot token/cost deltas and cumulative duration/tool-call count. Readers sum the deltas and take the numeric maximum of cumulative values. A snapshot MUST NOT carry `coding_agent.session.outcome` and MUST NOT be treated as a terminal `coding_agent.session` root.
+
**LLM turn span** (`coding_agent.llm.turn`):
| Attribute | Required | Notes |
@@ -99,6 +103,7 @@ the query layer falls back to per-event aggregation with the
| `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.reasoning_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 |
@@ -400,11 +405,11 @@ 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>`.
+4. **Plugin manifest** β€” `plugins/opencode/`. Keep the distributable source in sync with the embedded installer copy. The plugin invokes `openlit coding hook --vendor=opencode --event=<EventName>` with a strictly projected payload.
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.md` Β§10.
+7. **Onboarding doc** β€” `docs/latest/openlit/coding-agents/setup-and-configure.mdx`. Add a tab for the vendor.
+8. **Sanity check** β€” run one session end to end (or through the vendor's strongest available lifecycle boundary), then run the verification SQL in `coding-agents-hook.md` Β§9.
## 11. Things the convention WILL bite you on
@@ -426,5 +431,6 @@ These are known limits where the data the vendor sends prevents perfect rollup.
- **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.
+- **OpenCode: no terminal session-end event**. `session.idle` fires at run-loop boundaries and may follow errors or cancellation, while `session.deleted` means persisted conversation deletion rather than successful completion. The adapter therefore leaves outcome unknown instead of fabricating success. Minimal capture uses the non-terminal snapshot contract above; metadata/full retain ordinary child and lifecycle spans. A session row can keep updating whenever the conversation resumes.
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/agent-guides/coding-agents-hook.md b/agent-guides/coding-agents-hook.md
index 89a57799..85d55a6e 100644
--- a/agent-guides/coding-agents-hook.md
+++ b/agent-guides/coding-agents-hook.md
@@ -67,7 +67,7 @@ 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. |
+| `minimal` | Counters and identifiers only. No bodies. Session root on a true end signal; vendors without one may emit the registered non-terminal session snapshots described below. Other per-event spans are 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. |
@@ -77,6 +77,8 @@ Centralised in `cli/internal/otlp/attrs.go`:
- `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.
+OpenCode has no terminal session hook, and its `session.idle` event is only a turn boundary. In `minimal`, it may therefore emit exactly two registered non-terminal span names: `coding_agent.session.snapshot.start` and `coding_agent.session.snapshot`. Snapshot token/cost attributes are deltas so downstream sums remain correct; duration and tool-call count are cumulative so readers must take the numeric maximum. Snapshots never carry `coding_agent.session.outcome` and must not be treated as session roots.
+
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
diff --git a/cli/cmd/openlit/main.go b/cli/cmd/openlit/main.go
index c9076086..2dac9c63 100644
--- a/cli/cmd/openlit/main.go
+++ b/cli/cmd/openlit/main.go
@@ -1,6 +1,6 @@
// 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,
+// Codex, OpenCode). Future subcommand groups (prompts, traces, eval,
// migrate) plug in by registering on the root in `registerSubcommands`.
//
// Crash-isolation guardrails (see internal/coding/hook):
@@ -50,6 +50,7 @@ v1 ships the 'coding' subcommand group for AI-coding-agent observability:
openlit coding install --vendor=all
openlit coding launch claude
+ openlit coding launch opencode
openlit coding hook --vendor=cc --event=SessionStart
Run 'openlit doctor' to diagnose configuration, OTLP reachability,
diff --git a/cli/gen/semconv.ts b/cli/gen/semconv.ts
index fd9b6df5..b46381df 100644
--- a/cli/gen/semconv.ts
+++ b/cli/gen/semconv.ts
@@ -10,6 +10,8 @@ export const CodingAgentVendorCursor = "cursor";
export const CodingAgentVendorCodex = "codex";
+export const CodingAgentVendorOpenCode = "opencode";
+
export const CodingAgentVendorWindsurf = "windsurf";
// CodingAgentSessionID identifies a single coding-agent session.
@@ -115,6 +117,17 @@ export const CodingAgentLinkageConfidenceMedium = "medium";
export const CodingAgentLinkageConfidenceLow = "low";
+// CodingAgentLLMTurnKind describes the primary payload carried by an
+// individual coding-agent LLM turn.
+export const CodingAgentLLMTurnKind = "coding_agent.llm.turn.kind";
+
+// LLM turn kind values.
+export const CodingAgentLLMTurnKindPrompt = "prompt";
+
+export const CodingAgentLLMTurnKindResponse = "response";
+
+export const CodingAgentLLMTurnKindThought = "thought";
+
// CodingAgentEditDecision is one of: accept | reject | modify | auto_accepted.
export const CodingAgentEditDecision = "coding_agent.edit.decision";
@@ -306,6 +319,13 @@ export const CodingAgentEventSessionStart = "coding_agent.session.start";
export const CodingAgentEventSessionEnd = "coding_agent.session.end";
+// OpenCode has no terminal SessionEnd hook. Minimal capture uses
+// non-terminal snapshots so counters stay visible without inventing
+// a completed session root or emitting high-cardinality child spans.
+export const CodingAgentEventSessionSnapshotStart = "coding_agent.session.snapshot.start";
+
+export const CodingAgentEventSessionSnapshot = "coding_agent.session.snapshot";
+
export const CodingAgentEventEditDecision = "coding_agent.edit.decision";
export const CodingAgentEventLoopDetected = "coding_agent.loop.detected";
diff --git a/cli/internal/coding/cmd.go b/cli/internal/coding/cmd.go
index f4a78b36..9086e928 100644
--- a/cli/internal/coding/cmd.go
+++ b/cli/internal/coding/cmd.go
@@ -2,10 +2,10 @@
//
// v1 ships the following children:
//
-// openlit coding hook --vendor=cc|cursor|codex --event=...
+// openlit coding hook --vendor=cc|cursor|codex|opencode --event=...
// openlit coding install --vendor=all|<single>
// openlit coding uninstall --vendor=all|<single> [--purge]
-// openlit coding launch <claude|cursor|codex>
+// openlit coding launch <claude|cursor|codex|opencode>
//
// All children share the resolved config from internal/config and the
// OTLP exporter from internal/otlp. The hook subcommand is the hot path
@@ -25,11 +25,11 @@ import (
func NewCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "coding",
- Short: "Coding-agent observability (Claude Code, Cursor, Codex)",
+ Short: "Coding-agent observability (Claude Code, Cursor, Codex, OpenCode)",
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
+ A) openlit coding launch <claude|cursor|codex|opencode> # 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.
diff --git a/cli/internal/coding/hook/cursor/handle.go b/cli/internal/coding/hook/cursor/handle.go
index 64207402..70e75409 100644
--- a/cli/internal/coding/hook/cursor/handle.go
+++ b/cli/internal/coding/hook/cursor/handle.go
@@ -180,8 +180,8 @@ func handle(ctx context.Context, in normalize.Input) error {
}
// 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
+ // cli/internal/coding/hook/hook.go for every coding agent
+ // (Cursor / Claude Code / Codex / OpenCode), so we don't duplicate that
// logic here. The cache update for the latest value still
// happens via peekContext + sessionstate.Save in hook.go.
diff --git a/cli/internal/coding/hook/hook.go b/cli/internal/coding/hook/hook.go
index c121b402..255e3fe5 100644
--- a/cli/internal/coding/hook/hook.go
+++ b/cli/internal/coding/hook/hook.go
@@ -29,6 +29,7 @@ import (
"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/hook/opencode"
"github.com/openlit/openlit/cli/internal/coding/identity"
"github.com/openlit/openlit/cli/internal/coding/normalize"
"github.com/openlit/openlit/cli/internal/coding/sessionstate"
@@ -69,7 +70,7 @@ never blocks a developer's prompt.`,
},
}
- cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor: cc | claude-code | cursor | codex")
+ cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor: cc | claude-code | cursor | codex | opencode")
cmd.Flags().StringVar(&event, "event", "", "Hook event name (vendor-specific; e.g. SessionStart, PreToolUse)")
_ = cmd.MarkFlagRequired("vendor")
@@ -287,7 +288,7 @@ func run(cmd *cobra.Command, vendor, event string) (rerr error) {
}
// Default service.name to the vendor identifier ("cursor",
- // "claude-code", "codex") so the trace-detail header's
+ // "claude-code", "codex", "opencode") 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;
@@ -425,7 +426,7 @@ func run(cmd *cobra.Command, vendor, event string) (rerr error) {
// 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
+// `codex`, `opencode`. 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.
@@ -438,6 +439,8 @@ func canonicalVendor(vendor string) string {
return "cursor"
case "codex":
return "codex"
+ case "opencode":
+ return "opencode"
default:
return v
}
@@ -454,6 +457,8 @@ func pickAdapter(vendor string) (normalize.Adapter, error) {
return cursor.New(), nil
case "codex":
return codex.New(), nil
+ case "opencode":
+ return opencode.New(), nil
case "":
return nil, errors.New("--vendor is required")
default:
@@ -594,33 +599,60 @@ func peekContext(payload []byte) peekedContext {
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
+ var eventType string
+ var eventProperties map[string]any
+ var eventInfo map[string]any
+ if event, ok := probe["event"].(map[string]any); ok {
+ if value, ok := event["type"].(string); ok {
+ eventType = strings.TrimSpace(value)
+ }
+ if properties, ok := event["properties"].(map[string]any); ok {
+ eventProperties = properties
+ if info, ok := properties["info"].(map[string]any); ok {
+ eventInfo = info
}
- if s, ok := v.(string); ok {
- s = strings.TrimSpace(s)
- if s != "" {
- return s
+ }
+ }
+ containers := []map[string]any{probe, eventProperties, eventInfo}
+ pickString := func(keys ...string) string {
+ for _, container := range containers {
+ for _, k := range keys {
+ v, ok := container[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")
+ out.SessionID = pickString("session_id", "conversation_id", "sessionId", "sessionID", "thread_id")
+ if out.SessionID == "" && strings.HasPrefix(eventType, "session.") && eventInfo != nil {
+ if value, ok := eventInfo["id"].(string); ok {
+ out.SessionID = strings.TrimSpace(value)
+ }
+ }
// 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")
+ out.ConversationID = pickString("conversation_id", "conversationId", "thread_id", "threadId", "sessionID")
+ if out.ConversationID == "" && strings.HasPrefix(eventType, "session.") {
+ out.ConversationID = out.SessionID
+ }
// `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")
+ out.ParentConversationID = pickString(
+ "parent_conversation_id", "parentConversationId", "parent_session_id", "parentID",
+ )
// Cursor exposes `user_email` on every event that carries
// identity (sessionStart, beforeSubmitPrompt, sessionEnd, ...).
// Claude Code transcript hooks include the user-message author
@@ -630,7 +662,7 @@ func peekContext(payload []byte) peekedContext {
// 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")
+ out.CWD = pickString("cwd", "working_directory", "workingDirectory", "directory", "worktree")
if out.CWD == "" {
// Cursor sometimes only sends `workspace_roots: []`. Pick
// the first entry as a best-effort cwd.
@@ -654,8 +686,16 @@ func peekContext(payload []byte) peekedContext {
"composer_mode",
"permission_mode", "permissionMode",
"approval_mode", "approvalMode",
+ "mode",
)
- out.Model = pickString("model", "request_model", "requestModel")
+ out.Model = pickString("model", "request_model", "requestModel", "modelID")
+ if out.Model == "" && eventInfo != nil {
+ if model, ok := eventInfo["model"].(map[string]any); ok {
+ if value, ok := model["modelID"].(string); ok {
+ out.Model = strings.TrimSpace(value)
+ }
+ }
+ }
if v, ok := probe["is_background_agent"]; ok {
if b, ok := v.(bool); ok {
out.IsBackgroundAgent = b
diff --git a/cli/internal/coding/hook/hook_test.go b/cli/internal/coding/hook/hook_test.go
index 8278a53b..94111bcd 100644
--- a/cli/internal/coding/hook/hook_test.go
+++ b/cli/internal/coding/hook/hook_test.go
@@ -62,6 +62,66 @@ func TestIsClaudeCodeVendor(t *testing.T) {
}
}
+func TestCanonicalVendorOpenCode(t *testing.T) {
+ for _, input := range []string{"opencode", "OpenCode", " opencode "} {
+ if got := canonicalVendor(input); got != "opencode" {
+ t.Fatalf("canonicalVendor(%q) = %q, want opencode", input, got)
+ }
+ }
+}
+
+func TestPickAdapterOpenCode(t *testing.T) {
+ adapter, err := pickAdapter("opencode")
+ if err != nil {
+ t.Fatalf("pickAdapter(opencode): %v", err)
+ }
+ if got := adapter.Vendor(); got != "opencode" {
+ t.Fatalf("adapter vendor = %q, want opencode", got)
+ }
+}
+
+func TestPeekContextOpenCodeEnvelope(t *testing.T) {
+ payload := []byte(`{
+ "event": {
+ "type": "session.created",
+ "properties": {
+ "info": {
+ "id": "ses_123",
+ "directory": "/repo",
+ "parentID": "ses_parent",
+ "mode": "plan",
+ "model": {
+ "providerID": "provider-1",
+ "modelID": "model-1"
+ }
+ }
+ }
+ },
+ "directory": "/repo",
+ "worktree": "/repo"
+ }`)
+
+ got := peekContext(payload)
+ if got.SessionID != "ses_123" {
+ t.Fatalf("SessionID = %q, want ses_123", got.SessionID)
+ }
+ if got.ConversationID != "ses_123" {
+ t.Fatalf("ConversationID = %q, want ses_123", got.ConversationID)
+ }
+ if got.CWD != "/repo" {
+ t.Fatalf("CWD = %q, want /repo", got.CWD)
+ }
+ if got.Model != "model-1" {
+ t.Fatalf("Model = %q, want model-1", got.Model)
+ }
+ if got.ParentConversationID != "ses_parent" {
+ t.Fatalf("ParentConversationID = %q, want ses_parent", got.ParentConversationID)
+ }
+ if got.PermissionMode != "plan" {
+ t.Fatalf("PermissionMode = %q, want plan", got.PermissionMode)
+ }
+}
+
// 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
diff --git a/cli/internal/coding/hook/opencode/handle.go b/cli/internal/coding/hook/opencode/handle.go
new file mode 100644
index 00000000..14b1b66f
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/handle.go
@@ -0,0 +1,9 @@
+package opencode
+
+import (
+ "context"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+)
+
+func handle(ctx context.Context, in normalize.Input) error { return handlePayload(ctx, in) }
diff --git a/cli/internal/coding/hook/opencode/handle_test.go b/cli/internal/coding/hook/opencode/handle_test.go
new file mode 100644
index 00000000..d027d529
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/handle_test.go
@@ -0,0 +1,175 @@
+package opencode
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+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(tc normalize.ToolCall) error {
+ e.toolCalls = append(e.toolCalls, tc)
+ return nil
+}
+
+func (e *recordingEmitter) EmitEditDecision(d normalize.EditDecision) error {
+ e.editDecisions = append(e.editDecisions, d)
+ return nil
+}
+
+func (e *recordingEmitter) EmitLLMTurn(turn normalize.LLMTurn) error {
+ e.llmTurns = append(e.llmTurns, turn)
+ return nil
+}
+
+func (e *recordingEmitter) EmitSubagent(s normalize.Subagent) error {
+ e.subagents = append(e.subagents, s)
+ return nil
+}
+
+func (e *recordingEmitter) EmitEvent(event normalize.EventEmission) error {
+ e.events = append(e.events, event)
+ return nil
+}
+
+func (e *recordingEmitter) EmitGitCommit(commit normalize.GitCommit) error {
+ e.gitCommits = append(e.gitCommits, commit)
+ return nil
+}
+
+func (e *recordingEmitter) EmitGitPullRequest(pr normalize.GitPullRequest) error {
+ e.gitPRs = append(e.gitPRs, pr)
+ return nil
+}
+
+func withIsolatedCache(t *testing.T) {
+ t.Helper()
+ dir := t.TempDir()
+ t.Setenv("XDG_CACHE_HOME", dir)
+ t.Setenv("LOCALAPPDATA", dir)
+ if os.Getenv("HOME") != "" {
+ t.Setenv("HOME", dir)
+ }
+}
+
+func adapterInput(t *testing.T, em normalize.Emitter, event, capture string, payload any) normalize.Input {
+ t.Helper()
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal payload: %v", err)
+ }
+ return normalize.Input{
+ Vendor: "opencode",
+ Event: event,
+ Payload: body,
+ ContentCapture: capture,
+ Emit: em,
+ }
+}
+
+func TestUnknownEventIsDropped(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ payload := map[string]any{
+ "event": map[string]any{
+ "type": "plugin.future.event",
+ "properties": map[string]any{
+ "opaque": "value",
+ },
+ },
+ }
+ if err := New().Handle(context.Background(), adapterInput(t, em, "plugin.future.event", "full", payload)); err != nil {
+ t.Fatalf("unknown event: %v", err)
+ }
+ if len(em.sessions)+len(em.toolCalls)+len(em.editDecisions)+len(em.llmTurns)+len(em.subagents)+len(em.events)+len(em.gitCommits)+len(em.gitPRs) != 0 {
+ t.Fatalf("unknown event emitted telemetry: %+v", em)
+ }
+}
+
+func TestLifecycleDoesNotTreatIdleAsSessionEnd(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ adapter := New()
+ startedAt := time.Now().UTC().Add(-5 * time.Minute).Truncate(time.Millisecond)
+ directory := t.TempDir()
+ created := map[string]any{
+ "event": map[string]any{
+ "type": "session.created",
+ "properties": map[string]any{
+ "info": map[string]any{
+ "id": "ses_open_1",
+ "directory": directory,
+ "parentID": "ses_parent",
+ "title": "private session title",
+ "version": "1.18.16",
+ "time": map[string]any{
+ "created": startedAt.UnixMilli(),
+ },
+ },
+ },
+ },
+ "directory": directory,
+ "worktree": directory,
+ }
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "session.created", "metadata_only", created)); err != nil {
+ t.Fatalf("session.created: %v", err)
+ }
+ if len(em.sessions) != 0 {
+ t.Fatalf("session.created emitted %d session roots, want 0", len(em.sessions))
+ }
+ if len(em.events) != 1 || em.events[0].Name != semconv.CodingAgentEventSessionStart {
+ t.Fatalf("session.created event = %+v, want %q", em.events, semconv.CodingAgentEventSessionStart)
+ }
+
+ idle := map[string]any{
+ "event": map[string]any{
+ "type": "session.idle",
+ "properties": map[string]any{
+ "sessionID": "ses_open_1",
+ },
+ },
+ "directory": directory,
+ "worktree": directory,
+ }
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "session.idle", "metadata_only", idle)); err != nil {
+ t.Fatalf("first session.idle: %v", err)
+ }
+ if len(em.sessions) != 0 {
+ t.Fatalf("session.idle emitted %d roots, want 0 because idle is a turn boundary", len(em.sessions))
+ }
+ if len(em.events) != 2 || em.events[1].Name != "coding_agent.session.loop.stop" {
+ t.Fatalf("session.idle events = %+v, want loop.stop after session.start", em.events)
+ }
+ if _, ok := em.events[1].Attrs[semconv.CodingAgentSessionOutcome]; ok {
+ t.Fatalf("session.idle fabricated a terminal outcome: %+v", em.events[1].Attrs)
+ }
+
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "session.idle", "metadata_only", idle)); err != nil {
+ t.Fatalf("duplicate session.idle: %v", err)
+ }
+ if len(em.sessions) != 0 {
+ t.Fatalf("later session.idle emitted %d roots, want 0", len(em.sessions))
+ }
+}
diff --git a/cli/internal/coding/hook/opencode/idle_refresh_test.go b/cli/internal/coding/hook/opencode/idle_refresh_test.go
new file mode 100644
index 00000000..1d96110a
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/idle_refresh_test.go
@@ -0,0 +1,336 @@
+package opencode
+
+import (
+ "context"
+ "math"
+ "testing"
+
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+func TestSessionErrorAndFollowingIdleDoNotReportCompletion(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ errorPayload := map[string]any{
+ "event": map[string]any{
+ "type": "session.error",
+ "properties": map[string]any{
+ "sessionID": "ses_failed",
+ "errorName": "APIError",
+ "message": "must-not-be-recorded",
+ },
+ },
+ }
+ if err := New().Handle(context.Background(), adapterInput(t, em, "session.error", "full", errorPayload)); err != nil {
+ t.Fatalf("session.error: %v", err)
+ }
+ if len(em.events) != 1 || em.events[0].Name != "coding_agent.session.error" {
+ t.Fatalf("session.error events = %+v", em.events)
+ }
+ if em.events[0].Attrs[semconv.ErrorType] != "APIError" {
+ t.Errorf("error type = %v, want APIError", em.events[0].Attrs[semconv.ErrorType])
+ }
+ for _, value := range em.events[0].Attrs {
+ if value == "must-not-be-recorded" {
+ t.Fatalf("session.error leaked error body: %+v", em.events[0].Attrs)
+ }
+ }
+
+ idlePayload := map[string]any{
+ "event": map[string]any{
+ "type": "session.idle",
+ "properties": map[string]any{"sessionID": "ses_failed"},
+ },
+ }
+ if err := New().Handle(context.Background(), adapterInput(t, em, "session.idle", "full", idlePayload)); err != nil {
+ t.Fatalf("session.idle: %v", err)
+ }
+ if len(em.sessions) != 0 {
+ t.Fatalf("error + idle emitted %d terminal roots, want 0", len(em.sessions))
+ }
+ if _, ok := em.events[len(em.events)-1].Attrs[semconv.CodingAgentSessionOutcome]; ok {
+ t.Fatalf("idle after error reported terminal outcome: %+v", em.events[len(em.events)-1].Attrs)
+ }
+}
+
+func TestMinimalIdleEmitsCounterSnapshotWithoutTerminalOutcome(t *testing.T) {
+ withIsolatedCache(t)
+
+ const sessionID = "ses_minimal_snapshot"
+ state := &sessionstate.State{
+ ConversationID: sessionID,
+ ToolCallCount: 2,
+ InputTokens: 100,
+ OutputTokens: 25,
+ TotalTokens: 140,
+ CostUSD: 0.01,
+ }
+ sessionstate.Save(sessionID, "opencode", state)
+ em := &recordingEmitter{}
+ payload := map[string]any{
+ "event": map[string]any{
+ "type": "session.idle",
+ "properties": map[string]any{"sessionID": sessionID},
+ },
+ }
+ input := adapterInput(t, em, "session.idle", "minimal", payload)
+ if err := New().Handle(context.Background(), input); err != nil {
+ t.Fatalf("first minimal session.idle: %v", err)
+ }
+ if len(em.events) != 1 || em.events[0].Name != semconv.CodingAgentEventSessionSnapshot {
+ t.Fatalf("minimal idle events = %+v, want one session.snapshot", em.events)
+ }
+ first := em.events[0].Attrs
+ if first[semconv.CodingAgentSessionToolCallCount] != 2 || first[semconv.GenAIUsageInputTokens] != int64(100) || first[semconv.GenAIUsageOutputTokens] != int64(25) || first[semconv.GenAIUsageTotalTokens] != int64(140) {
+ t.Errorf("first snapshot counters = %+v", first)
+ }
+ if first[semconv.GenAIUsageCost] != 0.01 {
+ t.Errorf("first snapshot cost = %v, want 0.01", first[semconv.GenAIUsageCost])
+ }
+ if _, ok := first[semconv.CodingAgentSessionOutcome]; ok {
+ t.Fatalf("minimal snapshot fabricated terminal outcome: %+v", first)
+ }
+
+ state = sessionstate.Load(sessionID, "opencode")
+ state.ToolCallCount = 3
+ state.InputTokens = 140
+ state.OutputTokens = 35
+ state.TotalTokens = 195
+ state.CostUSD = 0.015
+ sessionstate.Save(sessionID, "opencode", state)
+ if err := New().Handle(context.Background(), input); err != nil {
+ t.Fatalf("second minimal session.idle: %v", err)
+ }
+ second := em.events[1].Attrs
+ if second[semconv.CodingAgentSessionToolCallCount] != 3 || second[semconv.GenAIUsageInputTokens] != int64(40) || second[semconv.GenAIUsageOutputTokens] != int64(10) || second[semconv.GenAIUsageTotalTokens] != int64(55) {
+ t.Errorf("second snapshot counters = %+v", second)
+ }
+ if got, _ := second[semconv.GenAIUsageCost].(float64); math.Abs(got-0.005) > 1e-9 {
+ t.Errorf("second snapshot cost = %v, want delta 0.005", second[semconv.GenAIUsageCost])
+ }
+}
+
+func TestMinimalErrorEmitsImmediateSnapshotAndFollowingIdleDoesNotRepeatIt(t *testing.T) {
+ withIsolatedCache(t)
+
+ const sessionID = "ses_minimal_error"
+ em := &recordingEmitter{}
+ errorPayload := map[string]any{
+ "event": map[string]any{
+ "type": "session.error",
+ "properties": map[string]any{
+ "sessionID": sessionID,
+ "errorName": "APIError",
+ "message": "must-not-be-recorded",
+ },
+ },
+ }
+ if err := New().Handle(context.Background(), adapterInput(t, em, "session.error", "minimal", errorPayload)); err != nil {
+ t.Fatalf("minimal session.error: %v", err)
+ }
+ if len(em.events) != 1 {
+ t.Fatalf("minimal error emitted %d events, want one immediate snapshot", len(em.events))
+ }
+ errorSnapshot := em.events[0]
+ if errorSnapshot.Name != semconv.CodingAgentEventSessionSnapshot || errorSnapshot.Attrs[semconv.ErrorType] != "APIError" {
+ t.Fatalf("error snapshot did not carry safe error type: %+v", errorSnapshot)
+ }
+ if errorSnapshot.Attrs[semconv.CodingAgentHookEvent] != "session.error" {
+ t.Fatalf("error snapshot hook = %v, want session.error", errorSnapshot.Attrs[semconv.CodingAgentHookEvent])
+ }
+
+ idlePayload := map[string]any{
+ "event": map[string]any{
+ "type": "session.idle",
+ "properties": map[string]any{"sessionID": sessionID},
+ },
+ }
+ input := adapterInput(t, em, "session.idle", "minimal", idlePayload)
+ if err := New().Handle(context.Background(), input); err != nil {
+ t.Fatalf("following idle: %v", err)
+ }
+ idleSnapshot := em.events[len(em.events)-1]
+ if idleSnapshot.Attrs[semconv.CodingAgentHookEvent] != "session.idle" {
+ t.Fatalf("idle snapshot hook = %v, want session.idle", idleSnapshot.Attrs[semconv.CodingAgentHookEvent])
+ }
+ if _, ok := idleSnapshot.Attrs[semconv.ErrorType]; ok {
+ t.Fatalf("idle snapshot repeated stale error type: %+v", idleSnapshot)
+ }
+ if _, ok := idleSnapshot.Attrs[semconv.CodingAgentSessionOutcome]; ok {
+ t.Fatalf("snapshot fabricated terminal outcome: %+v", idleSnapshot)
+ }
+}
+
+func TestMinimalErrorWithoutTypeStillEmitsImmediateSnapshot(t *testing.T) {
+ withIsolatedCache(t)
+
+ const sessionID = "ses_minimal_untyped_error"
+ em := &recordingEmitter{}
+ payload := map[string]any{
+ "event": map[string]any{
+ "type": "session.error",
+ "properties": map[string]any{
+ "sessionID": sessionID,
+ },
+ },
+ }
+ if err := New().Handle(context.Background(), adapterInput(t, em, "session.error", "minimal", payload)); err != nil {
+ t.Fatalf("minimal untyped session.error: %v", err)
+ }
+ if len(em.events) != 1 || em.events[0].Name != semconv.CodingAgentEventSessionSnapshot {
+ t.Fatalf("minimal untyped error events = %+v, want one immediate snapshot", em.events)
+ }
+ if em.events[0].Attrs[semconv.CodingAgentHookEvent] != "session.error" {
+ t.Fatalf("error snapshot hook = %v, want session.error", em.events[0].Attrs[semconv.CodingAgentHookEvent])
+ }
+ if _, ok := em.events[0].Attrs[semconv.ErrorType]; ok {
+ t.Fatalf("untyped error snapshot fabricated an error type: %+v", em.events[0].Attrs)
+ }
+}
+
+func TestNonMinimalTurnDoesNotReappearInMinimalSnapshot(t *testing.T) {
+ for _, capture := range []string{
+ semconv.CodingAgentContentCaptureMetadataOnly,
+ semconv.CodingAgentContentCaptureFull,
+ } {
+ t.Run(capture, func(t *testing.T) {
+ withIsolatedCache(t)
+
+ const sessionID = "ses_non_minimal_then_minimal"
+ em := &recordingEmitter{}
+ adapter := New()
+ message := completedAssistantMessage(
+ sessionID,
+ "msg-visible-turn",
+ 100,
+ 20,
+ 5,
+ 40,
+ 10,
+ 0.0125,
+ )
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "message.updated", capture, message)); err != nil {
+ t.Fatalf("%s message.updated: %v", capture, err)
+ }
+ if len(em.llmTurns) != 1 {
+ t.Fatalf("%s emitted %d LLM turns, want 1", capture, len(em.llmTurns))
+ }
+
+ idle := map[string]any{
+ "event": map[string]any{
+ "type": "session.idle",
+ "properties": map[string]any{"sessionID": sessionID},
+ },
+ }
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "session.idle", semconv.CodingAgentContentCaptureMinimal, idle)); err != nil {
+ t.Fatalf("minimal session.idle: %v", err)
+ }
+ if len(em.events) != 1 {
+ t.Fatalf("minimal idle emitted %d events, want 1", len(em.events))
+ }
+ assertSnapshotUsage(t, em.events[0].Attrs, 0, 0, 0, 0)
+ })
+ }
+}
+
+func TestMinimalSnapshotPreservesOnlyPendingMinimalUsageAcrossModeChanges(t *testing.T) {
+ withIsolatedCache(t)
+
+ const sessionID = "ses_pending_minimal_usage"
+ // Model the real minimal exporter after turn A: it records usage in the
+ // lifetime counters but has not emitted a snapshot yet.
+ sessionstate.Save(sessionID, "opencode", &sessionstate.State{
+ ConversationID: sessionID,
+ InputTokens: 10,
+ OutputTokens: 2,
+ TotalTokens: 15,
+ CostUSD: 0.001,
+ })
+
+ em := &recordingEmitter{}
+ adapter := New()
+ message := completedAssistantMessage(
+ sessionID,
+ "msg-visible-turn-b",
+ 100,
+ 20,
+ 5,
+ 40,
+ 10,
+ 0.0125,
+ )
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "message.updated", semconv.CodingAgentContentCaptureMetadataOnly, message)); err != nil {
+ t.Fatalf("metadata-only message.updated: %v", err)
+ }
+
+ idle := map[string]any{
+ "event": map[string]any{
+ "type": "session.idle",
+ "properties": map[string]any{"sessionID": sessionID},
+ },
+ }
+ minimalIdle := adapterInput(t, em, "session.idle", semconv.CodingAgentContentCaptureMinimal, idle)
+ if err := adapter.Handle(context.Background(), minimalIdle); err != nil {
+ t.Fatalf("first minimal session.idle: %v", err)
+ }
+ assertSnapshotUsage(t, em.events[0].Attrs, 10, 2, 15, 0.001)
+
+ // Model a later minimal turn C. The next snapshot must contain only C.
+ state := sessionstate.Load(sessionID, "opencode")
+ state.InputTokens += 7
+ state.OutputTokens += 3
+ state.TotalTokens += 11
+ state.CostUSD += 0.002
+ sessionstate.Save(sessionID, "opencode", state)
+ if err := adapter.Handle(context.Background(), minimalIdle); err != nil {
+ t.Fatalf("second minimal session.idle: %v", err)
+ }
+ assertSnapshotUsage(t, em.events[1].Attrs, 7, 3, 11, 0.002)
+
+ if err := adapter.Handle(context.Background(), minimalIdle); err != nil {
+ t.Fatalf("repeated minimal session.idle: %v", err)
+ }
+ assertSnapshotUsage(t, em.events[2].Attrs, 0, 0, 0, 0)
+}
+
+func completedAssistantMessage(sessionID, messageID string, input, output, reasoning, cacheRead, cacheWrite int64, cost float64) map[string]any {
+ return map[string]any{
+ "event": map[string]any{
+ "type": "message.updated",
+ "properties": map[string]any{
+ "info": map[string]any{
+ "id": messageID,
+ "sessionID": sessionID,
+ "role": "assistant",
+ "time": map[string]any{
+ "created": int64(1_000),
+ "completed": int64(2_000),
+ },
+ "cost": cost,
+ "tokens": map[string]any{
+ "input": input,
+ "output": output,
+ "reasoning": reasoning,
+ "cache": map[string]any{
+ "read": cacheRead,
+ "write": cacheWrite,
+ },
+ },
+ },
+ },
+ },
+ }
+}
+
+func assertSnapshotUsage(t *testing.T, attrs map[string]any, input, output, total int64, cost float64) {
+ t.Helper()
+ if attrs[semconv.GenAIUsageInputTokens] != input || attrs[semconv.GenAIUsageOutputTokens] != output || attrs[semconv.GenAIUsageTotalTokens] != total {
+ t.Errorf("snapshot usage = %v/%v/%v, want %d/%d/%d", attrs[semconv.GenAIUsageInputTokens], attrs[semconv.GenAIUsageOutputTokens], attrs[semconv.GenAIUsageTotalTokens], input, output, total)
+ }
+ gotCost, _ := attrs[semconv.GenAIUsageCost].(float64)
+ if math.Abs(gotCost-cost) > 1e-9 {
+ t.Errorf("snapshot cost = %v, want %v", attrs[semconv.GenAIUsageCost], cost)
+ }
+}
diff --git a/cli/internal/coding/hook/opencode/lifecycle.go b/cli/internal/coding/hook/opencode/lifecycle.go
new file mode 100644
index 00000000..19f94eb8
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/lifecycle.go
@@ -0,0 +1,265 @@
+package opencode
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/git"
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+type payloadEnvelope struct {
+ Event struct {
+ Type string `json:"type"`
+ Properties json.RawMessage `json:"properties"`
+ } `json:"event"`
+ Directory string `json:"directory"`
+ Worktree string `json:"worktree"`
+}
+
+type eventHandler func(context.Context, normalize.Input, payloadEnvelope) error
+
+var eventHandlers = map[string]eventHandler{
+ "session.created": handleSessionCreated,
+ "session.idle": handleSessionIdle,
+ "session.error": handleSessionError,
+ "session.deleted": handleSessionDeleted,
+}
+
+type sessionInfo struct {
+ ID string `json:"id"`
+ Directory string `json:"directory"`
+ ParentID string `json:"parentID"`
+ Version string `json:"version"`
+ Time struct {
+ Created int64 `json:"created"`
+ } `json:"time"`
+}
+
+type sessionCreatedProperties struct {
+ Info sessionInfo `json:"info"`
+}
+
+type sessionIDProperties struct {
+ SessionID string `json:"sessionID"`
+}
+
+type sessionErrorProperties struct {
+ SessionID string `json:"sessionID"`
+ ErrorName string `json:"errorName"`
+}
+
+func handlePayload(ctx context.Context, in normalize.Input) error {
+ var payload payloadEnvelope
+ if err := json.Unmarshal(in.Payload, &payload); err != nil {
+ return nil
+ }
+ event := firstNonEmpty(payload.Event.Type, in.Event)
+ if handler := eventHandlers[event]; handler != nil {
+ return handler(ctx, in, payload)
+ }
+ // Unknown OpenCode events are intentionally dropped. Emitting a generic
+ // span here would either violate the required session-id convention or
+ // guess a session association that the payload does not guarantee.
+ return nil
+}
+
+func handleSessionCreated(ctx context.Context, in normalize.Input, payload payloadEnvelope) error {
+ var properties sessionCreatedProperties
+ if err := json.Unmarshal(payload.Event.Properties, &properties); err != nil {
+ return nil
+ }
+ info := properties.Info
+ sessionID := strings.TrimSpace(info.ID)
+ if sessionID == "" {
+ return nil
+ }
+
+ startedAt := time.Now()
+ if info.Time.Created > 0 {
+ startedAt = time.UnixMilli(info.Time.Created)
+ }
+ cwd := firstNonEmpty(info.Directory, payload.Directory, payload.Worktree)
+ state := sessionstate.Load(sessionID, in.Vendor)
+ if state.SessionStartedAt.IsZero() {
+ state.SessionStartedAt = startedAt
+ }
+ state.ConversationID = sessionID
+ if cwd != "" {
+ state.CWD = cwd
+ }
+ if info.ParentID != "" {
+ state.ParentConversationID = info.ParentID
+ }
+ if cwd != "" && (state.RepoURL == "" || state.Branch == "") {
+ vcs := git.Snapshot(ctx, cwd)
+ if state.RepoURL == "" {
+ state.RepoURL = vcs.RepoURL
+ }
+ if state.Branch == "" {
+ state.Branch = vcs.Branch
+ }
+ }
+ sessionstate.Save(sessionID, in.Vendor, state)
+
+ attrs := map[string]any{
+ semconv.CodingAgentClient: in.Vendor,
+ semconv.CodingAgentHookEvent: "session.created",
+ }
+ if info.Version != "" {
+ attrs[semconv.CodingAgentClientVersion] = info.Version
+ }
+ if info.ParentID != "" {
+ attrs[semconv.CodingAgentAgentParentID] = info.ParentID
+ }
+ eventName := semconv.CodingAgentEventSessionStart
+ if in.ContentCapture == semconv.CodingAgentContentCaptureMinimal {
+ eventName = semconv.CodingAgentEventSessionSnapshotStart
+ }
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: eventName,
+ At: startedAt,
+ Attrs: attrs,
+ })
+}
+
+// OpenCode publishes session.idle after every run loop, including error and
+// cancellation paths. It is a turn boundary, not a terminal SessionEnd.
+func handleSessionIdle(_ context.Context, in normalize.Input, payload payloadEnvelope) error {
+ var properties sessionIDProperties
+ if err := json.Unmarshal(payload.Event.Properties, &properties); err != nil {
+ return nil
+ }
+ sessionID := strings.TrimSpace(properties.SessionID)
+ if sessionID == "" {
+ return nil
+ }
+ if in.ContentCapture == semconv.CodingAgentContentCaptureMinimal {
+ return emitMinimalSessionSnapshot(in, sessionID, "session.idle")
+ }
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.session.loop.stop",
+ At: time.Now(),
+ Attrs: map[string]any{
+ semconv.CodingAgentClient: in.Vendor,
+ semconv.CodingAgentHookEvent: "session.idle",
+ },
+ })
+}
+
+func emitMinimalSessionSnapshot(in normalize.Input, sessionID, hookEvent string) error {
+ state := sessionstate.Load(sessionID, in.Vendor)
+ inputDelta := nonNegative(state.InputTokens - state.OpenCodeSnapshotInputTokens)
+ outputDelta := nonNegative(state.OutputTokens - state.OpenCodeSnapshotOutputTokens)
+ totalDelta := nonNegative(state.TotalTokens - state.OpenCodeSnapshotTotalTokens)
+ costDelta := state.CostUSD - state.OpenCodeSnapshotCostUSD
+ if costDelta < 0 {
+ costDelta = 0
+ }
+ now := time.Now()
+ duration := int64(0)
+ if !state.SessionStartedAt.IsZero() && state.SessionStartedAt.Before(now) {
+ duration = now.Sub(state.SessionStartedAt).Milliseconds()
+ }
+ attrs := map[string]any{
+ semconv.CodingAgentClient: in.Vendor,
+ semconv.CodingAgentHookEvent: hookEvent,
+ semconv.CodingAgentSessionDurationMs: duration,
+ semconv.CodingAgentSessionToolCallCount: state.ToolCallCount,
+ semconv.GenAIUsageInputTokens: inputDelta,
+ semconv.GenAIUsageOutputTokens: outputDelta,
+ semconv.GenAIUsageTotalTokens: totalDelta,
+ semconv.GenAIUsageCost: costDelta,
+ }
+ if state.OpenCodePendingErrorType != "" {
+ attrs[semconv.ErrorType] = state.OpenCodePendingErrorType
+ }
+ state.OpenCodeSnapshotInputTokens = state.InputTokens
+ state.OpenCodeSnapshotOutputTokens = state.OutputTokens
+ state.OpenCodeSnapshotTotalTokens = state.TotalTokens
+ state.OpenCodeSnapshotCostUSD = state.CostUSD
+ state.OpenCodePendingErrorType = ""
+ sessionstate.Save(sessionID, in.Vendor, state)
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: semconv.CodingAgentEventSessionSnapshot,
+ At: now,
+ Attrs: attrs,
+ })
+}
+
+func handleSessionError(_ context.Context, in normalize.Input, payload payloadEnvelope) error {
+ var properties sessionErrorProperties
+ if err := json.Unmarshal(payload.Event.Properties, &properties); err != nil {
+ return nil
+ }
+ sessionID := strings.TrimSpace(properties.SessionID)
+ if sessionID == "" {
+ return nil
+ }
+ attrs := map[string]any{
+ semconv.CodingAgentClient: in.Vendor,
+ semconv.CodingAgentHookEvent: "session.error",
+ }
+ errorName := strings.TrimSpace(properties.ErrorName)
+ if errorName != "" {
+ attrs[semconv.ErrorType] = errorName
+ }
+ if in.ContentCapture == semconv.CodingAgentContentCaptureMinimal {
+ if errorName != "" {
+ state := sessionstate.Load(sessionID, in.Vendor)
+ state.OpenCodePendingErrorType = errorName
+ sessionstate.Save(sessionID, in.Vendor, state)
+ }
+ // Some OpenCode error paths (for example failed automatic
+ // compaction) return without publishing a following idle event.
+ // Flush a safe snapshot immediately so minimal mode does not lose
+ // the error boundary; the snapshot advances deltas and consumes any
+ // pending type, making a later idle refresh idempotent.
+ return emitMinimalSessionSnapshot(in, sessionID, "session.error")
+ }
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.session.error",
+ At: time.Now(),
+ Attrs: attrs,
+ })
+}
+
+// session.deleted destroys a persisted OpenCode conversation. It is not a
+// signal that the agent completed successfully, so record the lifecycle event
+// without fabricating a session-root outcome.
+func handleSessionDeleted(_ context.Context, in normalize.Input, payload payloadEnvelope) error {
+ var properties sessionCreatedProperties
+ if err := json.Unmarshal(payload.Event.Properties, &properties); err != nil {
+ return nil
+ }
+ sessionID := strings.TrimSpace(properties.Info.ID)
+ if sessionID == "" {
+ return nil
+ }
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: sessionID,
+ Name: "coding_agent.session.deleted",
+ At: time.Now(),
+ Attrs: map[string]any{
+ semconv.CodingAgentClient: in.Vendor,
+ semconv.CodingAgentHookEvent: "session.deleted",
+ },
+ })
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if value = strings.TrimSpace(value); value != "" {
+ return value
+ }
+ }
+ return ""
+}
diff --git a/cli/internal/coding/hook/opencode/message.go b/cli/internal/coding/hook/opencode/message.go
new file mode 100644
index 00000000..f2c835a0
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/message.go
@@ -0,0 +1,171 @@
+package opencode
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+func init() {
+ eventHandlers["message.updated"] = handleMessageUpdated
+}
+
+type messageUpdatedProperties struct {
+ Info messageInfo `json:"info"`
+}
+
+// messageInfo intentionally contains metadata fields only. OpenCode emits
+// text and reasoning through message-part events; this adapter does not read
+// those bodies, even when content capture is configured as full.
+type messageInfo struct {
+ ID string `json:"id"`
+ SessionID string `json:"sessionID"`
+ Role string `json:"role"`
+ Mode string `json:"mode"`
+ ModelID string `json:"modelID"`
+ ProviderID string `json:"providerID"`
+ Model struct {
+ ModelID string `json:"modelID"`
+ ProviderID string `json:"providerID"`
+ } `json:"model"`
+ Time struct {
+ Created int64 `json:"created"`
+ Completed int64 `json:"completed"`
+ } `json:"time"`
+ Cost float64 `json:"cost"`
+ Finish string `json:"finish"`
+ Tokens struct {
+ Input int64 `json:"input"`
+ Output int64 `json:"output"`
+ Reasoning int64 `json:"reasoning"`
+ Cache struct {
+ Read int64 `json:"read"`
+ Write int64 `json:"write"`
+ } `json:"cache"`
+ } `json:"tokens"`
+}
+
+func handleMessageUpdated(_ context.Context, in normalize.Input, payload payloadEnvelope) error {
+ var properties messageUpdatedProperties
+ if err := json.Unmarshal(payload.Event.Properties, &properties); err != nil {
+ return nil
+ }
+ info := properties.Info
+ sessionID := strings.TrimSpace(info.SessionID)
+ if sessionID == "" {
+ return nil
+ }
+ role := strings.ToLower(strings.TrimSpace(info.Role))
+ if role != "assistant" || info.Time.Completed <= 0 {
+ return nil
+ }
+ messageID := strings.TrimSpace(info.ID)
+ if messageID == "" {
+ return nil
+ }
+
+ model := firstNonEmpty(info.Model.ModelID, info.ModelID)
+ provider := firstNonEmpty(info.Model.ProviderID, info.ProviderID)
+ createdAt := timeFromUnixMillis(info.Time.Created)
+ if createdAt.IsZero() {
+ createdAt = time.Now()
+ }
+ endedAt := createdAt
+ if completedAt := timeFromUnixMillis(info.Time.Completed); !completedAt.IsZero() {
+ endedAt = completedAt
+ }
+
+ state := sessionstate.Load(sessionID, in.Vendor)
+ if state == nil {
+ state = &sessionstate.State{}
+ }
+ if state.ConversationID == "" {
+ state.ConversationID = sessionID
+ }
+ if state.SessionStartedAt.IsZero() {
+ state.SessionStartedAt = createdAt
+ }
+ if model != "" {
+ state.Model = model
+ }
+ if mode := strings.TrimSpace(info.Mode); mode != "" {
+ state.PermissionMode = mode
+ }
+ for _, emittedID := range state.EmittedAssistantTurnIDs {
+ if emittedID == messageID {
+ sessionstate.Save(sessionID, in.Vendor, state)
+ return nil
+ }
+ }
+ state.EmittedAssistantTurnIDs = append(state.EmittedAssistantTurnIDs, messageID)
+ if len(state.EmittedAssistantTurnIDs) > 256 {
+ state.EmittedAssistantTurnIDs = state.EmittedAssistantTurnIDs[len(state.EmittedAssistantTurnIDs)-256:]
+ }
+
+ extras := map[string]string{}
+ if provider != "" {
+ extras[semconv.GenAISystem] = provider
+ extras[semconv.GenAIProviderName] = provider
+ }
+ turn := normalize.LLMTurn{
+ SessionID: sessionID,
+ ConversationID: firstNonEmpty(state.ConversationID, sessionID),
+ GenerationID: messageID,
+ Vendor: in.Vendor,
+ Model: model,
+ StartedAt: createdAt,
+ EndedAt: endedAt,
+ Extras: extras,
+ }
+ turn.AssistantMessageOnly = true
+ cacheRead := nonNegative(info.Tokens.Cache.Read)
+ cacheWrite := nonNegative(info.Tokens.Cache.Write)
+ reasoning := nonNegative(info.Tokens.Reasoning)
+ turn.InputTokens = nonNegative(info.Tokens.Input)
+ turn.OutputTokens = nonNegative(info.Tokens.Output)
+ turn.ReasoningTokens = reasoning
+ turn.TotalTokens = turn.InputTokens + turn.OutputTokens + reasoning + cacheRead + cacheWrite
+ turn.CacheReadTokens = cacheRead
+ turn.CacheCreationTokens = cacheWrite
+ if info.Cost > 0 {
+ turn.CostUSD = info.Cost
+ }
+ if finish := strings.TrimSpace(info.Finish); finish != "" {
+ turn.FinishReasons = []string{finish}
+ }
+ if in.ContentCapture != semconv.CodingAgentContentCaptureMinimal {
+ state.InputTokens += turn.InputTokens
+ state.OutputTokens += turn.OutputTokens
+ state.TotalTokens += turn.TotalTokens
+ state.CostUSD += turn.CostUSD
+ // This turn is emitted on its own span, so it is already represented
+ // in downstream usage totals. Advance the snapshot watermarks by the
+ // same increment; assigning the lifetime totals here would incorrectly
+ // consume earlier minimal-mode usage that has not been flushed yet.
+ state.OpenCodeSnapshotInputTokens += turn.InputTokens
+ state.OpenCodeSnapshotOutputTokens += turn.OutputTokens
+ state.OpenCodeSnapshotTotalTokens += turn.TotalTokens
+ state.OpenCodeSnapshotCostUSD += turn.CostUSD
+ }
+ sessionstate.Save(sessionID, in.Vendor, state)
+ return in.Emit.EmitLLMTurn(turn)
+}
+
+func timeFromUnixMillis(value int64) time.Time {
+ if value <= 0 {
+ return time.Time{}
+ }
+ return time.UnixMilli(value)
+}
+
+func nonNegative(value int64) int64 {
+ if value < 0 {
+ return 0
+ }
+ return value
+}
diff --git a/cli/internal/coding/hook/opencode/message_test.go b/cli/internal/coding/hook/opencode/message_test.go
new file mode 100644
index 00000000..e78e032d
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/message_test.go
@@ -0,0 +1,124 @@
+package opencode
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+func TestMessageUpdatedEmitsMetadataWithoutBodies(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ adapter := New()
+ createdAt := time.Now().UTC().Add(-time.Second).Truncate(time.Millisecond)
+ userMessage := map[string]any{
+ "event": map[string]any{
+ "type": "message.updated",
+ "properties": map[string]any{
+ "info": map[string]any{
+ "id": "msg_user_1",
+ "sessionID": "ses_messages",
+ "role": "user",
+ "time": map[string]any{
+ "created": createdAt.UnixMilli(),
+ },
+ "model": map[string]any{
+ "providerID": "anthropic",
+ "modelID": "claude-sonnet-4-5",
+ },
+ "content": "prompt-secret-must-not-leak",
+ "text": "prompt-secret-must-not-leak",
+ "reasoning": "reasoning-secret-must-not-leak",
+ },
+ },
+ },
+ }
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "message.updated", "full", userMessage)); err != nil {
+ t.Fatalf("user message.updated: %v", err)
+ }
+ if len(em.llmTurns) != 0 {
+ t.Fatalf("metadata-only user update emitted %d LLM turns, want 0", len(em.llmTurns))
+ }
+
+ completedAt := createdAt.Add(750 * time.Millisecond)
+ assistantMessage := map[string]any{
+ "event": map[string]any{
+ "type": "message.updated",
+ "properties": map[string]any{
+ "info": map[string]any{
+ "id": "msg_assistant_1",
+ "sessionID": "ses_messages",
+ "role": "assistant",
+ "modelID": "claude-sonnet-4-5",
+ "providerID": "anthropic",
+ "mode": "plan",
+ "time": map[string]any{
+ "created": createdAt.UnixMilli(),
+ "completed": completedAt.UnixMilli(),
+ },
+ "cost": 0.0125,
+ "tokens": map[string]any{
+ "input": 100,
+ "output": 20,
+ "reasoning": 5,
+ "cache": map[string]any{
+ "read": 40,
+ "write": 10,
+ },
+ },
+ "finish": "stop",
+ "content": "assistant-secret-must-not-leak",
+ "text": "assistant-secret-must-not-leak",
+ "reasoning": "reasoning-secret-must-not-leak",
+ },
+ },
+ },
+ }
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "message.updated", "full", assistantMessage)); err != nil {
+ t.Fatalf("assistant message.updated: %v", err)
+ }
+ if len(em.llmTurns) != 1 {
+ t.Fatalf("assistant message brought total to %d LLM turns, want 1", len(em.llmTurns))
+ }
+ assistantTurn := em.llmTurns[0]
+ if !assistantTurn.AssistantMessageOnly {
+ t.Error("assistant message turn is not marked AssistantMessageOnly")
+ }
+ if assistantTurn.InputTokens != 100 || assistantTurn.OutputTokens != 20 || assistantTurn.TotalTokens != 175 {
+ t.Errorf("assistant token totals = %d/%d/%d, want 100/20/175", assistantTurn.InputTokens, assistantTurn.OutputTokens, assistantTurn.TotalTokens)
+ }
+ if assistantTurn.ReasoningTokens != 5 {
+ t.Errorf("assistant reasoning tokens = %d, want 5", assistantTurn.ReasoningTokens)
+ }
+ if assistantTurn.CacheReadTokens != 40 || assistantTurn.CacheCreationTokens != 10 {
+ t.Errorf("assistant cache tokens = %d/%d, want 40/10", assistantTurn.CacheReadTokens, assistantTurn.CacheCreationTokens)
+ }
+ if assistantTurn.CostUSD != 0.0125 {
+ t.Errorf("assistant cost = %v, want 0.0125", assistantTurn.CostUSD)
+ }
+ if len(assistantTurn.FinishReasons) != 1 || assistantTurn.FinishReasons[0] != "stop" {
+ t.Errorf("assistant finish reasons = %v, want [stop]", assistantTurn.FinishReasons)
+ }
+ if _, ok := assistantTurn.Extras[semconv.CodingAgentLLMTurnKind]; ok {
+ t.Error("assistant turn kind bypassed the canonical emitter mapping")
+ }
+ assertNoMessageBodies(t, assistantTurn)
+
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "message.updated", "full", assistantMessage)); err != nil {
+ t.Fatalf("duplicate assistant message.updated: %v", err)
+ }
+ if len(em.llmTurns) != 1 {
+ t.Fatalf("duplicate completed assistant emitted %d total turns, want 1", len(em.llmTurns))
+ }
+}
+
+func assertNoMessageBodies(t *testing.T, turn normalize.LLMTurn) {
+ t.Helper()
+ if turn.Prompt != "" || turn.Response != "" || turn.ThoughtText != "" {
+ t.Errorf("message body leaked: prompt=%q response=%q thought=%q", turn.Prompt, turn.Response, turn.ThoughtText)
+ }
+}
diff --git a/cli/internal/coding/hook/opencode/opencode.go b/cli/internal/coding/hook/opencode/opencode.go
new file mode 100644
index 00000000..e6efeb38
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/opencode.go
@@ -0,0 +1,20 @@
+// Package opencode implements the OpenCode hook adapter.
+package opencode
+
+import (
+ "context"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+// New returns a new OpenCode adapter.
+func New() normalize.Adapter { return &adapter{} }
+
+type adapter struct{}
+
+func (a *adapter) Vendor() string { return semconv.CodingAgentVendorOpenCode }
+
+func (a *adapter) Handle(ctx context.Context, in normalize.Input) error {
+ return handle(ctx, in)
+}
diff --git a/cli/internal/coding/hook/opencode/opencode_test.go b/cli/internal/coding/hook/opencode/opencode_test.go
new file mode 100644
index 00000000..3f6fe432
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/opencode_test.go
@@ -0,0 +1,9 @@
+package opencode
+
+import "testing"
+
+func TestAdapterVendor(t *testing.T) {
+ if got := New().Vendor(); got != "opencode" {
+ t.Fatalf("Vendor() = %q, want %q", got, "opencode")
+ }
+}
diff --git a/cli/internal/coding/hook/opencode/privacy.go b/cli/internal/coding/hook/opencode/privacy.go
new file mode 100644
index 00000000..fed319b3
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/privacy.go
@@ -0,0 +1,16 @@
+package opencode
+
+import (
+ "context"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+)
+
+func init() {
+ eventHandlers["chat.message"] = ignoreBodyBearingMessageEvent
+ eventHandlers["message.part.updated"] = ignoreBodyBearingMessageEvent
+}
+
+func ignoreBodyBearingMessageEvent(context.Context, normalize.Input, payloadEnvelope) error {
+ return nil
+}
diff --git a/cli/internal/coding/hook/opencode/privacy_test.go b/cli/internal/coding/hook/opencode/privacy_test.go
new file mode 100644
index 00000000..1f5731db
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/privacy_test.go
@@ -0,0 +1,58 @@
+package opencode
+
+import (
+ "context"
+ "testing"
+)
+
+func TestBodyBearingMessageEventsAreIgnored(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ adapter := New()
+ payloads := []struct {
+ event string
+ payload map[string]any
+ }{
+ {
+ event: "chat.message",
+ payload: map[string]any{
+ "event": map[string]any{
+ "type": "chat.message",
+ "properties": map[string]any{
+ "sessionID": "ses_private",
+ "parts": []map[string]any{{
+ "type": "text",
+ "text": "chat-message-secret",
+ }},
+ },
+ },
+ },
+ },
+ {
+ event: "message.part.updated",
+ payload: map[string]any{
+ "event": map[string]any{
+ "type": "message.part.updated",
+ "properties": map[string]any{
+ "part": map[string]any{
+ "sessionID": "ses_private",
+ "type": "reasoning",
+ "text": "reasoning-part-secret",
+ },
+ "delta": "reasoning-delta-secret",
+ },
+ },
+ },
+ },
+ }
+ for _, test := range payloads {
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, test.event, "full", test.payload)); err != nil {
+ t.Fatalf("%s: %v", test.event, err)
+ }
+ }
+ if len(em.llmTurns) != 0 || len(em.events) != 0 || len(em.toolCalls) != 0 || len(em.sessions) != 0 {
+ t.Fatalf("body-bearing events emitted telemetry: turns=%d events=%d tools=%d sessions=%d",
+ len(em.llmTurns), len(em.events), len(em.toolCalls), len(em.sessions))
+ }
+}
diff --git a/cli/internal/coding/hook/opencode/tool.go b/cli/internal/coding/hook/opencode/tool.go
new file mode 100644
index 00000000..2a038b8c
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/tool.go
@@ -0,0 +1,303 @@
+package opencode
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/cli/internal/coding/sessionstate"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
+
+func init() {
+ eventHandlers["tool.execute.before"] = handleToolExecuteBefore
+ eventHandlers["tool.execute.after"] = handleToolExecuteAfter
+ eventHandlers["tool.execute.completed"] = handleToolExecuteCompleted
+ eventHandlers["tool.execute.error"] = handleToolExecuteError
+}
+
+type toolProperties struct {
+ Tool string `json:"tool"`
+ SessionID string `json:"sessionID"`
+ CallID string `json:"callID"`
+ Args json.RawMessage `json:"args"`
+ Output json.RawMessage `json:"output"`
+ Metadata json.RawMessage `json:"metadata"`
+ Status string `json:"status"`
+ StartedAt int64 `json:"startedAt"`
+ EndedAt int64 `json:"endedAt"`
+}
+
+func handleToolExecuteBefore(_ context.Context, in normalize.Input, payload payloadEnvelope) error {
+ properties, ok := decodeToolProperties(payload.Event.Properties)
+ if !ok || !validToolIdentity(properties) {
+ return nil
+ }
+ cwd := firstNonEmpty(payload.Directory, payload.Worktree)
+ rememberToolContext(properties.SessionID, in.Vendor, cwd)
+ at := timeFromUnixMillis(properties.StartedAt)
+ if at.IsZero() {
+ at = time.Now()
+ }
+ return in.Emit.EmitEvent(normalize.EventEmission{
+ SessionID: properties.SessionID,
+ Name: "coding_agent.tool.requested",
+ At: at,
+ Attrs: map[string]any{
+ semconv.CodingAgentClient: in.Vendor,
+ semconv.CodingAgentHookEvent: "tool.execute.before",
+ "gen_ai.tool.name": properties.Tool,
+ "gen_ai.tool.call.id": properties.CallID,
+ "code.cwd": cwd,
+ },
+ })
+}
+
+func handleToolExecuteAfter(_ context.Context, in normalize.Input, payload payloadEnvelope) error {
+ properties, ok := decodeToolProperties(payload.Event.Properties)
+ if !ok || !validToolIdentity(properties) {
+ return nil
+ }
+ errored, errorMessage := toolError(properties.Metadata)
+ return emitTerminalToolCall(in, payload, properties, errored, errorMessage, true)
+}
+
+func handleToolExecuteCompleted(_ context.Context, in normalize.Input, payload payloadEnvelope) error {
+ properties, ok := decodeToolProperties(payload.Event.Properties)
+ if !ok || !validToolIdentity(properties) || !strings.EqualFold(properties.Status, "completed") {
+ return nil
+ }
+ // Provider-executed tools bypass OpenCode's explicit before/after hooks.
+ // The plugin projects only safe terminal metadata from their ToolPart.
+ return emitTerminalToolCall(in, payload, properties, false, "", false)
+}
+
+func handleToolExecuteError(_ context.Context, in normalize.Input, payload payloadEnvelope) error {
+ properties, ok := decodeToolProperties(payload.Event.Properties)
+ if !ok || !validToolIdentity(properties) || !strings.EqualFold(properties.Status, "error") {
+ return nil
+ }
+ // This event is a safe projection of a body-bearing ToolPart. Never
+ // read args, output, or the raw error string from it, even in full mode.
+ return emitTerminalToolCall(in, payload, properties, true, "", false)
+}
+
+func emitTerminalToolCall(
+ in normalize.Input,
+ payload payloadEnvelope,
+ properties toolProperties,
+ errored bool,
+ errorMessage string,
+ allowBodies bool,
+) error {
+ cwd := firstNonEmpty(payload.Directory, payload.Worktree)
+ if !claimToolCall(properties.SessionID, in.Vendor, properties.CallID, cwd, in.ContentCapture) {
+ return nil
+ }
+ startedAt := timeFromUnixMillis(properties.StartedAt)
+ endedAt := timeFromUnixMillis(properties.EndedAt)
+ if startedAt.IsZero() {
+ startedAt = time.Now()
+ }
+ if endedAt.IsZero() || endedAt.Before(startedAt) {
+ endedAt = startedAt
+ }
+ call := normalize.ToolCall{
+ SessionID: properties.SessionID,
+ ToolName: properties.Tool,
+ ToolUseID: properties.CallID,
+ Vendor: in.Vendor,
+ StartedAt: startedAt,
+ EndedAt: endedAt,
+ Duration: endedAt.Sub(startedAt),
+ Errored: errored,
+ WorkingDir: cwd,
+ }
+ if allowBodies {
+ call.Command = commandFromArgs(properties.Tool, properties.Args, in.ContentCapture)
+ }
+ if errored {
+ call.FailureType = "error"
+ }
+ if allowBodies && in.ContentCapture == semconv.CodingAgentContentCaptureFull {
+ call.Args = rawJSON(properties.Args)
+ call.Result = rawJSON(properties.Output)
+ call.ErrorMsg = errorMessage
+ }
+ return in.Emit.EmitToolCall(call)
+}
+
+func validToolIdentity(properties toolProperties) bool {
+ return properties.SessionID != "" && properties.Tool != "" && properties.CallID != ""
+}
+
+func decodeToolProperties(raw json.RawMessage) (toolProperties, bool) {
+ var properties toolProperties
+ if err := json.Unmarshal(raw, &properties); err != nil {
+ return toolProperties{}, false
+ }
+ properties.Tool = strings.TrimSpace(properties.Tool)
+ properties.SessionID = strings.TrimSpace(properties.SessionID)
+ properties.CallID = strings.TrimSpace(properties.CallID)
+ properties.Status = strings.TrimSpace(properties.Status)
+ return properties, true
+}
+
+func claimToolCall(sessionID, vendor, callID, cwd, capture string) bool {
+ state := sessionstate.Load(sessionID, vendor)
+ for _, emittedID := range state.EmittedToolCallIDs {
+ if emittedID == callID {
+ return false
+ }
+ }
+ state.EmittedToolCallIDs = append(state.EmittedToolCallIDs, callID)
+ if len(state.EmittedToolCallIDs) > 256 {
+ state.EmittedToolCallIDs = state.EmittedToolCallIDs[len(state.EmittedToolCallIDs)-256:]
+ }
+ if state.ConversationID == "" {
+ state.ConversationID = sessionID
+ }
+ if state.SessionStartedAt.IsZero() {
+ state.SessionStartedAt = time.Now()
+ }
+ if cwd != "" {
+ state.CWD = cwd
+ }
+ if capture != semconv.CodingAgentContentCaptureMinimal {
+ state.ToolCallCount++
+ }
+ sessionstate.Save(sessionID, vendor, state)
+ return true
+}
+
+func rememberToolContext(sessionID, vendor, cwd string) {
+ state := sessionstate.Load(sessionID, vendor)
+ if state == nil {
+ state = &sessionstate.State{}
+ }
+ if state.ConversationID == "" {
+ state.ConversationID = sessionID
+ }
+ if state.SessionStartedAt.IsZero() {
+ state.SessionStartedAt = time.Now()
+ }
+ if cwd != "" {
+ state.CWD = cwd
+ }
+ sessionstate.Save(sessionID, vendor, state)
+}
+
+func rawJSON(raw json.RawMessage) string {
+ trimmed := strings.TrimSpace(string(raw))
+ if trimmed == "" || trimmed == "null" {
+ return ""
+ }
+ var value string
+ if err := json.Unmarshal(raw, &value); err == nil {
+ return value
+ }
+ return trimmed
+}
+
+func commandFromArgs(tool string, raw json.RawMessage, capture string) string {
+ switch strings.ToLower(strings.TrimSpace(tool)) {
+ case "bash", "shell", "sh", "zsh", "powershell", "pwsh":
+ default:
+ return ""
+ }
+ var args map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &args); err != nil {
+ return ""
+ }
+ var command string
+ for _, key := range []string{"command", "cmd", "shell"} {
+ value, ok := args[key]
+ if !ok {
+ continue
+ }
+ if err := json.Unmarshal(value, &command); err == nil && strings.TrimSpace(command) != "" {
+ break
+ }
+ var parts []string
+ if err := json.Unmarshal(value, &parts); err == nil && len(parts) > 0 {
+ command = strings.Join(parts, " ")
+ break
+ }
+ }
+ command = strings.TrimSpace(command)
+ if command == "" || capture == semconv.CodingAgentContentCaptureFull {
+ return command
+ }
+ fields := strings.Fields(command)
+ if len(fields) == 0 || strings.Contains(fields[0], "=") {
+ return ""
+ }
+ return fields[0]
+}
+
+func toolError(raw json.RawMessage) (bool, string) {
+ if len(raw) == 0 || strings.TrimSpace(string(raw)) == "null" {
+ return false, ""
+ }
+ var metadata map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &metadata); err != nil {
+ return false, ""
+ }
+ if status := rawString(metadata["status"]); status != "" {
+ switch strings.ToLower(status) {
+ case "error", "failed", "failure":
+ return true, rawErrorMessage(metadata["error"])
+ }
+ }
+ for _, key := range []string{"exit", "exitCode", "exit_code"} {
+ if value, ok := rawNumber(metadata[key]); ok && value != 0 {
+ return true, rawErrorMessage(metadata["error"])
+ }
+ }
+ if errorValue, ok := metadata["error"]; ok && hasJSONError(errorValue) {
+ return true, rawErrorMessage(errorValue)
+ }
+ return false, ""
+}
+
+func rawString(raw json.RawMessage) string {
+ var value string
+ if len(raw) > 0 && json.Unmarshal(raw, &value) == nil {
+ return strings.TrimSpace(value)
+ }
+ return ""
+}
+
+func rawNumber(raw json.RawMessage) (float64, bool) {
+ var value float64
+ if len(raw) == 0 || json.Unmarshal(raw, &value) != nil {
+ return 0, false
+ }
+ return value, true
+}
+
+func hasJSONError(raw json.RawMessage) bool {
+ trimmed := strings.TrimSpace(string(raw))
+ if trimmed == "" || trimmed == "null" || trimmed == "false" || trimmed == `""` || trimmed == "{}" || trimmed == "[]" {
+ return false
+ }
+ return true
+}
+
+func rawErrorMessage(raw json.RawMessage) string {
+ if !hasJSONError(raw) {
+ return ""
+ }
+ if value := rawString(raw); value != "" {
+ return value
+ }
+ var object struct {
+ Message string `json:"message"`
+ }
+ if json.Unmarshal(raw, &object) == nil {
+ return object.Message
+ }
+ return ""
+}
diff --git a/cli/internal/coding/hook/opencode/tool_test.go b/cli/internal/coding/hook/opencode/tool_test.go
new file mode 100644
index 00000000..de198b80
--- /dev/null
+++ b/cli/internal/coding/hook/opencode/tool_test.go
@@ -0,0 +1,219 @@
+package opencode
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestToolExecuteEmitsOneCanonicalCallAfterCompletion(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ adapter := New()
+ directory := t.TempDir()
+ startedAt := time.Now().UTC().Add(-250 * time.Millisecond).Truncate(time.Millisecond)
+ endedAt := startedAt.Add(200 * time.Millisecond)
+ properties := map[string]any{
+ "tool": "bash",
+ "sessionID": "ses_tool_full",
+ "callID": "call_42",
+ "startedAt": startedAt.UnixMilli(),
+ "args": map[string]any{
+ "command": "echo full-secret-argument",
+ },
+ }
+ before := map[string]any{
+ "event": map[string]any{
+ "type": "tool.execute.before",
+ "properties": properties,
+ },
+ "directory": directory,
+ "worktree": directory,
+ }
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "tool.execute.before", "full", before)); err != nil {
+ t.Fatalf("tool.execute.before: %v", err)
+ }
+ if len(em.toolCalls) != 0 {
+ t.Fatalf("tool.execute.before emitted %d tool calls, want 0", len(em.toolCalls))
+ }
+ if len(em.events) != 1 || em.events[0].Name != "coding_agent.tool.requested" {
+ t.Fatalf("tool.execute.before event = %+v, want coding_agent.tool.requested", em.events)
+ }
+ if _, ok := em.events[0].Attrs["args"]; ok {
+ t.Fatalf("tool request event leaked args: %+v", em.events[0].Attrs)
+ }
+
+ afterProperties := map[string]any{}
+ for key, value := range properties {
+ afterProperties[key] = value
+ }
+ afterProperties["title"] = "shell"
+ afterProperties["output"] = "full-secret-result"
+ afterProperties["metadata"] = map[string]any{"exit": 0}
+ afterProperties["endedAt"] = endedAt.UnixMilli()
+ after := map[string]any{
+ "event": map[string]any{
+ "type": "tool.execute.after",
+ "properties": afterProperties,
+ },
+ "directory": directory,
+ "worktree": directory,
+ }
+ if err := adapter.Handle(context.Background(), adapterInput(t, em, "tool.execute.after", "full", after)); err != nil {
+ t.Fatalf("tool.execute.after: %v", err)
+ }
+ if len(em.toolCalls) != 1 {
+ t.Fatalf("tool.execute.after emitted %d tool calls, want 1", len(em.toolCalls))
+ }
+ got := em.toolCalls[0]
+ if got.SessionID != "ses_tool_full" || got.ToolName != "bash" || got.ToolUseID != "call_42" || got.Vendor != "opencode" {
+ t.Errorf("tool identity = %+v", got)
+ }
+ if got.WorkingDir != directory {
+ t.Errorf("tool working dir = %q, want %q", got.WorkingDir, directory)
+ }
+ if !got.StartedAt.Equal(startedAt) || !got.EndedAt.Equal(endedAt) || got.Duration != 200*time.Millisecond {
+ t.Errorf("tool timing = %s/%s (%s), want %s/%s (200ms)", got.StartedAt, got.EndedAt, got.Duration, startedAt, endedAt)
+ }
+ if got.Errored {
+ t.Error("successful tool call marked errored")
+ }
+ if !strings.Contains(got.Args, "full-secret-argument") || got.Result != "full-secret-result" {
+ t.Errorf("full capture args/result = %q/%q", got.Args, got.Result)
+ }
+ if got.Command != "echo full-secret-argument" {
+ t.Errorf("full capture command = %q, want full command", got.Command)
+ }
+}
+
+func TestToolPartErrorEmitsOneBodyFreeFailedCall(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ startedAt := time.Now().UTC().Add(-500 * time.Millisecond).Truncate(time.Millisecond)
+ endedAt := startedAt.Add(450 * time.Millisecond)
+ payload := map[string]any{
+ "event": map[string]any{
+ "type": "tool.execute.error",
+ "properties": map[string]any{
+ "tool": "bash",
+ "sessionID": "ses_tool_error",
+ "callID": "call_failed",
+ "status": "error",
+ "startedAt": startedAt.UnixMilli(),
+ "endedAt": endedAt.UnixMilli(),
+ "args": "must-not-be-forwarded",
+ "output": "must-not-be-forwarded",
+ "error": "must-not-be-forwarded",
+ },
+ },
+ "directory": t.TempDir(),
+ }
+ input := adapterInput(t, em, "tool.execute.error", "full", payload)
+ if err := New().Handle(context.Background(), input); err != nil {
+ t.Fatalf("tool.execute.error: %v", err)
+ }
+ if err := New().Handle(context.Background(), input); err != nil {
+ t.Fatalf("duplicate tool.execute.error: %v", err)
+ }
+ if len(em.toolCalls) != 1 {
+ t.Fatalf("emitted %d failed calls, want exactly 1", len(em.toolCalls))
+ }
+ got := em.toolCalls[0]
+ if !got.Errored || got.FailureType != "error" {
+ t.Errorf("failed tool status = errored:%v failure:%q", got.Errored, got.FailureType)
+ }
+ if !got.StartedAt.Equal(startedAt) || !got.EndedAt.Equal(endedAt) || got.Duration != 450*time.Millisecond {
+ t.Errorf("failed tool timing = %s/%s (%s)", got.StartedAt, got.EndedAt, got.Duration)
+ }
+ if got.Args != "" || got.Result != "" || got.ErrorMsg != "" {
+ t.Errorf("safe failure projection leaked bodies: args=%q result=%q error=%q", got.Args, got.Result, got.ErrorMsg)
+ }
+}
+
+func TestProviderExecutedToolPartEmitsOneBodyFreeSuccessfulCall(t *testing.T) {
+ withIsolatedCache(t)
+
+ em := &recordingEmitter{}
+ startedAt := time.Now().UTC().Add(-500 * time.Millisecond).Truncate(time.Millisecond)
+ endedAt := startedAt.Add(450 * time.Millisecond)
+ payload := map[string]any{
+ "event": map[string]any{
+ "type": "tool.execute.completed",
+ "properties": map[string]any{
+ "tool": "websearch",
+ "sessionID": "ses_provider_tool",
+ "callID": "call_provider",
+ "status": "completed",
+ "startedAt": startedAt.UnixMilli(),
+ "endedAt": endedAt.UnixMilli(),
+ "args": "must-not-be-forwarded",
+ "output": "must-not-be-forwarded",
+ },
+ },
+ "directory": t.TempDir(),
+ }
+ input := adapterInput(t, em, "tool.execute.completed", "full", payload)
+ if err := New().Handle(context.Background(), input); err != nil {
+ t.Fatalf("tool.execute.completed: %v", err)
+ }
+ if err := New().Handle(context.Background(), input); err != nil {
+ t.Fatalf("duplicate tool.execute.completed: %v", err)
+ }
+ if len(em.toolCalls) != 1 {
+ t.Fatalf("emitted %d provider tool calls, want exactly 1", len(em.toolCalls))
+ }
+ got := em.toolCalls[0]
+ if got.Errored || got.FailureType != "" {
+ t.Errorf("provider tool status = errored:%v failure:%q", got.Errored, got.FailureType)
+ }
+ if got.ToolName != "websearch" || got.ToolUseID != "call_provider" {
+ t.Errorf("provider tool identity = %+v", got)
+ }
+ if !got.StartedAt.Equal(startedAt) || !got.EndedAt.Equal(endedAt) || got.Duration != 450*time.Millisecond {
+ t.Errorf("provider tool timing = %s/%s (%s)", got.StartedAt, got.EndedAt, got.Duration)
+ }
+ if got.Args != "" || got.Result != "" || got.ErrorMsg != "" {
+ t.Errorf("safe provider projection leaked bodies: args=%q result=%q error=%q", got.Args, got.Result, got.ErrorMsg)
+ }
+}
+
+func TestToolExecuteCaptureModesDoNotLeakBodies(t *testing.T) {
+ for _, capture := range []string{"metadata_only", "minimal"} {
+ t.Run(capture, func(t *testing.T) {
+ withIsolatedCache(t)
+ em := &recordingEmitter{}
+ payload := map[string]any{
+ "event": map[string]any{
+ "type": "tool.execute.after",
+ "properties": map[string]any{
+ "tool": "bash",
+ "sessionID": "ses_tool_" + capture,
+ "callID": "call_private",
+ "args": map[string]any{
+ "command": "echo non-full-secret-argument",
+ },
+ "output": "non-full-secret-result",
+ "metadata": map[string]any{"error": "non-full-secret-error"},
+ },
+ },
+ "directory": t.TempDir(),
+ }
+ if err := New().Handle(context.Background(), adapterInput(t, em, "tool.execute.after", capture, payload)); err != nil {
+ t.Fatalf("tool.execute.after: %v", err)
+ }
+ if len(em.toolCalls) != 1 {
+ t.Fatalf("emitted %d tool calls, want 1", len(em.toolCalls))
+ }
+ got := em.toolCalls[0]
+ if got.Args != "" || got.Result != "" || got.ErrorMsg != "" {
+ t.Errorf("%s leaked bodies: args=%q result=%q error=%q", capture, got.Args, got.Result, got.ErrorMsg)
+ }
+ if got.Command != "echo" {
+ t.Errorf("%s command = %q, want executable-only metadata", capture, got.Command)
+ }
+ })
+ }
+}
diff --git a/cli/internal/coding/install/install.go b/cli/internal/coding/install/install.go
index 0d0490e7..df4acd9f 100644
--- a/cli/internal/coding/install/install.go
+++ b/cli/internal/coding/install/install.go
@@ -1,7 +1,7 @@
// 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
+// so the agent (Claude Code, Cursor, Codex, OpenCode) 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
@@ -33,7 +33,9 @@ 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
+ opencode Plugin under $XDG_CONFIG_HOME/opencode/plugins/ when set;
+ otherwise <user-home>/.config/opencode/plugins/
+ all shorthand for all four
The 'openlit' binary itself must be on PATH. Install via Homebrew, the
prebuilt binaries on GitHub Releases, the curl|sh installer, or
@@ -45,7 +47,7 @@ prebuilt binaries on GitHub Releases, the curl|sh installer, or
},
}
- cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor (claude-code | cursor | codex | all)")
+ cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor (claude-code | cursor | codex | opencode | all)")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print what would be written without modifying any files")
_ = cmd.MarkFlagRequired("vendor")
@@ -101,13 +103,15 @@ func run(cmd *cobra.Command, vendor string, dryRun bool) error {
func vendorsFromArg(arg string) ([]string, error) {
switch arg {
case "all":
- return []string{"claude-code", "cursor", "codex"}, nil
+ return []string{"claude-code", "cursor", "codex", "opencode"}, nil
case "claude-code", "cc":
return []string{"claude-code"}, nil
case "cursor":
return []string{"cursor"}, nil
case "codex":
return []string{"codex"}, nil
+ case "opencode":
+ return []string{"opencode"}, nil
default:
return nil, fmt.Errorf("unknown --vendor %q", arg)
}
diff --git a/cli/internal/coding/install/install_opencode.go b/cli/internal/coding/install/install_opencode.go
new file mode 100644
index 00000000..b51bd68c
--- /dev/null
+++ b/cli/internal/coding/install/install_opencode.go
@@ -0,0 +1,51 @@
+package install
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/openlit/openlit/cli/internal/coding/opencodeconfig"
+)
+
+const openCodePluginTemplate = "marketplace/plugins/opencode/openlit.ts"
+
+func installOpenCodePlugin(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)
+ }
+ target, err := opencodeconfig.PluginPath()
+ if err != nil {
+ return nil, err
+ }
+ return installOpenCodePluginAtPath(target, openlitBin, dryRun)
+}
+
+func installOpenCodePluginAt(home, openlitBin string, dryRun bool) ([]string, error) {
+ return installOpenCodePluginAtConfig(home, "", openlitBin, dryRun)
+}
+
+func installOpenCodePluginAtConfig(home, xdgConfigHome, openlitBin string, dryRun bool) ([]string, error) {
+ target := opencodeconfig.PluginPathAt(home, xdgConfigHome)
+ return installOpenCodePluginAtPath(target, openlitBin, dryRun)
+}
+
+func installOpenCodePluginAtPath(target, openlitBin string, dryRun bool) ([]string, error) {
+ body, err := marketplaceFS.ReadFile(openCodePluginTemplate)
+ if err != nil {
+ return nil, fmt.Errorf("read embedded opencode plugin: %w", err)
+ }
+ body = patchManifestBytes("openlit.ts", body, openlitBin)
+
+ if dryRun {
+ return []string{target}, nil
+ }
+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+ return nil, err
+ }
+ if err := os.WriteFile(target, body, 0o644); err != nil {
+ return nil, err
+ }
+ return []string{target}, nil
+}
diff --git a/cli/internal/coding/install/install_opencode_test.go b/cli/internal/coding/install/install_opencode_test.go
new file mode 100644
index 00000000..95c216b5
--- /dev/null
+++ b/cli/internal/coding/install/install_opencode_test.go
@@ -0,0 +1,225 @@
+package install
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestPatchManifestBytesQuotesOpenCodeBinaryForTypeScript(t *testing.T) {
+ t.Parallel()
+
+ body := []byte("const openlitBin = __OPENLIT_BIN_JSON__;\n")
+ got := string(patchManifestBytes("openlit.ts", body, "C:\\Program Files\\OpenLIT\\openlit.exe"))
+
+ if strings.Contains(got, "__OPENLIT_BIN_JSON__") {
+ t.Fatalf("binary placeholder was not replaced: %s", got)
+ }
+ if !strings.Contains(got, "\"C:\\\\Program Files\\\\OpenLIT\\\\openlit.exe\"") {
+ t.Fatalf("binary path is not a safe TypeScript string: %s", got)
+ }
+}
+
+func TestInstallOpenCodePluginAtIsDryRunSafeAndIdempotent(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ bin := filepath.Join(home, "OpenLIT Bin", "openlit")
+ target := filepath.Join(home, ".config", "opencode", "plugins", "openlit.ts")
+ other := filepath.Join(home, ".config", "opencode", "plugins", "keep.ts")
+
+ written, err := installOpenCodePluginAt(home, bin, true)
+ if err != nil {
+ t.Fatalf("dry-run: %v", err)
+ }
+ if len(written) != 1 || written[0] != target {
+ t.Fatalf("dry-run paths = %v, want [%s]", written, target)
+ }
+ if _, err := os.Stat(target); !os.IsNotExist(err) {
+ t.Fatalf("dry-run created target: %v", err)
+ }
+
+ if err := os.MkdirAll(filepath.Dir(other), 0o755); err != nil {
+ t.Fatalf("mkdir plugins: %v", err)
+ }
+ if err := os.WriteFile(other, []byte("user plugin"), 0o644); err != nil {
+ t.Fatalf("write unrelated plugin: %v", err)
+ }
+
+ if _, err := installOpenCodePluginAt(home, bin, false); err != nil {
+ t.Fatalf("first install: %v", err)
+ }
+ first, err := os.ReadFile(target)
+ if err != nil {
+ t.Fatalf("read installed plugin: %v", err)
+ }
+ if strings.Contains(string(first), "__OPENLIT_BIN_JSON__") {
+ t.Fatalf("installed plugin retained binary placeholder")
+ }
+
+ if _, err := installOpenCodePluginAt(home, bin, false); err != nil {
+ t.Fatalf("second install: %v", err)
+ }
+ second, err := os.ReadFile(target)
+ if err != nil {
+ t.Fatalf("read reinstalled plugin: %v", err)
+ }
+ if string(first) != string(second) {
+ t.Fatalf("reinstall changed plugin content")
+ }
+ if got, err := os.ReadFile(other); err != nil || string(got) != "user plugin" {
+ t.Fatalf("unrelated plugin changed: content=%q err=%v", got, err)
+ }
+}
+
+func TestInstallOpenCodePluginHonorsXDGConfigHome(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ xdgConfigHome := filepath.Join(t.TempDir(), "custom-config")
+ target := filepath.Join(xdgConfigHome, "opencode", "plugins", "openlit.ts")
+ bin := filepath.Join(home, "bin", "openlit")
+
+ written, err := installOpenCodePluginAtConfig(home, xdgConfigHome, bin, false)
+ if err != nil {
+ t.Fatalf("install with XDG_CONFIG_HOME: %v", err)
+ }
+ if len(written) != 1 || written[0] != target {
+ t.Fatalf("written paths = %v, want [%s]", written, target)
+ }
+ if _, err := os.Stat(target); err != nil {
+ t.Fatalf("XDG OpenCode plugin was not written: %v", err)
+ }
+ legacy := filepath.Join(home, ".config", "opencode", "plugins", "openlit.ts")
+ if _, err := os.Stat(legacy); !os.IsNotExist(err) {
+ t.Fatalf("legacy path was written despite XDG_CONFIG_HOME: %v", err)
+ }
+}
+
+func TestOpenCodePluginTemplateUsesSafeTimedSpawn(t *testing.T) {
+ t.Parallel()
+
+ body, err := marketplaceFS.ReadFile(openCodePluginTemplate)
+ if err != nil {
+ t.Fatalf("read OpenCode plugin template: %v", err)
+ }
+ source := string(body)
+ for _, want := range []string{
+ `const openlitBin = __OPENLIT_BIN_JSON__`,
+ "[openlitBin, \"coding\", \"hook\", \"--vendor=opencode\", `--event=${event.type}`]",
+ `const payload = new Blob([JSON.stringify({ event, directory, worktree })])`,
+ `stdin: payload`,
+ `timeout: 5_000`,
+ `windowsHide: true`,
+ } {
+ if !strings.Contains(source, want) {
+ t.Errorf("OpenCode plugin missing %q", want)
+ }
+ }
+ if strings.Contains(source, "\\${event.type}") {
+ t.Error("OpenCode event interpolation is escaped and would send a literal placeholder")
+ }
+ if strings.Contains(source, "Bun.$") {
+ t.Error("OpenCode plugin must not construct a shell command")
+ }
+}
+
+func TestOpenCodePluginGuardsMissingToolHookOutput(t *testing.T) {
+ t.Parallel()
+
+ body, err := marketplaceFS.ReadFile(openCodePluginTemplate)
+ if err != nil {
+ t.Fatalf("read OpenCode plugin template: %v", err)
+ }
+ source := string(body)
+ for _, want := range []string{
+ `const projectedOutput = asRecord(output)`,
+ `if (!projectedOutput)`,
+ `args: projectedOutput?.args`,
+ `title: projectedOutput.title`,
+ } {
+ if !strings.Contains(source, want) {
+ t.Errorf("OpenCode plugin missing safe tool-output handling %q", want)
+ }
+ }
+ for _, unsafe := range []string{
+ `args: output.args`,
+ `title: output.title`,
+ `output: output.output`,
+ `metadata: output.metadata`,
+ } {
+ if strings.Contains(source, unsafe) {
+ t.Errorf("OpenCode plugin directly dereferences hook output: %q", unsafe)
+ }
+ }
+}
+
+func TestOpenCodePluginProjectsGenericEventsBeforeSpawning(t *testing.T) {
+ t.Parallel()
+
+ body, err := marketplaceFS.ReadFile(openCodePluginTemplate)
+ if err != nil {
+ t.Fatalf("read OpenCode plugin template: %v", err)
+ }
+ source := string(body)
+ for _, want := range []string{
+ `function projectEvent(event: OpenCodeEvent): OpenCodeEvent | undefined`,
+ `"session.created"`,
+ `"message.updated"`,
+ `"session.idle"`,
+ `"session.error"`,
+ `"session.deleted"`,
+ `"message.part.updated"`,
+ `const isError = state?.status === "error"`,
+ `metadata?.providerExecuted === true`,
+ `type: isError ? "tool.execute.error" : "tool.execute.completed"`,
+ `const projected = projectEvent(event)`,
+ `if (!projected) return`,
+ } {
+ if !strings.Contains(source, want) {
+ t.Errorf("OpenCode plugin missing safe event projection %q", want)
+ }
+ }
+ for _, forbidden := range []string{
+ `"chat.message"`,
+ `...event`,
+ `...info`,
+ `...part`,
+ `...state`,
+ } {
+ if strings.Contains(source, forbidden) {
+ t.Errorf("OpenCode plugin must not forward unprojected content via %s", forbidden)
+ }
+ }
+}
+
+func TestOpenCodePluginQueuesTelemetryWithoutAwaitingItInHooks(t *testing.T) {
+ t.Parallel()
+
+ body, err := marketplaceFS.ReadFile(openCodePluginTemplate)
+ if err != nil {
+ t.Fatalf("read OpenCode plugin template: %v", err)
+ }
+ source := string(body)
+ for _, want := range []string{
+ `const maxQueuedEmissions = 32`,
+ `queueMicrotask(() => {`,
+ `if (queue.length >= maxQueuedEmissions)`,
+ `const dropIndex = queue.findIndex((pending) => pending.priority < priority)`,
+ `void enqueue(projected)`,
+ `void enqueue({`,
+ } {
+ if !strings.Contains(source, want) {
+ t.Errorf("OpenCode plugin missing non-blocking serial queue %q", want)
+ }
+ }
+ for _, forbidden := range []string{
+ `let pending = Promise.resolve()`,
+ `await enqueue(`,
+ } {
+ if strings.Contains(source, forbidden) {
+ t.Errorf("OpenCode hooks contain an unsafe queue pattern %q", forbidden)
+ }
+ }
+}
diff --git a/cli/internal/coding/install/install_patch.go b/cli/internal/coding/install/install_patch.go
index e0141dbf..6712d194 100644
--- a/cli/internal/coding/install/install_patch.go
+++ b/cli/internal/coding/install/install_patch.go
@@ -6,6 +6,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "strconv"
"strings"
)
@@ -17,6 +18,9 @@ import (
// don't find the CLI" failures.
func patchManifestBytes(_ string, body []byte, openlitBin string) []byte {
s := string(body)
+ if strings.Contains(s, "__OPENLIT_BIN_JSON__") {
+ s = strings.ReplaceAll(s, "__OPENLIT_BIN_JSON__", strconv.Quote(openlitBin))
+ }
if strings.Contains(s, "__OPENLIT_BIN__") {
s = strings.ReplaceAll(s, "__OPENLIT_BIN__", openlitBin)
}
diff --git a/cli/internal/coding/install/install_test.go b/cli/internal/coding/install/install_test.go
new file mode 100644
index 00000000..e4abd6f6
--- /dev/null
+++ b/cli/internal/coding/install/install_test.go
@@ -0,0 +1,28 @@
+package install
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestVendorsFromArgIncludesOpenCode(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ in string
+ want []string
+ }{
+ {in: "opencode", want: []string{"opencode"}},
+ {in: "all", want: []string{"claude-code", "cursor", "codex", "opencode"}},
+ }
+
+ for _, tc := range cases {
+ got, err := vendorsFromArg(tc.in)
+ if err != nil {
+ t.Fatalf("vendorsFromArg(%q): %v", tc.in, err)
+ }
+ if !reflect.DeepEqual(got, tc.want) {
+ t.Fatalf("vendorsFromArg(%q) = %v, want %v", tc.in, got, tc.want)
+ }
+ }
+}
diff --git a/cli/internal/coding/install/install_vendors.go b/cli/internal/coding/install/install_vendors.go
index 40712cdd..057783d7 100644
--- a/cli/internal/coding/install/install_vendors.go
+++ b/cli/internal/coding/install/install_vendors.go
@@ -15,7 +15,7 @@ import (
"strings"
)
-// marketplaceFS holds the embedded Claude Code marketplace tree. The
+// marketplaceFS holds the embedded coding-agent plugin 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
@@ -30,6 +30,7 @@ import (
// plugins/claude-code/
// plugins/cursor/
// plugins/codex/
+// plugins/opencode/
//
// Keeping the layouts identical means the single marketplace.json
// `source: "./plugins/claude-code"` resolves correctly whether Claude
@@ -52,6 +53,9 @@ func installVendor(vendor string, dryRun bool) ([]string, error) {
if vendor == "cursor" {
return installCursorHooks(dryRun)
}
+ if vendor == "opencode" {
+ return installOpenCodePlugin(dryRun)
+ }
dest, err := vendorDestRoot(vendor)
if err != nil {
diff --git a/cli/internal/coding/install/marketplace/plugins/opencode/openlit.ts b/cli/internal/coding/install/marketplace/plugins/opencode/openlit.ts
new file mode 100644
index 00000000..eb58ac37
--- /dev/null
+++ b/cli/internal/coding/install/marketplace/plugins/opencode/openlit.ts
@@ -0,0 +1,273 @@
+import type { Plugin } from "@opencode-ai/plugin"
+
+const openlitBin = __OPENLIT_BIN_JSON__
+// One additional event may be in-flight while this queue is full.
+const maxQueuedEmissions = 32
+
+type OpenCodeEvent = {
+ type: string
+ properties?: unknown
+}
+
+type JSONRecord = Record<string, unknown>
+
+type PendingEmission = {
+ event: OpenCodeEvent
+ priority: number
+}
+
+function asRecord(value: unknown): JSONRecord | undefined {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return
+ return value as JSONRecord
+}
+
+function projectSessionInfo(value: unknown): JSONRecord | undefined {
+ const info = asRecord(value)
+ if (!info) return
+ const time = asRecord(info.time)
+ return {
+ id: info.id,
+ directory: info.directory,
+ parentID: info.parentID,
+ version: info.version,
+ time: { created: time?.created },
+ }
+}
+
+function projectMessageInfo(value: unknown): JSONRecord | undefined {
+ const info = asRecord(value)
+ if (!info || info.role !== "assistant") return
+ const time = asRecord(info.time)
+ if (typeof time?.completed !== "number" || time.completed <= 0) return
+ const model = asRecord(info.model)
+ const tokens = asRecord(info.tokens)
+ const cache = asRecord(tokens?.cache)
+ return {
+ id: info.id,
+ sessionID: info.sessionID,
+ role: info.role,
+ mode: info.mode,
+ modelID: info.modelID,
+ providerID: info.providerID,
+ model: {
+ modelID: model?.modelID,
+ providerID: model?.providerID,
+ },
+ time: {
+ created: time.created,
+ completed: time.completed,
+ },
+ cost: info.cost,
+ finish: info.finish,
+ tokens: {
+ input: tokens?.input,
+ output: tokens?.output,
+ reasoning: tokens?.reasoning,
+ cache: {
+ read: cache?.read,
+ write: cache?.write,
+ },
+ },
+ }
+}
+
+function projectEvent(event: OpenCodeEvent): OpenCodeEvent | undefined {
+ const properties = asRecord(event.properties)
+ switch (event.type) {
+ case "session.created":
+ case "session.deleted": {
+ const info = projectSessionInfo(properties?.info)
+ if (!info) return
+ return { type: event.type, properties: { info } }
+ }
+ case "session.idle":
+ return {
+ type: event.type,
+ properties: { sessionID: properties?.sessionID },
+ }
+ case "session.error": {
+ const error = asRecord(properties?.error)
+ return {
+ type: event.type,
+ properties: {
+ sessionID: properties?.sessionID,
+ errorName: error?.name,
+ },
+ }
+ }
+ case "message.updated": {
+ const info = projectMessageInfo(properties?.info)
+ if (!info) return
+ return { type: event.type, properties: { info } }
+ }
+ case "message.part.updated": {
+ const part = asRecord(properties?.part)
+ const state = asRecord(part?.state)
+ if (part?.type !== "tool") return
+ const metadata = asRecord(part.metadata)
+ const isError = state?.status === "error"
+ const isProviderExecutedSuccess =
+ state?.status === "completed" && metadata?.providerExecuted === true
+ if (!isError && !isProviderExecutedSuccess) return
+ const time = asRecord(state.time)
+ return {
+ type: isError ? "tool.execute.error" : "tool.execute.completed",
+ properties: {
+ sessionID: part.sessionID,
+ callID: part.callID,
+ tool: part.tool,
+ status: state.status,
+ startedAt: time?.start,
+ endedAt: time?.end,
+ },
+ }
+ }
+ }
+}
+
+async function emit(event: OpenCodeEvent, directory: string, worktree: string) {
+ try {
+ const payload = new Blob([JSON.stringify({ event, directory, worktree })])
+ const child = Bun.spawn(
+ [openlitBin, "coding", "hook", "--vendor=opencode", `--event=${event.type}`],
+ {
+ stdin: payload,
+ stdout: "ignore",
+ stderr: "ignore",
+ timeout: 5_000,
+ windowsHide: true,
+ },
+ )
+ await child.exited
+ } catch {
+ // Telemetry must never interrupt the user's OpenCode session.
+ }
+}
+
+function emissionPriority(eventType: string) {
+ if (eventType === "tool.execute.before") return 0
+ return 1
+}
+
+function createEmitter(directory: string, worktree: string) {
+ const queue: PendingEmission[] = []
+ let draining = false
+ let scheduled = false
+
+ const scheduleDrain = () => {
+ if (draining || scheduled) return
+ scheduled = true
+ queueMicrotask(() => {
+ scheduled = false
+ void drain()
+ })
+ }
+
+ const drain = async () => {
+ if (draining) return
+ draining = true
+ try {
+ while (queue.length > 0) {
+ const next = queue.shift()
+ if (!next) continue
+ try {
+ await emit(next.event, directory, worktree)
+ } catch {
+ // One failed delivery must not poison the remaining queue.
+ }
+ }
+ } finally {
+ draining = false
+ if (queue.length > 0) scheduleDrain()
+ }
+ }
+
+ return (event: OpenCodeEvent) => {
+ const priority = emissionPriority(event.type)
+ if (queue.length >= maxQueuedEmissions) {
+ // Preserve FIFO among peers; only higher-value telemetry may replace
+ // the oldest lower-priority event at the hard overload boundary.
+ const dropIndex = queue.findIndex((pending) => pending.priority < priority)
+ if (dropIndex < 0) return false
+ queue.splice(dropIndex, 1)
+ }
+
+ queue.push({ event, priority })
+ scheduleDrain()
+ return true
+ }
+}
+
+function toolKey(sessionID: string, callID: string) {
+ return `${sessionID}\u0000${callID}`
+}
+
+export const OpenLitPlugin: Plugin = async ({ directory, worktree }) => {
+ const enqueue = createEmitter(directory, worktree)
+ const toolStarts = new Map<string, number>()
+
+ return {
+ event: async ({ event }) => {
+ const projected = projectEvent(event)
+ if (!projected) return
+ if (
+ projected.type === "tool.execute.error" ||
+ projected.type === "tool.execute.completed"
+ ) {
+ const properties = asRecord(projected.properties)
+ if (typeof properties?.sessionID === "string" && typeof properties.callID === "string") {
+ toolStarts.delete(toolKey(properties.sessionID, properties.callID))
+ }
+ }
+ void enqueue(projected)
+ },
+ "tool.execute.before": async (input, output) => {
+ try {
+ const startedAt = Date.now()
+ const projectedOutput = asRecord(output)
+ toolStarts.set(toolKey(input.sessionID, input.callID), startedAt)
+ void enqueue({
+ type: "tool.execute.before",
+ properties: {
+ tool: input.tool,
+ sessionID: input.sessionID,
+ callID: input.callID,
+ args: projectedOutput?.args,
+ startedAt,
+ },
+ })
+ } catch {
+ // Telemetry must never interrupt tool execution.
+ }
+ },
+ "tool.execute.after": async (input, output) => {
+ try {
+ const key = toolKey(input.sessionID, input.callID)
+ const projectedOutput = asRecord(output)
+ if (!projectedOutput) {
+ toolStarts.delete(key)
+ return
+ }
+ const endedAt = Date.now()
+ const startedAt = toolStarts.get(key) ?? endedAt
+ toolStarts.delete(key)
+ void enqueue({
+ type: "tool.execute.after",
+ properties: {
+ tool: input.tool,
+ sessionID: input.sessionID,
+ callID: input.callID,
+ args: input.args,
+ title: projectedOutput.title,
+ output: projectedOutput.output,
+ metadata: projectedOutput.metadata,
+ startedAt,
+ endedAt,
+ },
+ })
+ } catch {
+ // A malformed tool result must not interrupt the OpenCode session.
+ }
+ },
+ }
+}
diff --git a/cli/internal/coding/install/testdata/opencode_queue.test.mjs b/cli/internal/coding/install/testdata/opencode_queue.test.mjs
new file mode 100644
index 00000000..1df1e857
--- /dev/null
+++ b/cli/internal/coding/install/testdata/opencode_queue.test.mjs
@@ -0,0 +1,234 @@
+import assert from "node:assert/strict"
+import test from "node:test"
+
+globalThis.__OPENLIT_BIN_JSON__ = "openlit"
+if (typeof globalThis.Bun === "undefined") globalThis.Bun = {}
+globalThis.Bun.spawn = () => ({ exited: Promise.resolve(0) })
+
+const { OpenLitPlugin } = await import(
+ new URL("../../../../../plugins/opencode/openlit.ts", import.meta.url),
+)
+
+function deferred() {
+ let resolve
+ const promise = new Promise((onResolve) => {
+ resolve = onResolve
+ })
+ return { promise, resolve }
+}
+
+async function hooks() {
+ return OpenLitPlugin({ directory: "/workspace", worktree: "/workspace" })
+}
+
+async function payloads(calls) {
+ return Promise.all(calls.map(async (call) => JSON.parse(await call.stdin.text())))
+}
+
+test("defers subprocess work and sends one event at a time", async () => {
+ const firstExit = deferred()
+ const allStarted = deferred()
+ const fourthStarted = deferred()
+ const calls = []
+ let active = 0
+ let maxActive = 0
+
+ globalThis.Bun.spawn = (_command, options) => {
+ active++
+ maxActive = Math.max(maxActive, active)
+ calls.push(options)
+ if (calls.length === 3) allStarted.resolve()
+ if (calls.length === 4) fourthStarted.resolve()
+ const exited = calls.length === 1 ? firstExit.promise : Promise.resolve(0)
+ return {
+ exited: exited.finally(() => {
+ active--
+ }),
+ }
+ }
+
+ const plugin = await hooks()
+ void plugin.event({
+ event: {
+ type: "session.created",
+ properties: { info: { id: "session-1", time: { created: 1 } } },
+ },
+ })
+ void plugin.event({
+ event: { type: "session.idle", properties: { sessionID: "session-1" } },
+ })
+ void plugin.event({
+ event: {
+ type: "session.deleted",
+ properties: { info: { id: "session-1", time: { created: 1 } } },
+ },
+ })
+
+ assert.equal(calls.length, 0, "the hook must not spawn synchronously")
+ await Promise.resolve()
+ assert.equal(calls.length, 1)
+ assert.equal(maxActive, 1)
+
+ firstExit.resolve(0)
+ await allStarted.promise
+ assert.equal(calls.length, 3)
+ assert.equal(maxActive, 1)
+
+ await new Promise((resolve) => setImmediate(resolve))
+ void plugin.event({
+ event: { type: "session.idle", properties: { sessionID: "after-drain" } },
+ })
+ assert.equal(calls.length, 3, "a later drain must also remain deferred")
+ await fourthStarted.promise
+ assert.equal(calls.length, 4)
+ assert.equal(maxActive, 1)
+})
+
+test("bounds a flooded queue and preserves later high-priority events", async () => {
+ const firstExit = deferred()
+ const allStarted = deferred()
+ const calls = []
+
+ globalThis.Bun.spawn = (_command, options) => {
+ calls.push(options)
+ if (calls.length === 33) allStarted.resolve()
+ return { exited: calls.length === 1 ? firstExit.promise : Promise.resolve(0) }
+ }
+
+ const plugin = await hooks()
+ void plugin.event({
+ event: {
+ type: "session.created",
+ properties: { info: { id: "session-2", time: { created: 1 } } },
+ },
+ })
+ await Promise.resolve()
+ assert.equal(calls.length, 1)
+
+ const hookPromises = []
+ for (let index = 0; index < 70; index++) {
+ hookPromises.push(
+ plugin["tool.execute.before"](
+ { tool: "bash", sessionID: "session-2", callID: `call-${index}` },
+ { args: { command: `echo ${index}` } },
+ ),
+ )
+ }
+ hookPromises.push(
+ plugin["tool.execute.after"](
+ {
+ tool: "bash",
+ sessionID: "session-2",
+ callID: "call-69",
+ args: { command: "echo 69" },
+ },
+ { title: "done", output: "69", metadata: {} },
+ ),
+ )
+ hookPromises.push(
+ plugin.event({
+ event: {
+ type: "session.error",
+ properties: { sessionID: "session-2", error: { name: "ExporterUnavailable" } },
+ },
+ }),
+ )
+
+ await Promise.all(hookPromises)
+ assert.equal(calls.length, 1, "hooks must not wait for the blocked exporter")
+
+ firstExit.resolve(0)
+ await allStarted.promise
+ await new Promise((resolve) => setImmediate(resolve))
+ const bodies = await payloads(calls)
+ assert.equal(bodies.length, 33, "one in-flight event plus 32 queued events")
+ assert.deepEqual(
+ bodies.slice(1, 31).map((body) => body.event.properties.callID),
+ Array.from({ length: 30 }, (_, index) => `call-${index + 2}`),
+ )
+ assert.deepEqual(
+ bodies.slice(-2).map((body) => body.event.type),
+ ["tool.execute.after", "session.error"],
+ )
+
+ void plugin.event({
+ event: { type: "session.idle", properties: { sessionID: "after-flood" } },
+ })
+ assert.equal(calls.length, 33, "a post-flood drain must remain deferred")
+ await Promise.resolve()
+ await new Promise((resolve) => setImmediate(resolve))
+ assert.equal(calls.length, 34)
+})
+
+test("rejects a new high-priority event when the queue contains only peers", async () => {
+ const firstExit = deferred()
+ const allStarted = deferred()
+ const calls = []
+
+ globalThis.Bun.spawn = (_command, options) => {
+ calls.push(options)
+ if (calls.length === 33) allStarted.resolve()
+ return { exited: calls.length === 1 ? firstExit.promise : Promise.resolve(0) }
+ }
+
+ const plugin = await hooks()
+ void plugin.event({
+ event: {
+ type: "session.created",
+ properties: { info: { id: "in-flight", time: { created: 1 } } },
+ },
+ })
+ await Promise.resolve()
+
+ for (let index = 0; index < 32; index++) {
+ void plugin.event({
+ event: {
+ type: "session.created",
+ properties: { info: { id: `queued-${index}`, time: { created: 1 } } },
+ },
+ })
+ }
+ void plugin.event({
+ event: {
+ type: "session.error",
+ properties: { sessionID: "rejected", error: { name: "QueueFull" } },
+ },
+ })
+
+ firstExit.resolve(0)
+ await allStarted.promise
+ await new Promise((resolve) => setImmediate(resolve))
+ const bodies = await payloads(calls)
+ assert.equal(bodies.length, 33)
+ assert.equal(bodies.some((body) => body.event.type === "session.error"), false)
+})
+
+test("continues draining after a telemetry subprocess fails", async () => {
+ const secondStarted = deferred()
+ const calls = []
+
+ globalThis.Bun.spawn = (_command, options) => {
+ calls.push(options)
+ if (calls.length === 2) secondStarted.resolve()
+ return {
+ exited:
+ calls.length === 1
+ ? Promise.reject(new Error("exporter unavailable"))
+ : Promise.resolve(0),
+ }
+ }
+
+ const plugin = await hooks()
+ void plugin.event({
+ event: {
+ type: "session.created",
+ properties: { info: { id: "failed", time: { created: 1 } } },
+ },
+ })
+ void plugin.event({
+ event: { type: "session.idle", properties: { sessionID: "still-sent" } },
+ })
+
+ await secondStarted.promise
+ assert.equal(calls.length, 2)
+})
diff --git a/cli/internal/coding/launch/launch.go b/cli/internal/coding/launch/launch.go
index 60b51c25..3c477875 100644
--- a/cli/internal/coding/launch/launch.go
+++ b/cli/internal/coding/launch/launch.go
@@ -28,6 +28,7 @@ Example:
openlit coding launch claude
openlit coding launch cursor -- --debug
openlit coding launch codex
+ openlit coding launch opencode
The agent's binary must be on PATH. The plugin manifest is installed
idempotently β€” running 'launch' twice is a no-op the second time.`,
@@ -88,8 +89,10 @@ func agentBinary(agent string) (string, error) {
return "cursor", nil
case "codex":
return "codex", nil
+ case "opencode":
+ return "opencode", nil
default:
- return "", fmt.Errorf("unknown agent %q (allowed: claude, cursor, codex)", agent)
+ return "", fmt.Errorf("unknown agent %q (allowed: claude, cursor, codex, opencode)", agent)
}
}
diff --git a/cli/internal/coding/launch/launch_test.go b/cli/internal/coding/launch/launch_test.go
new file mode 100644
index 00000000..05e4dc0a
--- /dev/null
+++ b/cli/internal/coding/launch/launch_test.go
@@ -0,0 +1,18 @@
+package launch
+
+import "testing"
+
+func TestOpenCodeAgentMapping(t *testing.T) {
+ t.Parallel()
+
+ bin, err := agentBinary("opencode")
+ if err != nil {
+ t.Fatalf("agentBinary(opencode): %v", err)
+ }
+ if bin != "opencode" {
+ t.Fatalf("agentBinary(opencode) = %q, want opencode", bin)
+ }
+ if vendor := vendorOf("opencode"); vendor != "opencode" {
+ t.Fatalf("vendorOf(opencode) = %q, want opencode", vendor)
+ }
+}
diff --git a/cli/internal/coding/normalize/normalize.go b/cli/internal/coding/normalize/normalize.go
index 65208c6e..354b2f69 100644
--- a/cli/internal/coding/normalize/normalize.go
+++ b/cli/internal/coding/normalize/normalize.go
@@ -284,10 +284,11 @@ type LLMTurn struct {
// captured regardless of ContentCapture.
AttachmentPaths []string
- InputTokens int64
- OutputTokens int64
- TotalTokens int64
- CostUSD float64
+ InputTokens int64
+ OutputTokens int64
+ ReasoningTokens 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
diff --git a/cli/internal/coding/opencodeconfig/path.go b/cli/internal/coding/opencodeconfig/path.go
new file mode 100644
index 00000000..bfe41847
--- /dev/null
+++ b/cli/internal/coding/opencodeconfig/path.go
@@ -0,0 +1,33 @@
+// Package opencodeconfig resolves OpenCode's global plugin location.
+package opencodeconfig
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// PluginPath resolves the user-scoped OpenLit plugin path. OpenCode follows
+// XDG_CONFIG_HOME when it is set and otherwise uses ~/.config.
+func PluginPath() (string, error) {
+ xdgConfigHome := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME"))
+ if xdgConfigHome != "" {
+ return PluginPathAt("", xdgConfigHome), nil
+ }
+
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("could not resolve home directory: %w", err)
+ }
+ return PluginPathAt(home, ""), nil
+}
+
+// PluginPathAt is the deterministic form used by installers and tests.
+func PluginPathAt(home, xdgConfigHome string) string {
+ root := strings.TrimSpace(xdgConfigHome)
+ if root == "" {
+ root = filepath.Join(home, ".config")
+ }
+ return filepath.Join(root, "opencode", "plugins", "openlit.ts")
+}
diff --git a/cli/internal/coding/opencodeconfig/path_test.go b/cli/internal/coding/opencodeconfig/path_test.go
new file mode 100644
index 00000000..3daed8b6
--- /dev/null
+++ b/cli/internal/coding/opencodeconfig/path_test.go
@@ -0,0 +1,40 @@
+package opencodeconfig
+
+import (
+ "path/filepath"
+ "testing"
+)
+
+func TestPluginPathUsesTrimmedXDGWithoutHomeDirectory(t *testing.T) {
+ xdgConfigHome := filepath.Join(t.TempDir(), "xdg")
+ t.Setenv("XDG_CONFIG_HOME", " "+xdgConfigHome+" ")
+ t.Setenv("HOME", "")
+ t.Setenv("USERPROFILE", "")
+
+ got, err := PluginPath()
+ if err != nil {
+ t.Fatalf("PluginPath() with XDG_CONFIG_HOME set: %v", err)
+ }
+
+ want := filepath.Join(xdgConfigHome, "opencode", "plugins", "openlit.ts")
+ if got != want {
+ t.Fatalf("PluginPath() = %q, want %q", got, want)
+ }
+}
+
+func TestPluginPathAtTrimsXDGConfigHome(t *testing.T) {
+ got := PluginPathAt("unused-home", " /custom/config ")
+ want := filepath.Join("/custom/config", "opencode", "plugins", "openlit.ts")
+ if got != want {
+ t.Fatalf("PluginPathAt() = %q, want %q", got, want)
+ }
+}
+
+func TestPluginPathAtWhitespaceXDGFallsBackToUserHome(t *testing.T) {
+ home := `C:\Users\openlit`
+ got := PluginPathAt(home, " \t ")
+ want := filepath.Join(home, ".config", "opencode", "plugins", "openlit.ts")
+ if got != want {
+ t.Fatalf("PluginPathAt() = %q, want %q", got, want)
+ }
+}
diff --git a/cli/internal/coding/sessionstate/sessionstate.go b/cli/internal/coding/sessionstate/sessionstate.go
index b55652b0..8df36ca6 100644
--- a/cli/internal/coding/sessionstate/sessionstate.go
+++ b/cli/internal/coding/sessionstate/sessionstate.go
@@ -104,8 +104,23 @@ type State struct {
SubagentCount int `json:"subagent_count,omitempty"`
InputTokens int64 `json:"input_tokens,omitempty"`
OutputTokens int64 `json:"output_tokens,omitempty"`
+ TotalTokens int64 `json:"total_tokens,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
+ // OpenCode has no terminal SessionEnd signal. In minimal capture mode
+ // its idle hook emits non-terminal snapshot deltas instead of inventing
+ // a completed session root. These watermarks cover usage already emitted
+ // either on a per-turn span or on a prior snapshot, so capture-mode changes
+ // cannot double-count token and cost totals in downstream SUM queries.
+ OpenCodeSnapshotInputTokens int64 `json:"opencode_snapshot_input_tokens,omitempty"`
+ OpenCodeSnapshotOutputTokens int64 `json:"opencode_snapshot_output_tokens,omitempty"`
+ OpenCodeSnapshotTotalTokens int64 `json:"opencode_snapshot_total_tokens,omitempty"`
+ OpenCodeSnapshotCostUSD float64 `json:"opencode_snapshot_cost_usd,omitempty"`
+ // OpenCodePendingErrorType carries a safe error class to the next
+ // minimal-mode snapshot. The generic error event itself is suppressed
+ // in minimal mode, and OpenCode's following idle event is non-terminal.
+ OpenCodePendingErrorType string `json:"opencode_pending_error_type,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).
@@ -157,6 +172,11 @@ type State struct {
// content. Bounded to the most recent ~256 ids.
EmittedAssistantTurnIDs []string `json:"emitted_assistant_turn_ids,omitempty"`
+ // EmittedToolCallIDs records terminal tool calls already normalized
+ // by adapters that can receive overlapping success/error signals.
+ // It is bounded by the adapter before saving.
+ EmittedToolCallIDs []string `json:"emitted_tool_call_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,
diff --git a/cli/internal/coding/uninstall/uninstall.go b/cli/internal/coding/uninstall/uninstall.go
index 4aa454b3..6373b8ee 100644
--- a/cli/internal/coding/uninstall/uninstall.go
+++ b/cli/internal/coding/uninstall/uninstall.go
@@ -37,7 +37,9 @@ 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
+ opencode $XDG_CONFIG_HOME/opencode/plugins/openlit.ts when set;
+ otherwise <user-home>/.config/opencode/plugins/openlit.ts
+ all shorthand for all four
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
@@ -53,7 +55,7 @@ installer, or 'go install').`,
},
}
- cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor (claude-code | cursor | codex | all)")
+ cmd.Flags().StringVar(&vendor, "vendor", "", "Vendor (claude-code | cursor | codex | opencode | 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")
@@ -120,13 +122,15 @@ func run(cmd *cobra.Command, vendor string, purge, dryRun bool) error {
func vendorsFromArg(arg string) ([]string, error) {
switch arg {
case "all":
- return []string{"claude-code", "cursor", "codex"}, nil
+ return []string{"claude-code", "cursor", "codex", "opencode"}, nil
case "claude-code", "cc":
return []string{"claude-code"}, nil
case "cursor":
return []string{"cursor"}, nil
case "codex":
return []string{"codex"}, nil
+ case "opencode":
+ return []string{"opencode"}, nil
default:
return nil, fmt.Errorf("unknown --vendor %q", arg)
}
diff --git a/cli/internal/coding/uninstall/uninstall_opencode.go b/cli/internal/coding/uninstall/uninstall_opencode.go
new file mode 100644
index 00000000..b4f01835
--- /dev/null
+++ b/cli/internal/coding/uninstall/uninstall_opencode.go
@@ -0,0 +1,33 @@
+package uninstall
+
+import (
+ "github.com/openlit/openlit/cli/internal/coding/opencodeconfig"
+)
+
+func uninstallOpenCodePlugin(dryRun bool) (removed []string, errs []string) {
+ target, err := opencodeconfig.PluginPath()
+ if err != nil {
+ return nil, []string{err.Error()}
+ }
+ return uninstallOpenCodePluginAtPath(target, dryRun)
+}
+
+func uninstallOpenCodePluginAt(home string, dryRun bool) (removed []string, errs []string) {
+ return uninstallOpenCodePluginAtConfig(home, "", dryRun)
+}
+
+func uninstallOpenCodePluginAtConfig(home, xdgConfigHome string, dryRun bool) (removed []string, errs []string) {
+ target := opencodeconfig.PluginPathAt(home, xdgConfigHome)
+ return uninstallOpenCodePluginAtPath(target, dryRun)
+}
+
+func uninstallOpenCodePluginAtPath(target string, dryRun bool) (removed []string, errs []string) {
+ path, err := removePath(target, dryRun)
+ if path != "" {
+ removed = append(removed, path)
+ }
+ if err != nil {
+ errs = append(errs, err.Error())
+ }
+ return removed, errs
+}
diff --git a/cli/internal/coding/uninstall/uninstall_opencode_test.go b/cli/internal/coding/uninstall/uninstall_opencode_test.go
new file mode 100644
index 00000000..7e03d90f
--- /dev/null
+++ b/cli/internal/coding/uninstall/uninstall_opencode_test.go
@@ -0,0 +1,75 @@
+package uninstall
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestUninstallOpenCodePluginAtRemovesOnlyOpenLitFile(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ plugins := filepath.Join(home, ".config", "opencode", "plugins")
+ target := filepath.Join(plugins, "openlit.ts")
+ other := filepath.Join(plugins, "keep.ts")
+ if err := os.MkdirAll(plugins, 0o755); err != nil {
+ t.Fatalf("mkdir plugins: %v", err)
+ }
+ if err := os.WriteFile(target, []byte("openlit"), 0o644); err != nil {
+ t.Fatalf("write openlit plugin: %v", err)
+ }
+ if err := os.WriteFile(other, []byte("user plugin"), 0o644); err != nil {
+ t.Fatalf("write unrelated plugin: %v", err)
+ }
+
+ removed, errs := uninstallOpenCodePluginAt(home, true)
+ if len(errs) != 0 {
+ t.Fatalf("dry-run errors: %v", errs)
+ }
+ if len(removed) != 1 || removed[0] != target {
+ t.Fatalf("dry-run paths = %v, want [%s]", removed, target)
+ }
+ if _, err := os.Stat(target); err != nil {
+ t.Fatalf("dry-run removed target: %v", err)
+ }
+
+ removed, errs = uninstallOpenCodePluginAt(home, false)
+ if len(errs) != 0 {
+ t.Fatalf("uninstall errors: %v", errs)
+ }
+ if len(removed) != 1 || removed[0] != target {
+ t.Fatalf("removed paths = %v, want [%s]", removed, target)
+ }
+ if _, err := os.Stat(target); !os.IsNotExist(err) {
+ t.Fatalf("OpenLit plugin still exists: %v", err)
+ }
+ if got, err := os.ReadFile(other); err != nil || string(got) != "user plugin" {
+ t.Fatalf("unrelated plugin changed: content=%q err=%v", got, err)
+ }
+}
+
+func TestUninstallOpenCodePluginHonorsXDGConfigHome(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ xdgConfigHome := filepath.Join(t.TempDir(), "custom-config")
+ target := filepath.Join(xdgConfigHome, "opencode", "plugins", "openlit.ts")
+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+ t.Fatalf("mkdir plugin dir: %v", err)
+ }
+ if err := os.WriteFile(target, []byte("openlit"), 0o644); err != nil {
+ t.Fatalf("write plugin: %v", err)
+ }
+
+ removed, errs := uninstallOpenCodePluginAtConfig(home, xdgConfigHome, false)
+ if len(errs) != 0 {
+ t.Fatalf("uninstall errors: %v", errs)
+ }
+ if len(removed) != 1 || removed[0] != target {
+ t.Fatalf("removed paths = %v, want [%s]", removed, target)
+ }
+ if _, err := os.Stat(target); !os.IsNotExist(err) {
+ t.Fatalf("XDG OpenCode plugin still exists: %v", err)
+ }
+}
diff --git a/cli/internal/coding/uninstall/uninstall_test.go b/cli/internal/coding/uninstall/uninstall_test.go
index 0aabb9aa..d6be49e4 100644
--- a/cli/internal/coding/uninstall/uninstall_test.go
+++ b/cli/internal/coding/uninstall/uninstall_test.go
@@ -80,11 +80,12 @@ func TestVendorsFromArg(t *testing.T) {
in string
want []string
}{
- {"all", []string{"claude-code", "cursor", "codex"}},
+ {"all", []string{"claude-code", "cursor", "codex", "opencode"}},
{"cc", []string{"claude-code"}},
{"claude-code", []string{"claude-code"}},
{"cursor", []string{"cursor"}},
{"codex", []string{"codex"}},
+ {"opencode", []string{"opencode"}},
}
for _, tc := range cases {
got, err := vendorsFromArg(tc.in)
diff --git a/cli/internal/coding/uninstall/uninstall_vendors.go b/cli/internal/coding/uninstall/uninstall_vendors.go
index 456d7143..ede22764 100644
--- a/cli/internal/coding/uninstall/uninstall_vendors.go
+++ b/cli/internal/coding/uninstall/uninstall_vendors.go
@@ -31,6 +31,9 @@ func uninstallVendor(vendor string, dryRun bool) (removed []string, errs []strin
if vendor == "cursor" {
return uninstallCursorHooks(dryRun)
}
+ if vendor == "opencode" {
+ return uninstallOpenCodePlugin(dryRun)
+ }
dest, err := vendorDestRoot(vendor)
if err != nil {
diff --git a/cli/internal/doctor/doctor.go b/cli/internal/doctor/doctor.go
index 3c989c49..58fc5be0 100644
--- a/cli/internal/doctor/doctor.go
+++ b/cli/internal/doctor/doctor.go
@@ -29,6 +29,7 @@ import (
"strings"
"time"
+ "github.com/openlit/openlit/cli/internal/coding/opencodeconfig"
"github.com/openlit/openlit/cli/internal/config"
"github.com/openlit/openlit/cli/internal/version"
"github.com/spf13/cobra"
@@ -104,7 +105,7 @@ func run(cmd *cobra.Command, _ []string) error {
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).")
+ fmt.Fprintln(out, " Run `openlit coding install --vendor=cursor` (or claude-code / codex / opencode).")
warnings++
}
for _, p := range plugins {
@@ -185,11 +186,21 @@ type installedPlugin struct {
// - codex: ~/.local/share/openlit/codex-marketplace/, the local
// marketplace tree that `openlit coding install --vendor=codex`
// materializes and registers with codex.
+// - opencode: ~/.config/opencode/plugins/openlit.ts containing the
+// OpenLit hook marker.
func detectInstalledPlugins() []installedPlugin {
home, err := os.UserHomeDir()
if err != nil || home == "" {
return nil
}
+ return detectInstalledPluginsAtConfig(home, os.Getenv("XDG_CONFIG_HOME"))
+}
+
+func detectInstalledPluginsAt(home string) []installedPlugin {
+ return detectInstalledPluginsAtConfig(home, "")
+}
+
+func detectInstalledPluginsAtConfig(home, xdgConfigHome string) []installedPlugin {
candidates := []struct {
vendor string
path string
@@ -215,6 +226,16 @@ func detectInstalledPlugins() []installedPlugin {
vendor: "codex",
path: filepath.Join(home, ".local", "share", "openlit", "codex-marketplace"),
},
+ {
+ vendor: "opencode",
+ path: opencodeconfig.PluginPathAt(home, xdgConfigHome),
+ verify: func(b []byte) bool {
+ body := string(b)
+ return strings.Contains(body, "coding") &&
+ strings.Contains(body, "hook") &&
+ strings.Contains(body, "--vendor=opencode")
+ },
+ },
}
var out []installedPlugin
for _, c := range candidates {
diff --git a/cli/internal/doctor/doctor_opencode_test.go b/cli/internal/doctor/doctor_opencode_test.go
new file mode 100644
index 00000000..20db01db
--- /dev/null
+++ b/cli/internal/doctor/doctor_opencode_test.go
@@ -0,0 +1,60 @@
+package doctor
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestDetectInstalledPluginsAtRecognizesOnlyOpenLitOpenCodePlugin(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ target := filepath.Join(home, ".config", "opencode", "plugins", "openlit.ts")
+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+ t.Fatalf("mkdir plugin dir: %v", err)
+ }
+ if err := os.WriteFile(target, []byte("export const Unrelated = {}\n"), 0o644); err != nil {
+ t.Fatalf("write unrelated plugin: %v", err)
+ }
+ if got := detectInstalledPluginsAt(home); hasInstalledVendor(got, "opencode") {
+ t.Fatalf("unrelated openlit.ts was detected as the OpenLit plugin: %v", got)
+ }
+
+ body := []byte("Bun.spawn([openlitBin, \"coding\", \"hook\", \"--vendor=opencode\"])\n")
+ if err := os.WriteFile(target, body, 0o644); err != nil {
+ t.Fatalf("write OpenLit plugin: %v", err)
+ }
+ if got := detectInstalledPluginsAt(home); !hasInstalledVendor(got, "opencode") {
+ t.Fatalf("OpenCode plugin not detected: %v", got)
+ }
+}
+
+func TestDetectInstalledPluginsHonorsXDGConfigHome(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ xdgConfigHome := filepath.Join(t.TempDir(), "custom-config")
+ target := filepath.Join(xdgConfigHome, "opencode", "plugins", "openlit.ts")
+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+ t.Fatalf("mkdir plugin dir: %v", err)
+ }
+ body := []byte("Bun.spawn([openlitBin, \"coding\", \"hook\", \"--vendor=opencode\"])\n")
+ if err := os.WriteFile(target, body, 0o644); err != nil {
+ t.Fatalf("write OpenLit plugin: %v", err)
+ }
+
+ got := detectInstalledPluginsAtConfig(home, xdgConfigHome)
+ if !hasInstalledVendor(got, "opencode") {
+ t.Fatalf("XDG OpenCode plugin not detected: %v", got)
+ }
+}
+
+func hasInstalledVendor(plugins []installedPlugin, vendor string) bool {
+ for _, plugin := range plugins {
+ if plugin.vendor == vendor {
+ return true
+ }
+ }
+ return false
+}
diff --git a/cli/internal/otlp/attrs.go b/cli/internal/otlp/attrs.go
index aee81e52..1973bcf0 100644
--- a/cli/internal/otlp/attrs.go
+++ b/cli/internal/otlp/attrs.go
@@ -266,13 +266,14 @@ func setToolCallAttrs(span trace.Span, t normalize.ToolCall, scrub scrubFn, capt
setStr(span, semconv.CodingAgentMCPSource, t.MCPSource, scrub)
setStr(span, semconv.CodingAgentClient, t.Vendor, scrub)
+ // Required on every canonical tool span, including successful calls.
+ span.SetAttributes(attribute.Bool("coding_agent.tool.errored", t.Errored))
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 {
@@ -299,9 +300,13 @@ func setToolCallAttrs(span trace.Span, t normalize.ToolCall, scrub scrubFn, capt
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()))
+ dur := t.EndedAt.Sub(t.StartedAt)
+ if dur < 0 {
+ dur = 0
}
+ // Duration is required even when the host's millisecond clock rounds
+ // a very fast call down to zero.
+ span.SetAttributes(attribute.Int64("coding_agent.tool.duration_ms", dur.Milliseconds()))
}
func nonEmpty(s, fallback string) string {
@@ -356,10 +361,15 @@ func setLLMTurnAttrs(span trace.Span, t normalize.LLMTurn, scrub scrubFn, captur
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)
+ switch {
+ case t.AssistantMessageOnly:
+ setStr(span, semconv.CodingAgentLLMTurnKind, semconv.CodingAgentLLMTurnKindResponse, scrub)
+ case t.Prompt != "":
+ setStr(span, semconv.CodingAgentLLMTurnKind, semconv.CodingAgentLLMTurnKindPrompt, scrub)
+ case t.ThoughtText != "":
+ setStr(span, semconv.CodingAgentLLMTurnKind, semconv.CodingAgentLLMTurnKindThought, scrub)
+ case t.Response != "":
+ setStr(span, semconv.CodingAgentLLMTurnKind, semconv.CodingAgentLLMTurnKindResponse, scrub)
}
if t.InputTokens > 0 {
@@ -368,6 +378,9 @@ func setLLMTurnAttrs(span trace.Span, t normalize.LLMTurn, scrub scrubFn, captur
if t.OutputTokens > 0 {
span.SetAttributes(attribute.Int64(semconv.GenAIUsageOutputTokens, t.OutputTokens))
}
+ if t.ReasoningTokens > 0 {
+ span.SetAttributes(attribute.Int64(semconv.GenAIUsageReasoningTokens, t.ReasoningTokens))
+ }
if t.TotalTokens > 0 {
span.SetAttributes(attribute.Int64(semconv.GenAIUsageTotalTokens, t.TotalTokens))
}
diff --git a/cli/internal/otlp/attrs_test.go b/cli/internal/otlp/attrs_test.go
index c8851d85..c8e06d7a 100644
--- a/cli/internal/otlp/attrs_test.go
+++ b/cli/internal/otlp/attrs_test.go
@@ -1,6 +1,13 @@
package otlp
-import "testing"
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/openlit/openlit/cli/internal/coding/normalize"
+ "github.com/openlit/openlit/sdk/go/semconv"
+)
func TestInferProvider(t *testing.T) {
tests := []struct {
@@ -29,3 +36,133 @@ func TestInferProvider(t *testing.T) {
}
}
}
+
+func TestToolCallAttrsAlwaysIncludeRequiredDurationAndErrored(t *testing.T) {
+ tracer, exporter, shutdown := newTestTracer(t)
+ defer shutdown()
+
+ _, span := tracer.Start(context.Background(), "tool")
+ now := time.Now()
+ setToolCallAttrs(span, normalize.ToolCall{
+ SessionID: "ses_required",
+ ToolName: "bash",
+ ToolUseID: "call_required",
+ Vendor: "opencode",
+ StartedAt: now,
+ EndedAt: now,
+ }, func(value string) string { return value }, "metadata_only")
+ span.End()
+
+ spans := exporter.GetSpans()
+ if len(spans) != 1 {
+ t.Fatalf("got %d spans, want 1", len(spans))
+ }
+ attrs := map[string]any{}
+ for _, attr := range spans[0].Attributes {
+ attrs[string(attr.Key)] = attr.Value.AsInterface()
+ }
+ if got, ok := attrs["coding_agent.tool.duration_ms"]; !ok || got != int64(0) {
+ t.Errorf("duration_ms = %v (present=%v), want int64(0)", got, ok)
+ }
+ if got, ok := attrs["coding_agent.tool.errored"]; !ok || got != false {
+ t.Errorf("errored = %v (present=%v), want false", got, ok)
+ }
+}
+
+func TestMinimalModeAllowsOnlySessionSnapshotEvents(t *testing.T) {
+ if !eventSpanAllowed("minimal", semconv.CodingAgentEventSessionSnapshot) {
+ t.Fatal("minimal mode suppressed the OpenCode session snapshot")
+ }
+ if eventSpanAllowed("minimal", "coding_agent.session.loop.stop") {
+ t.Fatal("minimal mode allowed an ordinary per-event span")
+ }
+ if !eventSpanAllowed("metadata_only", "coding_agent.session.loop.stop") {
+ t.Fatal("metadata mode suppressed an ordinary event span")
+ }
+ if eventSpanAllowed("minimal", "coding_agent.session.snapshot.unreviewed") {
+ t.Fatal("minimal mode allowed an unregistered snapshot-prefixed event")
+ }
+}
+
+func TestLLMTurnUsesNumericCanonicalReasoningTokens(t *testing.T) {
+ tracer, exporter, shutdown := newTestTracer(t)
+ defer shutdown()
+
+ _, span := tracer.Start(context.Background(), "llm")
+ setLLMTurnAttrs(span, normalize.LLMTurn{
+ SessionID: "ses_reasoning",
+ Vendor: "opencode",
+ ReasoningTokens: 7,
+ }, func(value string) string { return value }, "metadata_only")
+ span.End()
+
+ spans := exporter.GetSpans()
+ if len(spans) != 1 {
+ t.Fatalf("got %d spans, want 1", len(spans))
+ }
+ attrs := map[string]any{}
+ for _, attr := range spans[0].Attributes {
+ attrs[string(attr.Key)] = attr.Value.AsInterface()
+ }
+ if got, ok := attrs[semconv.GenAIUsageReasoningTokens]; !ok || got != int64(7) {
+ t.Errorf("reasoning tokens = %v (present=%v), want int64(7)", got, ok)
+ }
+ if _, ok := attrs["coding_agent.llm.reasoning.tokens"]; ok {
+ t.Error("emitted ad-hoc string reasoning token attribute")
+ }
+}
+
+func TestLLMTurnUsesCanonicalKindValues(t *testing.T) {
+ tests := []struct {
+ name string
+ turn normalize.LLMTurn
+ want string
+ }{
+ {
+ name: "prompt",
+ turn: normalize.LLMTurn{Prompt: "hello"},
+ want: semconv.CodingAgentLLMTurnKindPrompt,
+ },
+ {
+ name: "assistant response",
+ turn: normalize.LLMTurn{AssistantMessageOnly: true},
+ want: semconv.CodingAgentLLMTurnKindResponse,
+ },
+ {
+ name: "response body",
+ turn: normalize.LLMTurn{Response: "hello"},
+ want: semconv.CodingAgentLLMTurnKindResponse,
+ },
+ {
+ name: "thought",
+ turn: normalize.LLMTurn{ThoughtText: "considering"},
+ want: semconv.CodingAgentLLMTurnKindThought,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ tracer, exporter, shutdown := newTestTracer(t)
+ defer shutdown()
+
+ _, span := tracer.Start(context.Background(), "llm")
+ turn := tt.turn
+ turn.SessionID = "ses_kind"
+ turn.Vendor = semconv.CodingAgentVendorOpenCode
+ setLLMTurnAttrs(span, turn, func(value string) string { return value }, "metadata_only")
+ span.End()
+
+ spans := exporter.GetSpans()
+ if len(spans) != 1 {
+ t.Fatalf("got %d spans, want 1", len(spans))
+ }
+ attrs := map[string]any{}
+ for _, attr := range spans[0].Attributes {
+ attrs[string(attr.Key)] = attr.Value.AsInterface()
+ }
+ if got := attrs[semconv.CodingAgentLLMTurnKind]; got != tt.want {
+ t.Errorf("turn kind = %v, want %q", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/cli/internal/otlp/exporter.go b/cli/internal/otlp/exporter.go
index 90580217..0d920ebc 100644
--- a/cli/internal/otlp/exporter.go
+++ b/cli/internal/otlp/exporter.go
@@ -71,6 +71,9 @@ func drainCounters(s normalize.Session, vendor string) normalize.Session {
if s.OutputTokens == 0 && st.OutputTokens > 0 {
s.OutputTokens = st.OutputTokens
}
+ if s.TotalTokens == 0 && st.TotalTokens > 0 {
+ s.TotalTokens = st.TotalTokens
+ }
if s.CostUSD == 0 && st.CostUSD > 0 {
s.CostUSD = st.CostUSD
}
@@ -557,7 +560,7 @@ func (e *Emitter) bumpToolCounter(sessionID string) {
sessionstate.Save(sessionID, e.vendor, st)
}
-func (e *Emitter) bumpLLMCounter(sessionID string, in, out int64, cost float64) {
+func (e *Emitter) bumpLLMCounter(sessionID string, in, out, total int64, cost float64) {
if sessionID == "" {
return
}
@@ -571,6 +574,9 @@ func (e *Emitter) bumpLLMCounter(sessionID string, in, out int64, cost float64)
if out > 0 {
st.OutputTokens += out
}
+ if total > 0 {
+ st.TotalTokens += total
+ }
if cost > 0 {
st.CostUSD += cost
}
@@ -755,7 +761,7 @@ func (e *Emitter) EmitLLMTurn(t normalize.LLMTurn) error {
return errors.New("nil emitter")
}
if !perEventSpansAllowed(e.cfg.CodingContentCapture) {
- e.bumpLLMCounter(t.SessionID, t.InputTokens, t.OutputTokens, t.CostUSD)
+ e.bumpLLMCounter(t.SessionID, t.InputTokens, t.OutputTokens, t.TotalTokens, t.CostUSD)
return nil
}
startedAt := t.StartedAt
@@ -833,11 +839,17 @@ func (e *Emitter) EmitSubagent(s normalize.Subagent) error {
// 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 eventSpanAllowed(capture, name string) bool {
+ return perEventSpansAllowed(capture) ||
+ name == semconv.CodingAgentEventSessionSnapshotStart ||
+ name == semconv.CodingAgentEventSessionSnapshot
+}
+
func (e *Emitter) EmitEvent(ev normalize.EventEmission) error {
if e == nil || e.tracer == nil {
return errors.New("nil emitter")
}
- if !perEventSpansAllowed(e.cfg.CodingContentCapture) {
+ if !eventSpanAllowed(e.cfg.CodingContentCapture, ev.Name) {
return nil
}
at := ev.At
diff --git a/cli/internal/otlp/tracecontext.go b/cli/internal/otlp/tracecontext.go
index 3c7c7fe5..34335f47 100644
--- a/cli/internal/otlp/tracecontext.go
+++ b/cli/internal/otlp/tracecontext.go
@@ -6,7 +6,7 @@
//
// Why we need it
// --------------
-// Each Cursor / Claude Code / Codex hook fires its own
+// Each Cursor / Claude Code / Codex / OpenCode 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
diff --git a/cli/scripts/sync-plugins.sh b/cli/scripts/sync-plugins.sh
index 6f725cf7..e9703e86 100755
--- a/cli/scripts/sync-plugins.sh
+++ b/cli/scripts/sync-plugins.sh
@@ -14,6 +14,7 @@
# plugins/claude-code/ -- mirrored from repo-root
# plugins/cursor/ -- mirrored from repo-root
# plugins/codex/ -- mirrored from repo-root
+# plugins/opencode/ -- mirrored from repo-root
#
# Run after editing any file under either source tree. CI verifies the
# embedded copy is in sync (see .github/workflows/ci-cli.yml).
diff --git a/docs/latest/cli/commands.mdx b/docs/latest/cli/commands.mdx
index 59171148..e8c72e43 100644
--- a/docs/latest/cli/commands.mdx
+++ b/docs/latest/cli/commands.mdx
@@ -8,7 +8,7 @@ The root command is `openlit`. Run `openlit --help` or `openlit <command> --help
```
openlit
-β”œβ”€β”€ coding Coding-agent observability (Claude Code, Cursor, Codex)
+β”œβ”€β”€ coding Coding-agent observability (Claude Code, Cursor, Codex, OpenCode)
β”‚ β”œβ”€β”€ install Install per-vendor host plugin manifests
β”‚ β”œβ”€β”€ launch Bootstrap the plugin for an agent and exec it
β”‚ β”œβ”€β”€ uninstall Remove per-vendor host plugin manifests
@@ -20,7 +20,7 @@ openlit
## openlit coding
-Coding-agent observability for Claude Code, Cursor, and Codex. See the [Coding Agents setup guide](/latest/openlit/coding-agents/setup-and-configure) for the full vendor-by-vendor walkthrough.
+Coding-agent observability for Claude Code, Cursor, Codex, and OpenCode. See the [Coding Agents setup guide](/latest/openlit/coding-agents/setup-and-configure) for the full vendor-by-vendor walkthrough.
### openlit coding install
@@ -33,7 +33,7 @@ openlit coding install --vendor=all --dry-run # preview without writing
| Flag | Description |
|---|---|
-| `--vendor` *(required)* | `claude-code` \| `cursor` \| `codex` \| `all` |
+| `--vendor` *(required)* | `claude-code` \| `cursor` \| `codex` \| `opencode` \| `all` |
| `--dry-run` | Print what would be written without modifying any files |
**Where manifests are written:**
@@ -43,6 +43,7 @@ openlit coding install --vendor=all --dry-run # preview without writing
| Claude Code | `~/.claude/plugins/openlit-cc/` |
| Cursor | `~/.cursor/hooks.json` (user scope, merged) |
| Codex | `~/.codex/plugins/openlit/` |
+| OpenCode | `$XDG_CONFIG_HOME/opencode/plugins/openlit.ts` when set; otherwise `<user-home>/.config/opencode/plugins/openlit.ts` |
### openlit coding launch
@@ -52,11 +53,12 @@ Bootstrap the plugin for an agent and exec it - telemetry on from the first turn
openlit coding launch claude
openlit coding launch cursor -- <agent-args...> # pass args through after --
openlit coding launch codex
+openlit coding launch opencode
```
| Argument | Description |
|---|---|
-| `<agent>` *(required)* | `claude` \| `claude-code` \| `cc` \| `cursor` \| `codex` (`claude-code` and `cc` are aliases for `claude`) |
+| `<agent>` *(required)* | `claude` \| `claude-code` \| `cc` \| `cursor` \| `codex` \| `opencode` (`claude-code` and `cc` are aliases for `claude`) |
Any arguments after `--` are forwarded to the agent's own CLI.
@@ -73,7 +75,7 @@ openlit coding uninstall --vendor=cursor --dry-run # preview without touching d
| Flag | Description |
|---|---|
-| `--vendor` *(required)* | `claude-code` \| `cursor` \| `codex` \| `all` |
+| `--vendor` *(required)* | `claude-code` \| `cursor` \| `codex` \| `opencode` \| `all` |
| `--purge` | Also remove `~/.config/openlit` and the session-state cache |
| `--dry-run` | Print what would be removed without modifying any files |
@@ -89,7 +91,7 @@ openlit coding hook --vendor=claude-code --event=SessionStart < payload.json
| Flag | Description |
|---|---|
-| `--vendor` *(required)* | `cc` \| `claude-code` \| `cursor` \| `codex` |
+| `--vendor` *(required)* | `cc` \| `claude-code` \| `cursor` \| `codex` \| `opencode` |
| `--event` | Hook event name (vendor-specific; e.g. `SessionStart`, `PreToolUse`) |
The hook is crash-isolated: a 5-second hard timeout (~3s reserved for OTLP flush) and it **always exits 0** even when telemetry fails - a broken pipeline never blocks your coding session. It never writes to stdout (agents like Claude Code parse stdout for JSON). Set `OPENLIT_DEBUG_PAYLOAD_DIR` to tee raw payloads for debugging.
diff --git a/docs/latest/cli/installation.mdx b/docs/latest/cli/installation.mdx
index 49ea7722..fdf56034 100644
--- a/docs/latest/cli/installation.mdx
+++ b/docs/latest/cli/installation.mdx
@@ -99,6 +99,6 @@ iwr -useb https://raw.githubusercontent.com/openlit/openlit/main/cli/scripts/uni
Point the CLI at your OpenLIT OTLP endpoint
</Card>
<Card title="Wire your coding agents" href="/latest/openlit/coding-agents/setup-and-configure" icon="code">
- Claude Code, Cursor, and Codex in under a minute
+ Claude Code, Cursor, Codex, and OpenCode in under a minute
</Card>
</CardGroup>
diff --git a/docs/latest/cli/overview.mdx b/docs/latest/cli/overview.mdx
index 33526fd5..3e66c68e 100644
--- a/docs/latest/cli/overview.mdx
+++ b/docs/latest/cli/overview.mdx
@@ -4,7 +4,7 @@ sidebarTitle: "Overview"
description: "The command-line interface for OpenLIT - observe coding agents today, control the whole platform tomorrow"
---
-The **`openlit` CLI** is a single Go binary that connects your local tooling to an OpenLIT instance. Today it ships first-class observability for AI **coding agents** - Claude Code, Cursor, and Codex - by wiring into each vendor's hook system, normalizing events onto OpenTelemetry's `gen_ai.*` and OpenLIT's `coding_agent.*` semantic conventions, and exporting them via OTLP to OpenLIT's [OTLP receiver](/latest/openlit/otlp-receiver).
+The **`openlit` CLI** is a single Go binary that connects your local tooling to an OpenLIT instance. Today it ships first-class observability for AI **coding agents** - Claude Code, Cursor, Codex, and OpenCode - by wiring into each vendor's hook system, normalizing events onto OpenTelemetry's `gen_ai.*` and OpenLIT's `coding_agent.*` semantic conventions, and exporting them via OTLP to OpenLIT's [OTLP receiver](/latest/openlit/otlp-receiver).
It talks **only** to your OpenLIT endpoint. There is no managed cloud - your telemetry stays on your infrastructure.
@@ -16,7 +16,7 @@ The CLI is the future control plane for OpenLIT. It's built so new command group
<CardGroup cols={2}>
<Card title="Observe coding agents" icon="code">
- Wire Claude Code, Cursor, or Codex into OpenLIT with one idempotent command per vendor - no SDK, no code changes in your repos.
+ Wire Claude Code, Cursor, Codex, or OpenCode into OpenLIT with one idempotent command per vendor - no SDK, no code changes in your repos.
</Card>
<Card title="Configure once" icon="gear">
Set your OTLP endpoint, API key, environment, and content-capture mode in a single config file or via environment variables.
@@ -33,7 +33,7 @@ The CLI is the future control plane for OpenLIT. It's built so new command group
| Command | Purpose |
|---|---|
-| [`openlit coding`](/latest/cli/commands#openlit-coding) | Install, launch, and manage coding-agent telemetry (Claude Code, Cursor, Codex) |
+| [`openlit coding`](/latest/cli/commands#openlit-coding) | Install, launch, and manage coding-agent telemetry (Claude Code, Cursor, Codex, OpenCode) |
| [`openlit configure`](/latest/cli/commands#openlit-configure) | Write persistent settings to `~/.config/openlit/config.env` |
| [`openlit doctor`](/latest/cli/commands#openlit-doctor) | Diagnose config, OTLP reachability, and installed plugins |
| [`openlit version`](/latest/cli/commands#openlit-version) | Print the CLI version and build commit |
@@ -41,7 +41,7 @@ The CLI is the future control plane for OpenLIT. It's built so new command group
## How it works
```
-Coding agent (Claude Code / Cursor / Codex)
+Coding agent (Claude Code / Cursor / Codex / OpenCode)
+-- fires hook events (SessionStart, PreToolUse, Stop, ...)
|
v
diff --git a/docs/latest/openlit/coding-agents/overview.mdx b/docs/latest/openlit/coding-agents/overview.mdx
index a494c581..2861cd7d 100644
--- a/docs/latest/openlit/coding-agents/overview.mdx
+++ b/docs/latest/openlit/coding-agents/overview.mdx
@@ -1,7 +1,7 @@
---
title: "Coding Agent Observability: Claude Code, Codex, Cursor"
sidebarTitle: "Overview"
-description: 'Coding agent observability for Claude Code, Cursor, Codex, and Windsurf β€” tokens, cost, tool calls, and outcomes with no SDK.'
+description: 'Coding agent observability for Claude Code, Cursor, Codex, Windsurf, and OpenCode β€” tokens, cost, tool calls, and outcomes with no SDK.'
---
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 OpenLIT OTLP endpoint. The [Agents page](/latest/openlit/observability/agents/overview)'s Coding Agents tab detects them automatically - no controller, no SDK, no code change in your repos.
@@ -14,7 +14,7 @@ You only need an OpenLIT instance and the `openlit` CLI on each developer's mach
<CardGroup cols={2}>
<Card title="Setup & Configure" href="/latest/openlit/coding-agents/setup-and-configure" icon='download'>
- Install the CLI, wire Claude Code, Cursor, or Codex, and stop tracking when you need to
+ Install the CLI, wire Claude Code, Cursor, Codex, or OpenCode, and stop tracking when you need to
</Card>
<Card title="Analytics" href="/latest/openlit/coding-agents/analytics" icon='chart-line'>
The seeded dashboard - sessions, cost, acceptance, top tools and repos, session outcomes
diff --git a/docs/latest/openlit/coding-agents/setup-and-configure.mdx b/docs/latest/openlit/coding-agents/setup-and-configure.mdx
index 9d23dbb3..db37c0b6 100644
--- a/docs/latest/openlit/coding-agents/setup-and-configure.mdx
+++ b/docs/latest/openlit/coding-agents/setup-and-configure.mdx
@@ -102,6 +102,26 @@ description: "Install the openlit CLI, wire each vendor's hooks, then configure
Older Codex builds use `hooks = true` and `plugin_hooks = true` instead of `codex_hooks`.
+ </Tab>
+ <Tab title="OpenCode">
+
+ ```bash
+ openlit coding install --vendor=opencode
+
+ # Or install and launch OpenCode in one step
+ openlit coding launch opencode
+ ```
+
+ Plugin path: `$XDG_CONFIG_HOME/opencode/plugins/openlit.ts` when `XDG_CONFIG_HOME` is set, otherwise `<user-home>/.config/opencode/plugins/openlit.ts`. OpenCode [automatically loads global JavaScript and TypeScript plugins](https://opencode.ai/docs/plugins/#from-local-files) from this directory at startup, so restart OpenCode after installation.
+
+ The plugin projects session lifecycle, completed-assistant metadata, and tool execution into `openlit coding hook --vendor=opencode`. OpenLIT emits canonical LLM-turn and tool-call spans with `coding_agent.client=opencode`. Provider-executed tools, which bypass OpenCode's explicit tool hooks, are recovered from terminal tool-part metadata and deduplicated by call ID.
+
+ OpenCode does not expose a terminal `SessionEnd` hook: `session.idle` is a turn boundary and can also follow errors or cancellation. OpenLIT therefore does not fabricate a completed session root. In `metadata_only` and `full`, it records lifecycle events as they arrive. In `minimal`, it emits non-terminal `coding_agent.session.snapshot.start` / `coding_agent.session.snapshot` spans; token and cost values are per-snapshot deltas, while duration and tool count are cumulative. None of these snapshots carries `coding_agent.session.outcome`.
+
+ OpenCode message text, reasoning text, system messages, and structured parts are never forwarded. Explicit tool arguments and results are included only when `OPENLIT_CODING_CONTENT_CAPTURE=full`; provider-executed fallback events contain terminal metadata only.
+
+ Re-running the install is idempotent and replaces only `openlit.ts`; other files in your global OpenCode plugin directory are preserved.
+
</Tab>
</Tabs>
</Step>
@@ -155,6 +175,7 @@ What each flag removes:
| `~/.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`) | - |
+| `$XDG_CONFIG_HOME/opencode/plugins/openlit.ts` when set; otherwise `<user-home>/.config/opencode/plugins/openlit.ts` | βœ“ (when `<v>` is `opencode` 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) | - | βœ“ |
diff --git a/docs/latest/openlit/coding-agents/troubleshooting.mdx b/docs/latest/openlit/coding-agents/troubleshooting.mdx
index 638b41b8..a3d1146a 100644
--- a/docs/latest/openlit/coding-agents/troubleshooting.mdx
+++ b/docs/latest/openlit/coding-agents/troubleshooting.mdx
@@ -9,7 +9,7 @@ It prints the resolved config, the cached session count, the installed plugin pa
## No row on the Agents page
-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.
+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/`). For OpenCode, first run `openlit doctor` and confirm it detects `$XDG_CONFIG_HOME/opencode/plugins/openlit.ts` when `XDG_CONFIG_HOME` is set, or `<user-home>/.config/opencode/plugins/openlit.ts` otherwise. 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 landed
diff --git a/docs/latest/overview.mdx b/docs/latest/overview.mdx
index 97f52a70..c186ed48 100644
--- a/docs/latest/overview.mdx
+++ b/docs/latest/overview.mdx
@@ -66,14 +66,14 @@ See the [Concepts glossary](/latest/concepts/glossary) for short definitions of
controls
className="w-full aspect-video rounded-xl"
src="/images/coding-agents-overview.mp4"
- alt="Demo of coding agent observability for Claude Code, Cursor, and Codex"
+ alt="Demo of coding agent observability for Claude Code, Cursor, Codex, and OpenCode"
>
</video>
- Coding agent observability for Claude Code, Cursor, and Codex. Understand token consumption, AI spend, and developer productivity across your entire engineering team:
+ Coding agent observability for Claude Code, Cursor, Codex, and OpenCode. Understand token consumption, AI spend, and developer productivity across your entire engineering team:
- [One-command setup](/latest/openlit/coding-agents/setup-and-configure) - Install the `openlit` CLI and wire any vendor in under a minute. No SDK, no code changes in your repos.
- **Session monitoring** - Track cost per session, token usage, lines added and removed, model acceptance rate, commits, and PRs per user and per team.
- - **AI spend visibility** - See exactly how much each developer, team, and project spends on AI coding tools. Break down cost by model and vendor across Claude Code, Cursor, and Codex in one place.
+ - **AI spend visibility** - See exactly how much each developer, team, and project spends on AI coding tools. Break down cost by model and vendor across Claude Code, Cursor, Codex, and OpenCode in one place.
- **Privacy controls** - Automatic secret redaction, usage breakdowns by repo, and cohort-floor anonymization so individual data stays protected.
</Tab>
diff --git a/plugins/opencode/openlit.ts b/plugins/opencode/openlit.ts
new file mode 100644
index 00000000..eb58ac37
--- /dev/null
+++ b/plugins/opencode/openlit.ts
@@ -0,0 +1,273 @@
+import type { Plugin } from "@opencode-ai/plugin"
+
+const openlitBin = __OPENLIT_BIN_JSON__
+// One additional event may be in-flight while this queue is full.
+const maxQueuedEmissions = 32
+
+type OpenCodeEvent = {
+ type: string
+ properties?: unknown
+}
+
+type JSONRecord = Record<string, unknown>
+
+type PendingEmission = {
+ event: OpenCodeEvent
+ priority: number
+}
+
+function asRecord(value: unknown): JSONRecord | undefined {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return
+ return value as JSONRecord
+}
+
+function projectSessionInfo(value: unknown): JSONRecord | undefined {
+ const info = asRecord(value)
+ if (!info) return
+ const time = asRecord(info.time)
+ return {
+ id: info.id,
+ directory: info.directory,
+ parentID: info.parentID,
+ version: info.version,
+ time: { created: time?.created },
+ }
+}
+
+function projectMessageInfo(value: unknown): JSONRecord | undefined {
+ const info = asRecord(value)
+ if (!info || info.role !== "assistant") return
+ const time = asRecord(info.time)
+ if (typeof time?.completed !== "number" || time.completed <= 0) return
+ const model = asRecord(info.model)
+ const tokens = asRecord(info.tokens)
+ const cache = asRecord(tokens?.cache)
+ return {
+ id: info.id,
+ sessionID: info.sessionID,
+ role: info.role,
+ mode: info.mode,
+ modelID: info.modelID,
+ providerID: info.providerID,
+ model: {
+ modelID: model?.modelID,
+ providerID: model?.providerID,
+ },
+ time: {
+ created: time.created,
+ completed: time.completed,
+ },
+ cost: info.cost,
+ finish: info.finish,
+ tokens: {
+ input: tokens?.input,
+ output: tokens?.output,
+ reasoning: tokens?.reasoning,
+ cache: {
+ read: cache?.read,
+ write: cache?.write,
+ },
+ },
+ }
+}
+
+function projectEvent(event: OpenCodeEvent): OpenCodeEvent | undefined {
+ const properties = asRecord(event.properties)
+ switch (event.type) {
+ case "session.created":
+ case "session.deleted": {
+ const info = projectSessionInfo(properties?.info)
+ if (!info) return
+ return { type: event.type, properties: { info } }
+ }
+ case "session.idle":
+ return {
+ type: event.type,
+ properties: { sessionID: properties?.sessionID },
+ }
+ case "session.error": {
+ const error = asRecord(properties?.error)
+ return {
+ type: event.type,
+ properties: {
+ sessionID: properties?.sessionID,
+ errorName: error?.name,
+ },
+ }
+ }
+ case "message.updated": {
+ const info = projectMessageInfo(properties?.info)
+ if (!info) return
+ return { type: event.type, properties: { info } }
+ }
+ case "message.part.updated": {
+ const part = asRecord(properties?.part)
+ const state = asRecord(part?.state)
+ if (part?.type !== "tool") return
+ const metadata = asRecord(part.metadata)
+ const isError = state?.status === "error"
+ const isProviderExecutedSuccess =
+ state?.status === "completed" && metadata?.providerExecuted === true
+ if (!isError && !isProviderExecutedSuccess) return
+ const time = asRecord(state.time)
+ return {
+ type: isError ? "tool.execute.error" : "tool.execute.completed",
+ properties: {
+ sessionID: part.sessionID,
+ callID: part.callID,
+ tool: part.tool,
+ status: state.status,
+ startedAt: time?.start,
+ endedAt: time?.end,
+ },
+ }
+ }
+ }
+}
+
+async function emit(event: OpenCodeEvent, directory: string, worktree: string) {
+ try {
+ const payload = new Blob([JSON.stringify({ event, directory, worktree })])
+ const child = Bun.spawn(
+ [openlitBin, "coding", "hook", "--vendor=opencode", `--event=${event.type}`],
+ {
+ stdin: payload,
+ stdout: "ignore",
+ stderr: "ignore",
+ timeout: 5_000,
+ windowsHide: true,
+ },
+ )
+ await child.exited
+ } catch {
+ // Telemetry must never interrupt the user's OpenCode session.
+ }
+}
+
+function emissionPriority(eventType: string) {
+ if (eventType === "tool.execute.before") return 0
+ return 1
+}
+
+function createEmitter(directory: string, worktree: string) {
+ const queue: PendingEmission[] = []
+ let draining = false
+ let scheduled = false
+
+ const scheduleDrain = () => {
+ if (draining || scheduled) return
+ scheduled = true
+ queueMicrotask(() => {
+ scheduled = false
+ void drain()
+ })
+ }
+
+ const drain = async () => {
+ if (draining) return
+ draining = true
+ try {
+ while (queue.length > 0) {
+ const next = queue.shift()
+ if (!next) continue
+ try {
+ await emit(next.event, directory, worktree)
+ } catch {
+ // One failed delivery must not poison the remaining queue.
+ }
+ }
+ } finally {
+ draining = false
+ if (queue.length > 0) scheduleDrain()
+ }
+ }
+
+ return (event: OpenCodeEvent) => {
+ const priority = emissionPriority(event.type)
+ if (queue.length >= maxQueuedEmissions) {
+ // Preserve FIFO among peers; only higher-value telemetry may replace
+ // the oldest lower-priority event at the hard overload boundary.
+ const dropIndex = queue.findIndex((pending) => pending.priority < priority)
+ if (dropIndex < 0) return false
+ queue.splice(dropIndex, 1)
+ }
+
+ queue.push({ event, priority })
+ scheduleDrain()
+ return true
+ }
+}
+
+function toolKey(sessionID: string, callID: string) {
+ return `${sessionID}\u0000${callID}`
+}
+
+export const OpenLitPlugin: Plugin = async ({ directory, worktree }) => {
+ const enqueue = createEmitter(directory, worktree)
+ const toolStarts = new Map<string, number>()
+
+ return {
+ event: async ({ event }) => {
+ const projected = projectEvent(event)
+ if (!projected) return
+ if (
+ projected.type === "tool.execute.error" ||
+ projected.type === "tool.execute.completed"
+ ) {
+ const properties = asRecord(projected.properties)
+ if (typeof properties?.sessionID === "string" && typeof properties.callID === "string") {
+ toolStarts.delete(toolKey(properties.sessionID, properties.callID))
+ }
+ }
+ void enqueue(projected)
+ },
+ "tool.execute.before": async (input, output) => {
+ try {
+ const startedAt = Date.now()
+ const projectedOutput = asRecord(output)
+ toolStarts.set(toolKey(input.sessionID, input.callID), startedAt)
+ void enqueue({
+ type: "tool.execute.before",
+ properties: {
+ tool: input.tool,
+ sessionID: input.sessionID,
+ callID: input.callID,
+ args: projectedOutput?.args,
+ startedAt,
+ },
+ })
+ } catch {
+ // Telemetry must never interrupt tool execution.
+ }
+ },
+ "tool.execute.after": async (input, output) => {
+ try {
+ const key = toolKey(input.sessionID, input.callID)
+ const projectedOutput = asRecord(output)
+ if (!projectedOutput) {
+ toolStarts.delete(key)
+ return
+ }
+ const endedAt = Date.now()
+ const startedAt = toolStarts.get(key) ?? endedAt
+ toolStarts.delete(key)
+ void enqueue({
+ type: "tool.execute.after",
+ properties: {
+ tool: input.tool,
+ sessionID: input.sessionID,
+ callID: input.callID,
+ args: input.args,
+ title: projectedOutput.title,
+ output: projectedOutput.output,
+ metadata: projectedOutput.metadata,
+ startedAt,
+ endedAt,
+ },
+ })
+ } catch {
+ // A malformed tool result must not interrupt the OpenCode session.
+ }
+ },
+ }
+}
diff --git a/sdk/go/semconv/coding_agent.go b/sdk/go/semconv/coding_agent.go
index b0ed0e67..b72eb686 100644
--- a/sdk/go/semconv/coding_agent.go
+++ b/sdk/go/semconv/coding_agent.go
@@ -23,6 +23,7 @@ const (
CodingAgentVendorClaudeCode = "claude-code"
CodingAgentVendorCursor = "cursor"
CodingAgentVendorCodex = "codex"
+ CodingAgentVendorOpenCode = "opencode"
CodingAgentVendorWindsurf = "windsurf"
)
@@ -111,6 +112,20 @@ const (
CodingAgentLinkageConfidenceLow = "low"
)
+// LLM turn attributes.
+const (
+ // CodingAgentLLMTurnKind describes the primary payload carried by an
+ // individual coding-agent LLM turn.
+ CodingAgentLLMTurnKind = "coding_agent.llm.turn.kind"
+)
+
+// LLM turn kind values.
+const (
+ CodingAgentLLMTurnKindPrompt = "prompt"
+ CodingAgentLLMTurnKindResponse = "response"
+ CodingAgentLLMTurnKindThought = "thought"
+)
+
// 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.
@@ -137,11 +152,11 @@ const (
CodingAgentEditDecisionModify = "modify"
CodingAgentEditDecisionAutoAccepted = "auto_accepted"
- CodingAgentEditDecisionSourceUserInteractive = "user_interactive"
- CodingAgentEditDecisionSourceUserPermanentRule = "user_permanent_rule"
- CodingAgentEditDecisionSourceHook = "hook"
- CodingAgentEditDecisionSourceConfig = "config"
- CodingAgentEditDecisionSourcePolicy = "policy"
+ CodingAgentEditDecisionSourceUserInteractive = "user_interactive"
+ CodingAgentEditDecisionSourceUserPermanentRule = "user_permanent_rule"
+ CodingAgentEditDecisionSourceHook = "hook"
+ CodingAgentEditDecisionSourceConfig = "config"
+ CodingAgentEditDecisionSourcePolicy = "policy"
)
// Tool causality attributes β€” link tool invocations back to the model
@@ -260,11 +275,11 @@ const (
// 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"
+ 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.
@@ -292,13 +307,18 @@ const (
// 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"
+ CodingAgentEventSessionStart = "coding_agent.session.start"
+ CodingAgentEventSessionEnd = "coding_agent.session.end"
+ // OpenCode has no terminal SessionEnd hook. Minimal capture uses
+ // non-terminal snapshots so counters stay visible without inventing
+ // a completed session root or emitting high-cardinality child spans.
+ CodingAgentEventSessionSnapshotStart = "coding_agent.session.snapshot.start"
+ CodingAgentEventSessionSnapshot = "coding_agent.session.snapshot"
+ 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.
diff --git a/src/client/src/__tests__/lib/platform/agents/external-discovery.test.ts b/src/client/src/__tests__/lib/platform/agents/external-discovery.test.ts
index acd344ab..84c36a0a 100644
--- a/src/client/src/__tests__/lib/platform/agents/external-discovery.test.ts
+++ b/src/client/src/__tests__/lib/platform/agents/external-discovery.test.ts
@@ -976,3 +976,38 @@ describe("deriveSnapshotFromAdapter", () => {
expect(result?.runtime_config.provider).toBe("gemini");
});
});
+
+describe("OpenCode external discovery", () => {
+ it("excludes OpenCode CLI services from SDK discovery", async () => {
+ const discoverServices = jest.fn().mockResolvedValue([
+ makeService({ serviceName: "opencode" }),
+ ]);
+ const adapter = fakeAdapter({ discoverServices });
+
+ await expect(discoverSdkRowsFromAdapter(adapter)).resolves.toEqual([]);
+ });
+
+ it("includes OpenCode spans in coding-agent discovery", async () => {
+ const adapter = fakeAdapter({
+ sampleTracesForGraph: jest.fn().mockResolvedValue([
+ makeSpan({
+ name: "coding_agent.llm.turn",
+ serviceName: "opencode",
+ timestamp: "2026-09-07T00:00:00.000Z",
+ spanAttributes: {
+ "coding_agent.client": "opencode",
+ "coding_agent.session.id": "ses-1",
+ },
+ resourceAttributes: { "service.name": "opencode" },
+ }),
+ ]),
+ });
+
+ const rows = await discoverCodingRowsFromAdapter(adapter);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ vendor: "opencode",
+ session_count_24h: 1,
+ });
+ });
+});
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
index f9ef41a2..4a59b62f 100644
--- a/src/client/src/__tests__/lib/platform/coding-agents/queries.test.ts
+++ b/src/client/src/__tests__/lib/platform/coding-agents/queries.test.ts
@@ -226,6 +226,39 @@ describe("coding agent query service", () => {
);
});
+ it("aggregates OpenCode snapshot counters numerically without losing total tokens", async () => {
+ mockDataCollector.mockResolvedValue({ err: null, data: [] });
+
+ await listSessions(auth, { limit: 10 });
+ await getCodingSessionDigest(auth, "snapshot-session");
+ await listCodingUsers(auth, { limit: 10 });
+
+ const queries = mockDataCollector.mock.calls.map(
+ ([request]) => request.query as string
+ );
+ const perSpanTotal =
+ /nullIf\(\s*toInt64OrZero\(SpanAttributes\['gen_ai\.usage\.total_tokens'\]\),\s*0\s*\)/;
+ for (const query of queries) {
+ expect(query).toMatch(perSpanTotal);
+ expect(query).toContain("'coding_agent.session.snapshot'");
+ }
+ expect(queries[0]).toContain(
+ "max(toInt64OrZero(SpanAttributes['coding_agent.session.tool_call_count']))"
+ );
+ expect(queries[2]).toContain(
+ "max(toInt64OrZero(SpanAttributes['coding_agent.session.tool_call_count']))"
+ );
+ expect(queries[0]).toContain(
+ "max(toInt64OrZero(SpanAttributes['coding_agent.session.duration_ms']))"
+ );
+ expect(queries[1]).toContain(
+ "max(toInt64OrZero(SpanAttributes['coding_agent.session.duration_ms']))"
+ );
+ expect(queries.join("\n")).not.toMatch(
+ /toInt64OrZero\((?:any|max)\(SpanAttributes\['coding_agent\.session\.(?:duration_ms|tool_call_count)'\]\)\)/
+ );
+ });
+
it("falls back to default sort columns for unknown sortBy values", async () => {
mockDataCollector.mockResolvedValueOnce({
err: null,
diff --git a/src/client/src/app/(playground)/agents/__tests__/no-coding-agents.test.tsx b/src/client/src/app/(playground)/agents/__tests__/no-coding-agents.test.tsx
new file mode 100644
index 00000000..35a30563
--- /dev/null
+++ b/src/client/src/app/(playground)/agents/__tests__/no-coding-agents.test.tsx
@@ -0,0 +1,40 @@
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import NoCodingAgents from "@/app/(playground)/agents/no-coding-agents";
+
+jest.mock("@/selectors/database-config", () => ({
+ getPingStatus: jest.fn(),
+}));
+
+jest.mock("@/store", () => ({
+ useRootStore: jest.fn(() => "success"),
+}));
+
+jest.mock("@/utils/hooks/useFetchWrapper", () => ({
+ __esModule: true,
+ default: jest.fn(() => ({
+ data: [{ apiKey: "test-api-key" }],
+ fireRequest: jest.fn(),
+ isLoading: false,
+ })),
+}));
+
+describe("NoCodingAgents OpenCode onboarding", () => {
+ it("shows the OpenCode install command, restart, and first-session steps", () => {
+ render(<NoCodingAgents compact />);
+
+ fireEvent.click(screen.getByRole("button", { name: /OpenCode/ }));
+
+ expect(
+ screen.getByText(/openlit coding install --vendor=opencode/),
+ ).toBeInTheDocument();
+
+ const postInstall = screen
+ .getByText("After running the snippet")
+ .closest("div");
+ expect(postInstall).not.toBeNull();
+ const steps = within(postInstall as HTMLElement).getAllByRole("listitem");
+ expect(steps).toHaveLength(2);
+ expect(steps[0]).toHaveTextContent("Restart OpenCode.");
+ expect(steps[1]).toHaveTextContent("Send any prompt in OpenCode.");
+ });
+});
diff --git a/src/client/src/app/(playground)/agents/no-coding-agents.tsx b/src/client/src/app/(playground)/agents/no-coding-agents.tsx
index 866f0327..e29b70d0 100644
--- a/src/client/src/app/(playground)/agents/no-coding-agents.tsx
+++ b/src/client/src/app/(playground)/agents/no-coding-agents.tsx
@@ -17,7 +17,7 @@
* 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.
+ * reference lives at docs.openlit.io/.../coding-agents/setup-and-configure.
*/
import { ComponentType, useCallback, useEffect, useMemo, useState } from "react";
@@ -34,6 +34,11 @@ import {
CodingAgentVendorIcon,
hasCodingAgentVendorIcon,
} from "@/components/svg/coding-agents";
+import {
+ AGENTS_CODING_VENDOR_OPENCODE_LABEL,
+ AGENTS_CODING_VENDOR_OPENCODE_RESTART,
+ AGENTS_CODING_SETUP_GUIDE,
+} from "@/constants/messages/en";
import LinuxSvg from "@/components/svg/linux";
import MacSvg from "@/components/svg/mac";
import WindowsSvg from "@/components/svg/windows";
@@ -44,7 +49,7 @@ import { ApiKey } from "@/types/api-key";
type OsIconComponent = ComponentType<{ className?: string }>;
-type VendorId = "claude-code" | "cursor" | "codex";
+type VendorId = "claude-code" | "cursor" | "codex" | "opencode";
type OsId = "macos" | "linux" | "windows";
interface VendorMeta {
@@ -68,6 +73,8 @@ interface VendorMeta {
restart: string;
// Optional follow-up steps. Currently only Codex needs them.
extraSteps?: string[];
+ // Some vendors only need a restart after installation.
+ showPromptStep?: boolean;
};
}
@@ -112,6 +119,14 @@ const VENDORS: VendorMeta[] = [
],
},
},
+ {
+ id: "opencode",
+ label: AGENTS_CODING_VENDOR_OPENCODE_LABEL,
+ cliFlag: "opencode",
+ postInstall: {
+ restart: AGENTS_CODING_VENDOR_OPENCODE_RESTART,
+ },
+ },
];
// Use the locally vendored brand SVGs (icons8) so the OS cards
@@ -473,7 +488,9 @@ export default function NoCodingAgents({ compact = false }: NoCodingAgentsProps)
{(vendor.postInstall.extraSteps || []).map((step, i) => (
<li key={i}>{step}</li>
))}
- <li>Send any prompt in {vendor.label}.</li>
+ {vendor.postInstall.showPromptStep !== false && (
+ <li>Send any prompt in {vendor.label}.</li>
+ )}
</ol>
</div>
@@ -481,12 +498,12 @@ export default function NoCodingAgents({ compact = false }: NoCodingAgentsProps)
Full reference (env vars, content-capture modes,
marketplace install):{" "}
<a
- href="https://docs.openlit.io/latest/openlit/coding-agents/onboarding"
+ href="https://docs.openlit.io/latest/openlit/coding-agents/setup-and-configure"
target="_blank"
rel="noreferrer"
className="text-primary hover:underline"
>
- coding-agents onboarding
+ {AGENTS_CODING_SETUP_GUIDE}
</a>
.
</p>
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
index ea476e90..e324b4d3 100644
--- 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
@@ -1,7 +1,7 @@
{
"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 \u2014 sourced live from otel_traces emitted by the openlit CLI hook.",
+ "description": "Coding-agent observability across vendors (Claude Code, Cursor, Codex, OpenCode). Sessions, cost, tools, users, classification, and governance \u2014 sourced live from otel_traces emitted by the openlit CLI hook.",
"parentId": null,
"isMainDashboard": false,
"isPinned": true,
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 461592e5..eca6d1e5 100644
--- a/src/client/src/components/(playground)/request/components/chat-view.tsx
+++ b/src/client/src/components/(playground)/request/components/chat-view.tsx
@@ -292,9 +292,9 @@ function extractItemsFromSpan(
// 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)
+ // - "prompt" β†’ user message body lives in input.messages
+ // - "response" β†’ assistant body lives in output.messages
+ // - "thought" β†’ thinking-only turn (no user-visible message)
const codingTurnKind = attrs["coding_agent.llm.turn.kind"] as string | undefined;
if (!skipMessages) {
diff --git a/src/client/src/components/svg/__tests__/coding-agents.test.tsx b/src/client/src/components/svg/__tests__/coding-agents.test.tsx
new file mode 100644
index 00000000..5b610e20
--- /dev/null
+++ b/src/client/src/components/svg/__tests__/coding-agents.test.tsx
@@ -0,0 +1,27 @@
+import { render, screen } from "@testing-library/react";
+import {
+ CodingAgentVendorIcon,
+ codingAgentVendorLabel,
+ hasCodingAgentVendorIcon,
+} from "@/components/svg/coding-agents";
+import type { CodingAgentVendor } from "@/types/agents";
+
+describe("OpenCode coding-agent vendor presentation", () => {
+ it("provides the OpenCode label and icon through the shared helpers", () => {
+ const vendor = "opencode" satisfies CodingAgentVendor;
+
+ expect(codingAgentVendorLabel(vendor)).toBe("OpenCode");
+ expect(hasCodingAgentVendorIcon(vendor)).toBe(true);
+
+ render(<CodingAgentVendorIcon vendor={vendor} className="vendor-icon" />);
+
+ const icon = screen.getByRole("img", { name: "OpenCode" });
+ expect(icon).toHaveClass("vendor-icon");
+ expect(icon.querySelectorAll("path")).toHaveLength(2);
+ expect(
+ Array.from(icon.querySelectorAll("path")).every(
+ (path) => path.getAttribute("fill") === "currentColor",
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/src/client/src/components/svg/coding-agents.tsx b/src/client/src/components/svg/coding-agents.tsx
index a6dda592..4bed9e73 100644
--- a/src/client/src/components/svg/coding-agents.tsx
+++ b/src/client/src/components/svg/coding-agents.tsx
@@ -17,9 +17,15 @@
* 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.
+ * - OpenCode: geometry from anomalyco/opencode's official
+ * `packages/console/app/src/asset/brand/opencode-logo-light-square.svg`
+ * (MIT; see /THIRD_PARTY_NOTICES.md). The clip/mask wrappers are removed
+ * and their x-offset is folded into the same two paths so the mark can
+ * tint via `currentColor`.
*/
import type { SVGProps } from "react";
+import { AGENTS_CODING_VENDOR_OPENCODE_LABEL } from "@/constants/messages/en";
type IconProps = SVGProps<SVGSVGElement> & { className?: string };
@@ -99,6 +105,28 @@ export function CodexIcon({ className = "h-4 w-4" }: IconProps) {
);
}
+export function OpenCodeIcon({
+ className = "h-4 w-4",
+ ...rest
+}: IconProps) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 300 300"
+ className={className}
+ aria-label={AGENTS_CODING_VENDOR_OPENCODE_LABEL}
+ role="img"
+ {...rest}
+ >
+ <path d="M210 240H90V120H210V240Z" fill="currentColor" />
+ <path
+ d="M210 60H90V240H210V60ZM270 300H30V0H270V300Z"
+ fill="currentColor"
+ />
+ </svg>
+ );
+}
+
/**
* Returns true when we have an inline logo for the given vendor.
* Callers (table rows, session cards, trace-detail pills) use this
@@ -115,6 +143,7 @@ export function hasCodingAgentVendorIcon(
case "cursor":
case "claude-code":
case "codex":
+ case "opencode":
return true;
default:
return false;
@@ -134,6 +163,7 @@ const CODING_AGENT_VENDOR_LABELS: Record<string, string> = {
cursor: "Cursor",
"claude-code": "Claude Code",
codex: "Codex",
+ opencode: AGENTS_CODING_VENDOR_OPENCODE_LABEL,
windsurf: "Windsurf",
};
@@ -161,6 +191,8 @@ export function CodingAgentVendorIcon({
switch (vendor.toLowerCase()) {
case "cursor":
return <CursorIcon className={className} />;
+ case "opencode":
+ return <OpenCodeIcon className={className} />;
case "claude-code":
return <ClaudeCodeIcon className={className} />;
case "codex":
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index b47f262d..37515605 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -806,6 +806,8 @@ 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_CODING_VENDOR_OPENCODE_LABEL = "OpenCode";
+export const AGENTS_CODING_VENDOR_OPENCODE_RESTART = "Restart OpenCode.";
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
@@ -876,8 +878,9 @@ 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_SETUP_GUIDE = "coding-agents setup guide";
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.";
+ "Install the openlit CLI on a teammate's machine and run a Claude Code, Cursor, Codex, or OpenCode 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";
@@ -894,7 +897,7 @@ 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_SESSIONS_SUMMARY = "Per-session timeline of coding-agent runs (Cursor, Claude Code, Codex, OpenCode).";
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.";
diff --git a/src/client/src/lib/platform/agents/external-discovery.ts b/src/client/src/lib/platform/agents/external-discovery.ts
index c76150b6..1b10a71d 100644
--- a/src/client/src/lib/platform/agents/external-discovery.ts
+++ b/src/client/src/lib/platform/agents/external-discovery.ts
@@ -50,6 +50,14 @@ export interface CodingDiscoveryRow {
pr_count_24h: number;
}
+const CODING_AGENT_SERVICES = new Set([
+ "cursor",
+ "claude-code",
+ "codex",
+ "opencode",
+ "windsurf",
+]);
+
function windowHours(hours: number): QueryTimeRange {
const end = new Date();
const start = new Date(end.getTime() - hours * 60 * 60 * 1000);
@@ -60,7 +68,7 @@ function isCodingService(svc: DiscoveredService): boolean {
const sdk = (svc.sdkName || "").toLowerCase();
const name = (svc.serviceName || "").toLowerCase();
if (sdk === "openlit-cli") return true;
- if (["cursor", "claude-code", "codex", "windsurf"].includes(name)) return true;
+ if (CODING_AGENT_SERVICES.has(name)) return true;
return false;
}
@@ -185,9 +193,8 @@ export async function discoverCodingRowsFromAdapter(
if (span.timestamp > acc.last_seen) acc.last_seen = span.timestamp;
}
- const allowed = new Set(["cursor", "claude-code", "codex", "windsurf"]);
return Array.from(byVendor.values())
- .filter((a) => allowed.has(a.vendor))
+ .filter((a) => CODING_AGENT_SERVICES.has(a.vendor))
.map((a) => ({
vendor: a.vendor as CodingAgentVendor,
client_version: a.client_version,
diff --git a/src/client/src/lib/platform/coding-agents/queries.ts b/src/client/src/lib/platform/coding-agents/queries.ts
index 83f83080..f61a4241 100644
--- a/src/client/src/lib/platform/coding-agents/queries.ts
+++ b/src/client/src/lib/platform/coding-agents/queries.ts
@@ -345,11 +345,11 @@ const SESSION_BASE_COLUMNS = `
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}'])),
+ max(toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.sessionDurationMs}'])),
toInt64(toUnixTimestamp64Milli(max(Timestamp)) - toUnixTimestamp64Milli(min(Timestamp)))
) AS duration_ms,
greatest(
- toInt64OrZero(any(SpanAttributes['${CODING_AGENT_ATTR.sessionToolCallCount}'])),
+ max(toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.sessionToolCallCount}'])),
toInt64(countIf(SpanName = '${CODING_AGENT_SPAN_TOOL_CALL}'))
) AS tool_call_count,
-- Cost rollup. Two source paths exist:
@@ -452,8 +452,11 @@ const SESSION_BASE_COLUMNS = `
)), 0),
sumOrNull(if(
SpanName != '${CODING_AGENT_SPAN_SESSION}',
- toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
- toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}']),
+ coalesce(
+ nullIf(toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageTotalTokens}']), 0),
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}'])
+ ),
0
))
)) AS total_tokens,
@@ -1076,8 +1079,11 @@ export async function getCodingSessionDigest(
)), 0),
sumOrNull(if(
SpanName != '${CODING_AGENT_SPAN_SESSION}',
- toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
- toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}']),
+ coalesce(
+ nullIf(toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageTotalTokens}']), 0),
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}'])
+ ),
0
))
)) AS total_tokens,
@@ -1087,7 +1093,7 @@ export async function getCodingSessionDigest(
-- 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}'])),
+ max(toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.sessionDurationMs}'])),
toInt64(toUnixTimestamp64Milli(max(Timestamp)) - toUnixTimestamp64Milli(min(Timestamp)))
) AS duration_ms,
-- Predominant model: the latest non-empty
@@ -1351,7 +1357,10 @@ export async function getCodingUserDigest(
${USER_EXPR} AS user,
min(Timestamp) AS first_seen,
max(Timestamp) AS last_seen,
- countIf(SpanName = '${CODING_AGENT_SPAN_TOOL_CALL}') AS tool_calls,
+ greatest(
+ max(toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.sessionToolCallCount}'])),
+ toInt64(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
@@ -1676,7 +1685,10 @@ export async function listCodingUsers(
${USER_EXPR} AS user,
${VENDOR_EXPR} AS vendor,
max(Timestamp) AS session_last_ts,
- countIf(SpanName = '${CODING_AGENT_SPAN_TOOL_CALL}') AS tool_calls,
+ greatest(
+ max(toInt64OrZero(SpanAttributes['${CODING_AGENT_ATTR.sessionToolCallCount}'])),
+ toInt64(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
@@ -1705,8 +1717,11 @@ export async function listCodingUsers(
)), 0),
sumOrNull(if(
SpanName != '${CODING_AGENT_SPAN_SESSION}',
- toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
- toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}']),
+ coalesce(
+ nullIf(toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageTotalTokens}']), 0),
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageInputTokens}']) +
+ toInt64OrZero(SpanAttributes['${GEN_AI_ATTR.usageOutputTokens}'])
+ ),
0
))
) AS tokens,
diff --git a/src/client/src/lib/platform/coding-agents/table-details.ts b/src/client/src/lib/platform/coding-agents/table-details.ts
index a8c71d90..90f31faf 100644
--- a/src/client/src/lib/platform/coding-agents/table-details.ts
+++ b/src/client/src/lib/platform/coding-agents/table-details.ts
@@ -21,6 +21,10 @@ 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";
+export const CODING_AGENT_SPAN_SESSION_SNAPSHOT_START =
+ "coding_agent.session.snapshot.start";
+export const CODING_AGENT_SPAN_SESSION_SNAPSHOT =
+ "coding_agent.session.snapshot";
/** All coding-agent span names in a single tuple β€” handy for `IN (...)` clauses. */
export const CODING_AGENT_SPAN_NAMES = [
@@ -31,6 +35,8 @@ export const CODING_AGENT_SPAN_NAMES = [
CODING_AGENT_SPAN_LLM_TURN,
CODING_AGENT_SPAN_GIT_COMMIT,
CODING_AGENT_SPAN_GIT_PR,
+ CODING_AGENT_SPAN_SESSION_SNAPSHOT_START,
+ CODING_AGENT_SPAN_SESSION_SNAPSHOT,
] as const;
/**
diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.ts
index b48a101f..8cc294bb 100644
--- a/src/client/src/lib/platform/request/index.ts
+++ b/src/client/src/lib/platform/request/index.ts
@@ -528,7 +528,7 @@ export async function getHeirarchyViaSpanId(spanId: string, databaseConfigId?: s
AND (
notEmpty(SpanAttributes['gen_ai.input.messages'])
OR notEmpty(SpanAttributes['gen_ai.output.messages'])
- OR SpanAttributes['coding_agent.llm.turn.kind'] IN ('user_prompt', 'assistant_only')
+ OR SpanAttributes['coding_agent.llm.turn.kind'] IN ('prompt', 'response', 'thought', 'user_prompt', 'assistant_only')
)
ORDER BY Timestamp DESC
LIMIT 2000
diff --git a/src/client/src/types/agents.ts b/src/client/src/types/agents.ts
index 0033b869..9ef3eeeb 100644
--- a/src/client/src/types/agents.ts
+++ b/src/client/src/types/agents.ts
@@ -24,6 +24,7 @@ export type AgentSource = "controller" | "sdk" | "both" | "coding";
*/
export type CodingAgentVendor =
| "claude-code"
+ | "opencode"
| "cursor"
| "codex"
| "windsurf";