Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ The environment variables (set them in your shell profile — `~/.zshrc`, `~/.ba
| `OPENCODE_METRIC_PREFIX` | `opencode.` | Prefix for all metric names (e.g. set to `claude_code.` for Claude Code dashboard compatibility) |
| `OPENCODE_DISABLE_METRICS` | *(unset)* | Comma-separated list of metric name suffixes to disable (e.g. `cache.count,session.duration`) |
| `OPENCODE_DISABLE_LOGS` | *(unset)* | Set to any non-empty value to suppress all OTLP log events while leaving metrics and traces unchanged |
| `OPENCODE_CAPTURE_PROMPT_IN_LOGS` | *(unset)* | Set to any non-empty value to include the full prompt text in the `prompt` attribute of `user_prompt` log events. **Log events only** — trace spans carry an observed prompt in `input.value` regardless of this flag (disable span-level capture separately via `OPENCODE_DISABLE_TRACES`). **Off by default — prompts may contain secrets or PII; enable only for trusted collectors.** |
| `OPENCODE_CAPTURE_PROMPT_IN_LOGS` | *(unset)* | Set to any non-empty value to include the full prompt text in the `prompt` attribute of `user_prompt` log events. **Log events only** — span-level content capture is controlled separately by `OPENCODE_CAPTURE_CONTENT`. **Off by default — prompts may contain secrets or PII; enable only for trusted collectors.** |
| `OPENCODE_CAPTURE_MODEL_CONTEXT` | *(unset)* | Set to any non-empty value to attach a bounded text-only preview of the primary model-visible context to LLM spans. Off by default; can include system instructions, earlier messages, and tool text. |
| `OPENCODE_COMBINE_REASONING_TOKENS` | *(unset)* | Set to any non-empty value to report reasoning tokens as part of `output` instead of a separate `reasoning` type. OpenCode V2 excludes reasoning from `output`, while Claude Code includes it, so enable this for Claude Code dashboard and cost parity. Applies to the `token.usage` metric, `api_request` `output_tokens` (with `reasoning_tokens` omitted), and the LLM span `llm.token_count.completion`; `llm.token_count.completion_details.reasoning` still carries the reasoning subset. |
| `OPENCODE_DISABLE_TRACES` | *(unset)* | Comma-separated list of trace types to disable (`session`, `llm`, `tool`). Use `all`, `*`, `true`, or `1` to disable every trace type |
Expand All @@ -155,8 +155,9 @@ The environment variables (set them in your shell profile — `~/.zshrc`, `~/.ba
| `OPENCODE_TRACEPARENT` | *(unset)* | W3C [`traceparent`](https://www.w3.org/TR/trace-context/#traceparent-header) string. When set, all spans are parented under this remote context so opencode traces nest inside a caller's trace (e.g. a CI job). Invalid values are logged and ignored. Note: with the default `ParentBased` sampler, a value with the sampled flag off (`...-00`) suppresses all trace export. |
| `OPENCODE_TRACESTATE` | *(unset)* | W3C [`tracestate`](https://www.w3.org/TR/trace-context/#tracestate-header) string, parsed alongside `OPENCODE_TRACEPARENT` and attached to the remote parent context. Ignored unless a valid `OPENCODE_TRACEPARENT` is also set. |
| `OPENCODE_TRACE_PROPAGATION_PROVIDERS` | *(unset)* | Comma-separated opencode provider IDs that receive W3C `traceparent` and `tracestate` headers on LLM requests. Use `*` to explicitly enable every provider. |
| `OPENCODE_CAPTURE_CONTENT` | *(unset)* | Set to any non-empty value to include user prompts, model outputs, and tool parameters/inputs/outputs in span attributes (`input.value`, `output.value`, `llm.input_messages`, `llm.output_messages`, `tool.parameters`). **Off by default — span attributes omit all conversation content; enable only for trusted collectors.** |

Prompt logging remains disabled by default. Enable it only when the configured telemetry destination is trusted to receive potentially sensitive prompt contents.
Prompt logging and span content capture remain disabled by default. Enable them only when the configured telemetry destination is trusted to receive potentially sensitive conversation contents.

### Plugin options (opencode.json)

Expand Down Expand Up @@ -188,6 +189,7 @@ Option keys mirror the resolved config and map to the environment variables:
| `enabled` | `OPENCODE_ENABLE_TELEMETRY` |
| `logsEnabled` | `OPENCODE_DISABLE_LOGS` (inverted) |
| `capturePromptInLogs` | `OPENCODE_CAPTURE_PROMPT_IN_LOGS` |
| `captureContent` | `OPENCODE_CAPTURE_CONTENT` |
| `captureModelContext` | `OPENCODE_CAPTURE_MODEL_CONTEXT` |
| `combineReasoningTokens` | `OPENCODE_COMBINE_REASONING_TOKENS` |
| `logLevel` | *(none — option only)*: `debug`, `info`, `warn`, `error` |
Expand Down
3 changes: 3 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type PluginConfig = {
logsEnabled: boolean
capturePromptInLogs: boolean
captureModelContext: boolean
captureContent: boolean
combineReasoningTokens: boolean
logLevel: string | undefined
endpoint: string
Expand Down Expand Up @@ -62,6 +63,7 @@ export type OtelPluginOptions = {
logsEnabled?: boolean
capturePromptInLogs?: boolean
captureModelContext?: boolean
captureContent?: boolean
combineReasoningTokens?: boolean
logLevel?: string
endpoint?: string
Expand Down Expand Up @@ -201,6 +203,7 @@ export function loadConfig(options: OtelPluginOptions = {}): PluginConfig {
logsEnabled: pickBoolean(resolvedOptions.logsEnabled) ?? !hasNonEmptyEnv("OPENCODE_DISABLE_LOGS"),
capturePromptInLogs: pickBoolean(resolvedOptions.capturePromptInLogs) ?? hasNonEmptyEnv("OPENCODE_CAPTURE_PROMPT_IN_LOGS"),
captureModelContext: pickBoolean(resolvedOptions.captureModelContext) ?? hasNonEmptyEnv("OPENCODE_CAPTURE_MODEL_CONTEXT"),
captureContent: pickBoolean(resolvedOptions.captureContent) ?? hasNonEmptyEnv("OPENCODE_CAPTURE_CONTENT"),
combineReasoningTokens: pickBoolean(resolvedOptions.combineReasoningTokens) ?? hasNonEmptyEnv("OPENCODE_COMBINE_REASONING_TOKENS"),
logLevel: pickString(resolvedOptions.logLevel),
endpoint: pickString(resolvedOptions.endpoint) ?? process.env["OPENCODE_OTLP_ENDPOINT"] ?? "http://localhost:4317",
Expand Down
14 changes: 8 additions & 6 deletions src/handlers/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
isTraceEnabled,
markSeen,
modelRef,
redactErrorMessage,
resolveSubagentTraceContext,
setBoundedMap,
totalTokens,
Expand Down Expand Up @@ -191,7 +192,7 @@ export function handleExecutionStarted(e: EventOf<"session.execution.started">,
const parentCtx = isSubagent && totals?.parentID
? resolveSubagentTraceContext(sessionID, totals.parentID, totals.agent, ctx)
: ctx.rootContext()
const promptText = pendingPrompt?.text ?? ""
const promptText = (pendingPrompt?.text ?? "").slice(0, 64_000)

const span = ctx.tracer.startSpan(
`${ctx.tracePrefix}session`,
Expand All @@ -203,7 +204,7 @@ export function handleExecutionStarted(e: EventOf<"session.execution.started">,
[AGENT_NAME]: totals?.agent ?? "unknown",
"agent.type": totals?.agentType ?? "primary",
"session.is_subagent": isSubagent,
...(promptText
...(promptText && ctx.captureContent

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the prompt on the session span

When content capture is enabled for a prompt longer than 64,000 characters, handleExecutionStarted puts the entire pendingPrompt.text into input.value and llm.input_messages; unlike handleStepStarted, this session-span path never slices it. This can still create an oversized span despite the new content limit, so cap the root prompt before attaching it.

AGENTS.md reference: AGENTS.md:L61-L61

Useful? React with 👍 / 👎.

? {
[INPUT_VALUE]: promptText,
[INPUT_MIME_TYPE]: MimeType.TEXT,
Expand Down Expand Up @@ -258,8 +259,8 @@ export function handleExecutionEnded(
}
if (outcome.type === "failed") {
const message = errorSummary(outcome.error)
span.setStatus({ code: SpanStatusCode.ERROR, message })
span.setAttribute("error", message)
span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.captureContent ? message : redactErrorMessage(message) })
span.setAttribute("error", ctx.captureContent ? message : redactErrorMessage(message))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Redact errors before emitting failure logs

When captureContent is off (the default) and a failed session or tool error echoes a prompt or query, this redacts only the span fields: handleExecutionEnded still emits the raw message in session.error, and finishTool still emits the raw error in tool_result. Since OTLP logs are enabled by default, those failures still export user content despite the privacy mode; redact those log attributes too.

Useful? React with 👍 / 👎.

} else if (outcome.type === "interrupted") {
span.setAttribute("session.interrupted_reason", outcome.reason)
span.setStatus({ code: SpanStatusCode.OK })
Expand All @@ -273,6 +274,7 @@ export function handleExecutionEnded(

if (outcome.type === "failed") {
const message = errorSummary(outcome.error)
const safeMessage = ctx.captureContent ? message : redactErrorMessage(message)
ctx.emitLog({
severityNumber: SeverityNumber.ERROR,
severityText: "ERROR",
Expand All @@ -282,12 +284,12 @@ export function handleExecutionEnded(
attributes: {
"event.name": "session.error",
"session.id": sessionID,
error: message,
error: safeMessage,
...agentAttrs(totals?.agent ?? "unknown", totals?.agentType ?? "unknown"),
...ctx.commonAttrs,
},
})
void ctx.log("error", "otel: session.error", { sessionID, error: message })
void ctx.log("error", "otel: session.error", { sessionID, error: safeMessage })
}
}

Expand Down
14 changes: 8 additions & 6 deletions src/handlers/step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
genAiProviderName,
isMetricEnabled,
isTraceEnabled,
redactErrorMessage,
markSeen,
resolveRunContext,
setBoundedMap,
Expand Down Expand Up @@ -90,7 +91,8 @@ export function handleStepStarted(e: EventOf<"session.step.started">, ctx: Handl
}

if (!isTraceEnabled("llm", ctx)) return
const promptText = ctx.tracing.activePrompts.get(d.sessionID)?.text
const rawPrompt = ctx.tracing.activePrompts.get(d.sessionID)?.text
const promptText = rawPrompt !== undefined ? rawPrompt.slice(0, 64_000) : undefined
const attributes = {
[OPENINFERENCE_SPAN_KIND]: OpenInferenceSpanKind.LLM,
[SESSION_ID]: d.sessionID,
Expand All @@ -100,7 +102,7 @@ export function handleStepStarted(e: EventOf<"session.step.started">, ctx: Handl
[LLM_PROVIDER]: d.model.providerID,
"gen_ai.provider.name": genAiProviderName(d.model.providerID),
[LLM_MODEL_NAME]: d.model.id,
...(promptText
...(promptText && ctx.captureContent
? {
[INPUT_VALUE]: promptText,
[INPUT_MIME_TYPE]: MimeType.TEXT,
Expand Down Expand Up @@ -195,7 +197,7 @@ export function handleStepEnded(e: EventOf<"session.step.ended">, ctx: HandlerCo
[LLM_COST_TOTAL]: d.cost,
cost_usd: d.cost,
duration_ms: durationMs,
...(output ? {
...(output && ctx.captureContent ? {
[OUTPUT_VALUE]: output,
[OUTPUT_MIME_TYPE]: MimeType.TEXT,
[LLM_OUTPUT_MESSAGES]: JSON.stringify([{ role: "assistant", content: output }]),
Expand Down Expand Up @@ -264,9 +266,9 @@ export function handleStepFailed(e: EventOf<"session.step.failed">, ctx: Handler
[LLM_TOKEN_COUNT_TOTAL]: allTokens(d.tokens),
} : {}),
...(d.cost !== undefined ? { [LLM_COST_TOTAL]: d.cost, cost_usd: d.cost } : {}),
...(output ? { [OUTPUT_VALUE]: output, [OUTPUT_MIME_TYPE]: MimeType.TEXT } : {}),
...(output && ctx.captureContent ? { [OUTPUT_VALUE]: output, [OUTPUT_MIME_TYPE]: MimeType.TEXT } : {}),
})
span.setStatus({ code: SpanStatusCode.ERROR, message: error })
span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.captureContent ? error : redactErrorMessage(error) })
span.end(e.created)
}
cleanupStep(d.assistantMessageID, d.sessionID, ctx)
Expand All @@ -284,7 +286,7 @@ export function handleStepFailed(e: EventOf<"session.step.failed">, ctx: Handler
provider: providerID,
"gen_ai.provider.name": genAiProviderName(providerID),
...agentAttrs(agent, agentType),
error,
error: ctx.captureContent ? error : redactErrorMessage(error),
duration_ms: durationMs,
...ctx.commonAttrs,
},
Expand Down
68 changes: 49 additions & 19 deletions src/handlers/tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
getSessionAgentMeta,
isMetricEnabled,
isTraceEnabled,
redactErrorMessage,
resolveStepContext,
setBoundedMap,
} from "../util.ts"
Expand Down Expand Up @@ -79,11 +80,9 @@ export function handleToolCalled(e: EventOf<"session.tool.called">, ctx: Handler
}

const { agentName, agentType } = getSessionAgentMeta(d.sessionID, ctx)
const inputJson = safeJson(d.input)
const inputJson = ctx.captureContent ? safeJson(d.input) : ""
ctx.tracing.toolSpans.get(d.id)?.setAttributes({
[TOOL_PARAMETERS]: inputJson,
[INPUT_VALUE]: inputJson,
[INPUT_MIME_TYPE]: MimeType.JSON,
...(ctx.captureContent ? { [TOOL_PARAMETERS]: inputJson, [INPUT_VALUE]: inputJson, [INPUT_MIME_TYPE]: MimeType.JSON } : {}),
Comment thread
enternal111 marked this conversation as resolved.
Resolved
[AGENT_NAME]: agentName,
"agent.type": agentType,
"tool.provider_executed": isProviderExecuted(d),
Expand Down Expand Up @@ -145,15 +144,15 @@ export function handleToolProgress(e: EventOf<"session.tool.progress">, ctx: Han
/** Ends a successful tool call: records duration, sets output attributes, and emits `tool_result`. */
export function handleToolSuccess(e: EventOf<"session.tool.success">, ctx: HandlerContext) {
linkSubagent(e.data.id, e.data.metadata?.["sessionID"], ctx)
const output = contentText(e.data.content)
finishTool(e.data.id, e.data.sessionID, e.created, true, output, undefined, ctx)
const { text, fullLength } = contentText(e.data.content)
finishTool(e.data.id, e.data.sessionID, e.created, true, text, undefined, ctx, fullLength)
}

/** Ends a failed tool call: records duration, sets error attributes, and emits `tool_result`. */
export function handleToolFailed(e: EventOf<"session.tool.failed">, ctx: HandlerContext) {
linkSubagent(e.data.id, e.data.metadata?.["sessionID"], ctx)
const output = contentText(e.data.content)
finishTool(e.data.id, e.data.sessionID, e.created, false, output, errorSummary(e.data.error), ctx)
const { text, fullLength } = contentText(e.data.content)
finishTool(e.data.id, e.data.sessionID, e.created, false, text, errorSummary(e.data.error), ctx, fullLength)
}

function finishTool(
Expand All @@ -164,6 +163,7 @@ function finishTool(
output: string,
error: string | undefined,
ctx: HandlerContext,
fullOutputLength = 0,
) {
const meta = ctx.tracing.toolMeta.get(callID)
ctx.tracing.toolMeta.delete(callID)
Expand All @@ -172,7 +172,7 @@ function finishTool(
const start = observedExecution ? meta.startMs : endMs
const durationMs = Math.max(0, endMs - start)
const { agentName, agentType } = getSessionAgentMeta(sessionID, ctx)
const sizeBytes = output ? Buffer.byteLength(output, "utf8") : 0
const sizeBytes = fullOutputLength > 0 ? fullOutputLength : (output ? output.length : 0)

if (success && observedExecution && meta.command && SHELL_TOOL_RE.test(tool) && GIT_COMMIT_RE.test(meta.command)) {
if (isMetricEnabled("commit.count", ctx)) {
Expand Down Expand Up @@ -205,15 +205,15 @@ function finishTool(
const span = ctx.tracing.toolSpans.get(callID)
if (span) {
span.setAttributes({ [AGENT_NAME]: agentName, "agent.type": agentType, "tool.success": success })
if (output) {
if (output && ctx.captureContent) {
span.setAttributes({ [OUTPUT_VALUE]: output, [OUTPUT_MIME_TYPE]: MimeType.TEXT })
}
if (success) {
span.setAttribute("tool.result_size_bytes", sizeBytes)
span.setStatus({ code: SpanStatusCode.OK })
} else {
span.setAttribute("tool.error", error ?? "unknown")
span.setStatus({ code: SpanStatusCode.ERROR, message: error ?? "unknown" })
span.setAttribute("tool.error", ctx.captureContent ? (error ?? "unknown") : redactErrorMessage(error ?? "unknown"))
span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.captureContent ? error : redactErrorMessage(error ?? "unknown") })
}
span.end(endMs)
}
Expand All @@ -233,23 +233,53 @@ function finishTool(
...agentAttrs(agentName, agentType),
success,
duration_ms: durationMs,
...(success ? { tool_result_size_bytes: sizeBytes } : { error: error ?? "unknown" }),
...(success ? { tool_result_size_bytes: sizeBytes } : { error: ctx.captureContent ? error ?? "unknown" : redactErrorMessage(error ?? "unknown") }),
...ctx.commonAttrs,
},
})
}

function contentText(content: readonly ToolContent[] | undefined): string {
if (!content) return ""
return content
.map((part) => (part.type === "text" ? part.text : part.name ?? part.uri))
.filter(Boolean)
function contentText(content: readonly ToolContent[] | undefined): { text: string; fullLength: number } {
if (!content) return { text: "", fullLength: 0 }
const full = content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n")
return { text: full.length <= 64_000 ? full : full.slice(0, 64_000), fullLength: Buffer.byteLength(full, "utf8") }
}

const MAX_JSON_CHARS = 64_000
const MAX_JSON_DEPTH = 12
const JSON_LIMITS = { string: 4_096, array: 100, object: 200 } as const
const JSON_LIMITS_TIGHT = { string: 256, array: 20, object: 50 } as const

type JsonLimits = { string: number; array: number; object: number }

function clampJson(value: unknown, limits: JsonLimits, depth: number): unknown {
if (typeof value === "string") return value.length > limits.string ? `${value.slice(0, limits.string)}…[truncated]` : value
if (Array.isArray(value)) {
const items = value.slice(0, limits.array).map((item) => clampJson(item, limits, depth + 1))
if (value.length > limits.array) items.push(`…[truncated ${value.length - limits.array} items]`)
return items
}
if (value !== null && typeof value === "object") {
if (depth >= MAX_JSON_DEPTH) return "…[truncated]"
const entries = Object.entries(value as Record<string, unknown>)
const clamped: Record<string, unknown> = {}
for (const [key, item] of entries.slice(0, limits.object)) clamped[key] = clampJson(item, limits, depth + 1)
if (entries.length > limits.object) clamped["…truncated_keys"] = entries.length - limits.object
return clamped
}
return value
}

function safeJson(value: unknown): string {
try {
return JSON.stringify(value) ?? ""
let text = JSON.stringify(value) ?? ""
if (text.length > MAX_JSON_CHARS) text = JSON.stringify(clampJson(value, JSON_LIMITS, 0)) ?? ""
if (text.length > MAX_JSON_CHARS) text = JSON.stringify(clampJson(value, JSON_LIMITS_TIGHT, 0)) ?? ""
if (text.length > MAX_JSON_CHARS) text = JSON.stringify({ "…truncated_input": true, preview: text.slice(0, MAX_JSON_CHARS - 200) })
return text
} catch {
return ""
}
Expand Down
1 change: 1 addition & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export async function setup(ctx: OpenCodeContext): Promise<() => Promise<void>>
disabledMetrics: config.disabledMetrics,
disabledTraces: config.disabledTraces,
combineReasoningTokens: config.combineReasoningTokens,
captureContent: config.captureContent,
tracer: shared.tracer,
tracePrefix: config.metricPrefix,
rootContext: remoteContext ? () => remoteContext : () => ROOT_CONTEXT,
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ export type HandlerContext = {
disabledMetrics: Set<string>
disabledTraces: Set<string>
combineReasoningTokens: boolean
captureContent: boolean
tracer: Tracer
tracePrefix: string
rootContext: () => Context
Expand Down
5 changes: 5 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ export function errorSummary(err: StructuredError | undefined): string {
return `${err.type}: ${err.message}`
}

export function redactErrorMessage(message: string): string {
const sep = message.indexOf(": ")
return sep >= 0 && sep <= 64 ? `${message.slice(0, sep)}: [redacted]` : "[redacted]"
}

/** Returns the canonical OTel GenAI provider name, preserving unknown provider IDs. */
export function genAiProviderName(providerID: string): string {
return GEN_AI_PROVIDER_NAMES[providerID] ?? providerID
Expand Down
Loading
Loading