Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): export OTLP traces (interaction/llm_request/tool spans, TRACEPARENT)

thinhlpg14ef59ff482c
diff --git a/docs/src/pages/docs/agent/telemetry.mdx b/docs/src/pages/docs/agent/telemetry.mdx
index ae785f0d2..0492fafa0 100644
--- a/docs/src/pages/docs/agent/telemetry.mdx
+++ b/docs/src/pages/docs/agent/telemetry.mdx
@@ -8,7 +8,7 @@ import { Callout } from 'nextra/components'
# Telemetry (OpenTelemetry)
-Jan Agent can export usage **metrics** and **events** over [OTLP](https://opentelemetry.io/docs/specs/otlp/)
+Jan Agent can export usage **metrics**, **events** and (opt-in) **traces** over [OTLP](https://opentelemetry.io/docs/specs/otlp/)
to a collector you run: an OpenTelemetry Collector, Grafana, Honeycomb, Datadog, or anything else
that accepts OTLP/HTTP. A team can then see its token usage, cost, tool calls and errors across
every machine and every session.
@@ -95,7 +95,11 @@ setup you already use for another agent works unchanged.
| `OTEL_LOGS_EXPORT_INTERVAL` | `5000` | How often events are exported, in ms. |
| `OTEL_METRICS_INCLUDE_SESSION_ID` | `true` | `false` keeps `session.id` off metric points, so the number of series stays small. Events keep it. |
| `OTEL_LOG_USER_PROMPTS` | off | Include the prompt text on `user_prompt`. |
-| `OTEL_LOG_TOOL_DETAILS` | off | Include tool arguments on `tool_result`. |
+| `OTEL_LOG_TOOL_DETAILS` | off | Include tool arguments on `tool_result` and the `tool` span. |
+| `OTEL_TRACES_EXPORTER` | off | `otlp` turns traces on. Unlike metrics and logs, traces stay off until you ask for them. |
+| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` / `_PROTOCOL` / `_HEADERS` | derived from the base | Same rules as the other signals; the default path is `/v1/traces`. |
+| `OTEL_TRACES_EXPORT_INTERVAL` | `5000` | How often spans are exported, in ms. |
+| `TRACEPARENT` | none | W3C trace context of a caller's span. The `interaction` span becomes its child. |
Everything is also exported when a run ends and when the process exits, with a 2-second limit on
that final export. A short `jan cli agent run` or an ADK session that ends right away still reports.
@@ -137,6 +141,59 @@ Events are OTLP log records with `event_name` set. Every event carries `session.
| `jan_agent.compaction` | `message_count` |
| `jan_agent.subagent_result` | `success` |
+## Traces
+
+Set `OTEL_TRACES_EXPORTER=otlp` to also export spans. Each user prompt is one trace, laid out like
+Claude Code's (`claude_code.*` becomes `jan_agent.*`):
+
+```text
+jan_agent.interaction one per prompt; child of TRACEPARENT when set
+├── jan_agent.llm_request one per model call (kind CLIENT)
+└── jan_agent.tool one per tool call
+```
+
+A subagent's model and tool spans sit under the same interaction and carry `agent_id` and
+`subagent.name`.
+
+| Span | Attributes |
+| --- | --- |
+| `interaction` | `session.id`, `prompt.id`, `user_prompt_length`, `user_prompt` (`<REDACTED>` unless `OTEL_LOG_USER_PROMPTS`), `interaction.sequence`, `interaction.duration_ms` |
+| `llm_request` | `model`, `provider`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_creation_tokens`, `duration_ms`, `success`, `gen_ai.operation.name=chat`, `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens` / `output_tokens` / `cache_read.input_tokens` / `cache_creation.input_tokens`. Status ERROR (redacted message) on failure. |
+| `tool` | `tool_name`, `tool_use_id`, `gen_ai.tool.call.id`, `gen_ai.tool.name`, `success`, `duration_ms`, `decision`, `decision_source`, `result_size_bytes`, `tool_parameters` (only with `OTEL_LOG_TOOL_DETAILS`). Status ERROR when the tool failed. |
+
+Every span also has `span.type`. Langfuse, Jaeger, Tempo, Honeycomb and other OTLP trace backends
+can read them directly. For Langfuse, point a collector's `otlphttp` exporter at
+`<LANGFUSE_BASE_URL>/api/public/otel` with Basic auth `base64(public_key:secret_key)`.
+
+### Compared with Claude Code
+
+| Claude Code | Jan |
+| --- | --- |
+| `claude_code.session.count`, `token.usage`, `cost.usage`, `active_time.total` | `jan_agent.*` with the same name |
+| `claude_code.code_edit_tool.decision` | `jan_agent.tool.count` (all tools, `decision` label) |
+| `user_prompt`, `api_request`, `api_error`, `tool_result`, `tool_decision` events | `jan_agent.*` with the same name |
+| `claude_code.interaction`, `llm_request`, `tool` spans | `jan_agent.*` with the same name |
+| `lines_of_code.count`, `pull_request.count`, `commit.count` | not emitted |
+| `tool.execution`, `tool.blocked_on_user`, `hook` spans | not emitted; timing is on `tool` |
+| `TRACEPARENT` into Bash subprocesses | not yet |
+
+The unit test `every_claude_code_signal_has_a_jan_equivalent_or_a_reason` (in
+`src-tauri/src/core/agent/otel/tests.rs`) fails if a mapped signal or attribute goes missing.
+
+### End-to-end check
+
+`scripts/otel-e2e.sh` runs the built `jan` against a real OpenTelemetry Collector in Docker and a
+fake OpenAI-compatible model (no API key needed), then checks the collector's output for every
+metric, event and span above, and that every span sits under its interaction:
+
+```bash
+cd src-tauri/jan-cli && cargo build --no-default-features --features cli && cd ../..
+scripts/otel-e2e.sh # fake model
+JAN_E2E_REAL_MODEL=1 scripts/otel-e2e.sh # your configured default model
+LANGFUSE_PUBLIC_KEY=... LANGFUSE_SECRET_KEY=... LANGFUSE_BASE_URL=https://cloud.langfuse.com \
+ scripts/otel-e2e.sh # also forward traces to Langfuse
+```
+
## Privacy defaults
- Off unless you turn it on, and sent only to your endpoint.
@@ -182,7 +239,8 @@ runtime = JanRuntime(env={
## Not yet
-- Traces (`interaction` / `llm_request` / `tool` spans) and an inbound `TRACEPARENT`
+- `TRACEPARENT` passed to shell commands, and `traceparent` on model requests
+- `tool.execution` / `tool.blocked_on_user` sub-spans
- gRPC transport
- Jan Desktop
- Admin-enforced (managed) settings
diff --git a/src-tauri/src/core/agent/otel/config.rs b/src-tauri/src/core/agent/otel/config.rs
index 46ea1fc24..12dab3c60 100644
--- a/src-tauri/src/core/agent/otel/config.rs
+++ b/src-tauri/src/core/agent/otel/config.rs
@@ -49,10 +49,17 @@ pub struct Target {
pub struct Config {
pub metrics: Option<Target>,
pub logs: Option<Target>,
+ /// Off unless `OTEL_TRACES_EXPORTER=otlp` asks for it: enabling telemetry
+ /// alone keeps sending what it always sent.
+ pub traces: Option<Target>,
+ /// W3C `TRACEPARENT` from the environment: `(trace_id, span_id)` of the
+ /// caller's span, so an embedding process sees our spans as its children.
+ pub parent: Option<([u8; 16], [u8; 8])>,
/// `service.name` and `OTEL_RESOURCE_ATTRIBUTES`, in order, service first.
pub resource: Vec<(String, String)>,
pub metric_interval: Duration,
pub logs_interval: Duration,
+ pub traces_interval: Duration,
pub export_timeout: Duration,
/// `OTEL_LOG_USER_PROMPTS`: include prompt text on `user_prompt`.
pub log_user_prompts: bool,
@@ -114,7 +121,10 @@ pub fn resolve(
let mut target = |signal: &str, path: &str| -> Option<Target> {
let upper = signal.to_ascii_uppercase();
- match get(&format!("OTEL_{upper}_EXPORTER")).as_deref() {
+ let exporter = get(&format!("OTEL_{upper}_EXPORTER"));
+ match exporter.as_deref() {
+ // Traces are opt-in on their own, as in Claude Code.
+ None if signal == "traces" => return None,
None | Some("otlp") => {}
Some("none") => return None,
// stdout is the protocol channel for RPC and stream-json, so a
@@ -162,7 +172,8 @@ pub fn resolve(
};
let metrics = target("metrics", "v1/metrics");
let logs = target("logs", "v1/logs");
- if metrics.is_none() && logs.is_none() {
+ let traces = target("traces", "v1/traces");
+ if metrics.is_none() && logs.is_none() && traces.is_none() {
return None;
}
@@ -191,9 +202,12 @@ pub fn resolve(
Some(Config {
metrics,
logs,
+ traces,
+ parent: get("TRACEPARENT").as_deref().and_then(parse_traceparent),
resource,
metric_interval: millis("OTEL_METRIC_EXPORT_INTERVAL", 60_000),
logs_interval: millis("OTEL_LOGS_EXPORT_INTERVAL", 5_000),
+ traces_interval: millis("OTEL_TRACES_EXPORT_INTERVAL", 5_000),
export_timeout: millis("OTEL_EXPORTER_OTLP_TIMEOUT", 10_000),
log_user_prompts: gate("OTEL_LOG_USER_PROMPTS"),
log_tool_details: gate("OTEL_LOG_TOOL_DETAILS"),
@@ -205,6 +219,20 @@ pub fn resolve(
})
}
+/// A W3C `traceparent` (`00-<32 hex>-<16 hex>-<2 hex>`). All-zero ids and
+/// the reserved version `ff` are invalid and ignored, as the spec requires.
+pub fn parse_traceparent(raw: &str) -> Option<([u8; 16], [u8; 8])> {
+ let parts: Vec<&str> = raw.trim().split('-').collect();
+ let [version, trace, span, flags, ..] = parts.as_slice() else { return None };
+ if version.len() != 2 || *version == "ff" || flags.len() != 2 || (*version == "00" && parts.len() != 4) {
+ return None;
+ }
+ let trace: [u8; 16] = hex::decode(trace).ok()?.try_into().ok()?;
+ let span: [u8; 8] = hex::decode(span).ok()?.try_into().ok()?;
+ hex::decode(flags).ok()?;
+ (trace != [0; 16] && span != [0; 8]).then_some((trace, span))
+}
+
/// `k=v,k2=v2` as the OTel spec writes headers and resource attributes, with
/// values percent-decoded. Malformed members are skipped, not fatal.
pub fn parse_pairs(raw: &str) -> Vec<(String, String)> {
@@ -376,6 +404,55 @@ mod tests {
.is_none());
}
+ #[test]
+ fn traces_are_opt_in_and_follow_the_signal_rules() {
+ let c = resolve(&env(&[(ENABLE_ENV, "1")]), None, None).unwrap();
+ assert!(c.traces.is_none(), "enabling telemetry alone sends no spans");
+ let c = resolve(
+ &env(&[
+ (ENABLE_ENV, "1"),
+ ("OTEL_TRACES_EXPORTER", "otlp"),
+ ("OTEL_METRICS_EXPORTER", "none"),
+ ("OTEL_LOGS_EXPORTER", "none"),
+ ("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL", "http/json"),
+ ("OTEL_TRACES_EXPORT_INTERVAL", "250"),
+ ]),
+ None,
+ None,
+ )
+ .expect("traces alone keep telemetry on");
+ let t = c.traces.unwrap();
+ assert_eq!(t.url, "http://localhost:4318/v1/traces");
+ assert_eq!(t.protocol, Protocol::HttpJson);
+ assert_eq!(c.traces_interval, Duration::from_millis(250));
+ let c = resolve(&env(&[(ENABLE_ENV, "1"), ("OTEL_TRACES_EXPORTER", "console")]), None, None)
+ .unwrap();
+ assert!(c.traces.is_none());
+ assert_eq!(c.warnings.len(), 1);
+ }
+
+ #[test]
+ fn traceparent_is_parsed_strictly() {
+ let good = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
+ let (trace, span) = parse_traceparent(good).unwrap();
+ assert_eq!(hex::encode(trace), "4bf92f3577b34da6a3ce929d0e0e4736");
+ assert_eq!(hex::encode(span), "00f067aa0ba902b7");
+ for bad in [
+ "",
+ "garbage",
+ "00-00000000000000000000000000000000-00f067aa0ba902b7-01",
+ "00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-01",
+ "ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
+ "00-4bf92f3577b34da6a3ce929d0e0e473-00f067aa0ba902b7-01",
+ "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-extra",
+ "00-zzf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
+ ] {
+ assert_eq!(parse_traceparent(bad), None, "{bad}");
+ }
+ let c = resolve(&env(&[(ENABLE_ENV, "1"), ("TRACEPARENT", good)]), None, None).unwrap();
+ assert_eq!(c.parent.map(|(t, _)| hex::encode(t)).as_deref(), Some("4bf92f3577b34da6a3ce929d0e0e4736"));
+ }
+
#[test]
fn pairs_skip_malformed_members_and_decode_values() {
assert_eq!(
diff --git a/src-tauri/src/core/agent/otel/encode.rs b/src-tauri/src/core/agent/otel/encode.rs
index 9c43bf1de..87dea70e4 100644
--- a/src-tauri/src/core/agent/otel/encode.rs
+++ b/src-tauri/src/core/agent/otel/encode.rs
@@ -1,5 +1,5 @@
-//! OTLP wire encoding for the two signals this exporter sends: cumulative
-//! monotonic sums (metrics) and event log records (logs).
+//! OTLP wire encoding for the three signals this exporter sends: cumulative
+//! monotonic sums (metrics), event log records (logs) and spans (traces).
//!
//! Hand-rolled rather than generated: the subset is small and stable (OTLP v1
//! is frozen for these messages), and carrying `prost` + the generated proto
@@ -59,6 +59,25 @@ pub struct LogRecord {
pub attrs: Attrs,
}
+/// OTLP `Span.SpanKind`: 1 = INTERNAL, 3 = CLIENT.
+pub const SPAN_KIND_INTERNAL: u32 = 1;
+pub const SPAN_KIND_CLIENT: u32 = 3;
+
+/// One finished span.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Span {
+ pub trace_id: [u8; 16],
+ pub span_id: [u8; 8],
+ pub parent_span_id: Option<[u8; 8]>,
+ pub name: String,
+ pub kind: u32,
+ pub start_unix_nano: u64,
+ pub end_unix_nano: u64,
+ pub attrs: Attrs,
+ /// `Some(message)` sets status ERROR; `None` leaves it UNSET.
+ pub error: Option<String>,
+}
+
/// Who produced the batch: resource attributes plus the instrumentation scope.
#[derive(Debug, Clone, PartialEq)]
pub struct Origin {
@@ -158,6 +177,41 @@ pub fn logs_json(origin: &Origin, records: &[LogRecord]) -> Vec<u8> {
.unwrap_or_default()
}
+/// OTLP/JSON writes trace and span ids as lowercase hex, not base64.
+pub fn spans_json(origin: &Origin, spans: &[Span]) -> Vec<u8> {
+ let (resource, scope) = origin_json(origin);
+ let spans: Vec<Value> = spans
+ .iter()
+ .map(|s| {
+ let mut span = json!({
+ "traceId": hex::encode(s.trace_id),
+ "spanId": hex::encode(s.span_id),
+ "name": s.name,
+ "kind": s.kind,
+ "startTimeUnixNano": s.start_unix_nano.to_string(),
+ "endTimeUnixNano": s.end_unix_nano.to_string(),
+ "attributes": attrs_json(&s.attrs),
+ // 2 = STATUS_CODE_ERROR, 0 = UNSET
+ "status": match &s.error {
+ Some(m) => json!({ "code": 2, "message": m }),
+ None => json!({}),
+ },
+ });
+ if let Some(parent) = s.parent_span_id {
+ span["parentSpanId"] = json!(hex::encode(parent));
+ }
+ span
+ })
+ .collect();
+ serde_json::to_vec(&json!({
+ "resourceSpans": [{
+ "resource": resource,
+ "scopeSpans": [{ "scope": scope, "spans": spans }],
+ }]
+ }))
+ .unwrap_or_default()
+}
+
// ── OTLP/protobuf ────────────────────────────────────────────────────────────
const VARINT: u64 = 0;
@@ -298,6 +352,44 @@ pub fn logs_proto(origin: &Origin, records: &[LogRecord]) -> Vec<u8> {
request
}
+/// `ExportTraceServiceRequest { resource_spans = 1 }` ->
+/// `ResourceSpans { resource = 1; scope_spans = 2 }` ->
+/// `ScopeSpans { scope = 1; spans = 2 }` ->
+/// `Span { trace_id = 1; span_id = 2; parent_span_id = 4; name = 5; kind = 6;
+/// start = 7; end = 8; attributes = 9; status = 15 }` ->
+/// `Status { message = 2; code = 3 }`.
+pub fn spans_proto(origin: &Origin, spans: &[Span]) -> Vec<u8> {
+ let (resource, scope) = origin_pb(origin);
+ let mut scope_spans = Vec::new();
+ pb_bytes(&mut scope_spans, 1, &scope);
+ for s in spans {
+ let mut span = Vec::new();
+ pb_bytes(&mut span, 1, &s.trace_id);
+ pb_bytes(&mut span, 2, &s.span_id);
+ if let Some(parent) = s.parent_span_id {
+ pb_bytes(&mut span, 4, &parent);
+ }
+ pb_str(&mut span, 5, &s.name);
+ pb_varint(&mut span, 6, s.kind as u64);
+ pb_fixed64(&mut span, 7, s.start_unix_nano);
+ pb_fixed64(&mut span, 8, s.end_unix_nano);
+ attrs_pb(&mut span, 9, &s.attrs);
+ if let Some(message) = &s.error {
+ let mut status = Vec::new();
+ pb_str(&mut status, 2, message);
+ pb_varint(&mut status, 3, 2);
+ pb_bytes(&mut span, 15, &status);
+ }
+ pb_bytes(&mut scope_spans, 2, &span);
+ }
+ let mut resource_spans = Vec::new();
+ pb_bytes(&mut resource_spans, 1, &resource);
+ pb_bytes(&mut resource_spans, 2, &scope_spans);
+ let mut request = Vec::new();
+ pb_bytes(&mut request, 1, &resource_spans);
+ request
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -443,4 +535,57 @@ mod tests {
assert_eq!(record["severityNumber"], 17);
assert_eq!(record["attributes"][0]["value"]["boolValue"], false);
}
+
+ fn span(error: Option<&str>, parent: Option<[u8; 8]>) -> Span {
+ Span {
+ trace_id: [0xab; 16],
+ span_id: [0xcd; 8],
+ parent_span_id: parent,
+ name: "jan_agent.llm_request".into(),
+ kind: SPAN_KIND_CLIENT,
+ start_unix_nano: 10,
+ end_unix_nano: 20,
+ attrs: vec![("gen_ai.request.model".into(), AnyValue::Str("m".into()))],
+ error: error.map(str::to_string),
+ }
+ }
+
+ #[test]
+ fn spans_protobuf_carries_ids_times_and_status() {
+ let bytes = spans_proto(&origin(), &[span(Some("boom"), Some([0xef; 8]))]);
+ let scope_spans = only(&only(&bytes, 1), 2);
+ let s = only(&scope_spans, 2);
+ assert_eq!(only(&s, 1), vec![0xab; 16]);
+ assert_eq!(only(&s, 2), vec![0xcd; 8]);
+ assert_eq!(only(&s, 4), vec![0xef; 8]);
+ assert_eq!(only(&s, 5), b"jan_agent.llm_request");
+ assert_eq!(only(&s, 6)[0], SPAN_KIND_CLIENT as u8);
+ assert_eq!(u64::from_le_bytes(only(&s, 7).try_into().unwrap()), 10);
+ assert_eq!(u64::from_le_bytes(only(&s, 8).try_into().unwrap()), 20);
+ let kv = only(&s, 9);
+ assert_eq!(only(&kv, 1), b"gen_ai.request.model");
+ let status = only(&s, 15);
+ assert_eq!(only(&status, 2), b"boom");
+ assert_eq!(only(&status, 3)[0], 2, "STATUS_CODE_ERROR");
+ }
+
+ #[test]
+ fn a_root_span_has_no_parent_and_an_ok_span_no_status() {
+ let bytes = spans_proto(&origin(), &[span(None, None)]);
+ let s = only(&only(&only(&bytes, 1), 2), 2);
+ assert!(fields(&s).iter().all(|f| f.0 != 4 && f.0 != 15));
+ }
+
+ #[test]
+ fn spans_json_writes_ids_as_hex() {
+ let v: Value =
+ serde_json::from_slice(&spans_json(&origin(), &[span(Some("x"), Some([1; 8]))])).unwrap();
+ let s = &v["resourceSpans"][0]["scopeSpans"][0]["spans"][0];
+ assert_eq!(s["traceId"], "ab".repeat(16));
+ assert_eq!(s["spanId"], "cd".repeat(8));
+ assert_eq!(s["parentSpanId"], "01".repeat(8));
+ assert_eq!(s["startTimeUnixNano"], "10");
+ assert_eq!(s["status"]["code"], 2);
+ assert_eq!(s["kind"], 3);
+ }
}
diff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rs
index 7acc2d678..db778b55e 100644
--- a/src-tauri/src/core/agent/otel/mod.rs
+++ b/src-tauri/src/core/agent/otel/mod.rs
@@ -1,5 +1,5 @@
-//! Opt-in OpenTelemetry export of the agent's usage: metrics and event logs over
-//! OTLP/HTTP, to a collector the user names (janhq/jan-internal#393).
+//! Opt-in OpenTelemetry export of the agent's usage: metrics, event logs and
+//! (separately opted into) traces over OTLP/HTTP, to a collector the user names (janhq/jan-internal#393).
//!
//! Off by default: nothing here runs, and no request is made, unless
//! [`config::enabled`] says so. This is separate from Jan's own update-check
@@ -40,7 +40,7 @@ use tokio::sync::{mpsc, oneshot};
use crate::core::agent::events::{StreamEvent, Usage};
use crate::core::agent::session::TokenRates;
use config::{Config, Target};
-use encode::{AnyValue, Attrs, LogRecord, Metric, Origin, Point, PointValue};
+use encode::{AnyValue, Attrs, LogRecord, Metric, Origin, Point, PointValue, Span};
/// Signals that can wait for the worker. Generous: a busy turn emits a few
/// dozen, and the worker drains continuously.
@@ -49,6 +49,8 @@ pub const QUEUE_CAPACITY: usize = 4096;
pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
/// Logs buffered before an early export, whatever the interval.
const LOG_BATCH: usize = 512;
+/// Spans buffered before an early export, whatever the interval.
+const SPAN_BATCH: usize = 512;
/// Cap on a gated free-text attribute (prompt text, tool arguments).
const CONTENT_CAP: usize = 4096;
/// Cap on an error message carried by `api_error`.
@@ -493,6 +495,7 @@ type SeriesKey = (&'static str, Vec<(String, String)>);
#[derive(Debug)]
struct PendingRequest {
at: Instant,
+ wall: u64,
model: String,
provider: Option<String>,
body_bytes: u64,
@@ -501,10 +504,34 @@ struct PendingRequest {
#[derive(Debug)]
struct PendingTool {
at: Instant,
+ wall: u64,
name: String,
args: Option<String>,
}
+/// The span a top-level run is recorded under, open until its `RunEnd`.
+#[derive(Debug, Clone)]
+struct Interaction {
+ trace_id: [u8; 16],
+ span_id: [u8; 8],
+ start: u64,
+ sequence: u64,
+ prompt: Option<(usize, Option<String>)>,
+}
+
+fn random_ids() -> ([u8; 16], [u8; 8]) {
+ use rand::Rng;
+ let mut rng = rand::thread_rng();
+ // All-zero ids are invalid in W3C trace context; a 2^-64 retry is cheap.
+ loop {
+ let trace: [u8; 16] = rng.gen();
+ let span: [u8; 8] = rng.gen();
+ if trace != [0; 16] && span != [0; 8] {
+ return (trace, span);
+ }
+ }
+}
+
/// Everything the worker folds signals into. Pure: no I/O, so the mapping from
/// events to metrics and logs is testable without a collector.
pub struct State {
@@ -525,6 +552,36 @@ pub struct State {
/// so overlapping RPC sessions never tag each other's records.
prompt_ids: HashMap<String, String>,
main_session: Option<String>,
+ /// Open interaction span per session key (`""` = no session id). Only
+ /// populated when traces are exported.
+ interactions: HashMap<String, Interaction>,
+ interaction_seq: HashMap<String, u64>,
+ spans: Vec<Span>,
+}
+
+/// `llm_request` span attributes from the `api_request` event's fields, plus
+/// the OpenTelemetry GenAI semantic-convention names for the same values.
+fn llm_attrs(fields: &[(String, AnyValue)]) -> Attrs {
+ let mut attrs: Attrs = fields.iter().filter(|(k, _)| k != "input_tokens").cloned().collect();
+ let get = |key: &str| fields.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone());
+ attrs.push(("gen_ai.operation.name".into(), AnyValue::Str("chat".into())));
+ if let Some(model) = get("model") {
+ attrs.push(("gen_ai.request.model".into(), model));
+ }
+ if let Some(AnyValue::Str(p)) = get("provider") {
+ if !p.is_empty() {
+ attrs.push(("gen_ai.system".into(), AnyValue::Str(p.clone())));
+ attrs.push(("gen_ai.provider.name".into(), AnyValue::Str(p)));
+ }
+ }
+ if let Some(v) = get("cache_read_tokens") {
+ attrs.push(("gen_ai.usage.cache_read.input_tokens".into(), v));
+ }
+ if let Some(v) = get("cache_write_tokens") {
+ attrs.push(("cache_creation_tokens".into(), v.clone()));
+ attrs.push(("gen_ai.usage.cache_creation.input_tokens".into(), v));
+ }
+ attrs
}
fn metric_attr(key: &str, value: impl Into<String>) -> (String, String) {
@@ -546,6 +603,9 @@ impl State {
prompted: HashMap::new(),
prompt_ids: HashMap::new(),
main_session: None,
+ interactions: HashMap::new(),
+ interaction_seq: HashMap::new(),
+ spans: Vec::new(),
}
}
@@ -603,9 +663,121 @@ impl State {
});
}
+ fn tracing(&self) -> bool {
+ self.cfg.traces.is_some()
+ }
+
+ /// Record a finished span under the session's open interaction, or as a
+ /// root of its own trace (under `TRACEPARENT`, when set) if none is open.
+ #[allow(clippy::too_many_arguments)]
+ fn span(
+ &mut self,
+ name: &str,
+ kind: u32,
+ session: Option<&str>,
+ child: Option<&Child>,
+ start: u64,
+ end: u64,
+ error: Option<String>,
+ mut attrs: Attrs,
+ ) {
+ if !self.tracing() {
+ return;
+ }
+ let key = session.unwrap_or("").to_string();
+ let (trace_id, parent) = match self.interactions.get(&key) {
+ Some(i) => (i.trace_id, Some(i.span_id)),
+ None => match self.cfg.parent {
+ Some((trace, span)) => (trace, Some(span)),
+ None => (random_ids().0, None),
+ },
+ };
+ let mut all: Attrs = vec![(
+ "span.type".into(),
+ AnyValue::Str(name.trim_start_matches("jan_agent.").to_string()),
+ )];
+ if let Some(s) = session {
+ all.push(("session.id".into(), AnyValue::Str(s.to_string())));
+ }
+ if let Some(p) = self.prompt_ids.get(&key) {
+ all.push(("prompt.id".into(), AnyValue::Str(p.clone())));
+ }
+ if let Some(c) = child {
+ all.push(("agent_id".into(), AnyValue::Str(c.run_id.clone())));
+ all.push(("subagent.name".into(), AnyValue::Str(c.name.clone())));
+ }
+ all.append(&mut attrs);
+ self.spans.push(Span {
+ trace_id,
+ span_id: random_ids().1,
+ parent_span_id: parent,
+ name: name.to_string(),
+ kind,
+ start_unix_nano: start,
+ end_unix_nano: end.max(start),
+ attrs: all,
+ error,
+ });
+ }
+
+ /// Close the session's interaction span, if one is open.
+ fn end_interaction(&mut self, session: Option<&str>, wall: u64) {
+ let key = session.unwrap_or("").to_string();
+ let Some(i) = self.interactions.remove(&key) else { return };
+ let mut attrs: Attrs = vec![("span.type".into(), AnyValue::Str("interaction".into()))];
+ if let Some(s) = session {
+ attrs.push(("session.id".into(), AnyValue::Str(s.to_string())));
+ }
+ if let Some(p) = self.prompt_ids.get(&key) {
+ attrs.push(("prompt.id".into(), AnyValue::Str(p.clone())));
+ }
+ if let Some((length, text)) = i.prompt {
+ attrs.push(("user_prompt_length".into(), AnyValue::Int(length as i64)));
+ // Claude Code writes a placeholder when the gate is off.
+ attrs.push(("user_prompt".into(), AnyValue::Str(text.unwrap_or_else(|| "<REDACTED>".into()))));
+ }
+ attrs.push(("interaction.sequence".into(), AnyValue::Int(i.sequence as i64)));
+ attrs.push((
+ "interaction.duration_ms".into(),
+ AnyValue::Int((wall.saturating_sub(i.start) / 1_000_000) as i64),
+ ));
+ self.spans.push(Span {
+ trace_id: i.trace_id,
+ span_id: i.span_id,
+ parent_span_id: self.cfg.parent.map(|(_, span)| span),
+ name: "jan_agent.interaction".into(),
+ kind: encode::SPAN_KIND_INTERNAL,
+ start_unix_nano: i.start,
+ end_unix_nano: wall.max(i.start),
+ attrs,
+ error: None,
+ });
+ }
+
+ pub fn take_spans(&mut self) -> Vec<Span> {
+ std::mem::take(&mut self.spans)
+ }
+
+ pub fn pending_spans(&self) -> usize {
+ self.spans.len()
+ }
+
pub fn apply(&mut self, at: Instant, wall: u64, signal: Signal) {
match signal {
Signal::RunStart { session, run_id, prompt } => {
+ if run_id.is_none() && self.tracing() {
+ let key = session.clone().unwrap_or_default();
+ let seq = self.interaction_seq.entry(key.clone()).or_insert(0);
+ *seq += 1;
+ let (trace_id, span_id) = match self.cfg.parent {
+ Some((trace, _)) => (trace, random_ids().1),
+ None => random_ids(),
+ };
+ self.interactions.insert(
+ key,
+ Interaction { trace_id, span_id, start: wall, sequence: *seq, prompt: prompt.clone() },
+ );
+ }
if run_id.is_none() {
self.main_session = session.clone();
if let Some(s) = &session {
@@ -636,6 +808,7 @@ impl State {
if run_id.is_none() {
let attrs = self.session_attr(session.as_deref());
self.add("jan_agent.active_time.total", attrs, elapsed.as_secs_f64());
+ self.end_interaction(session.as_deref(), wall);
}
}
Signal::Compaction { message_count } => {
@@ -663,7 +836,7 @@ impl State {
if let Some(s) = session {
self.run_session.insert(run.clone(), s);
}
- self.requests.insert(run, PendingRequest { at, model, provider, body_bytes });
+ self.requests.insert(run, PendingRequest { at, wall, model, provider, body_bytes });
}
EventSignal::Usage { tokens, execution_id } => {
let session = self.session_of(&run);
@@ -724,6 +897,24 @@ impl State {
if let Some(id) = execution_id {
fields.push(("execution_id".into(), AnyValue::Str(id)));
}
+ if self.tracing() {
+ let mut attrs = llm_attrs(&fields);
+ attrs.push(("input_tokens".into(), AnyValue::Int(input as i64)));
+ attrs.push(("gen_ai.usage.input_tokens".into(), AnyValue::Int(prompt as i64)));
+ attrs.push(("gen_ai.usage.output_tokens".into(), AnyValue::Int(output as i64)));
+ attrs.push(("success".into(), AnyValue::Bool(true)));
+ let start = request.as_ref().map_or(wall, |r| r.wall);
+ self.span(
+ "jan_agent.llm_request",
+ encode::SPAN_KIND_CLIENT,
+ session.as_deref(),
+ child.as_ref(),
+ start,
+ wall,
+ None,
+ attrs,
+ );
+ }
self.log(wall, "jan_agent.api_request", false, session.as_deref(), child.as_ref(), fields);
}
EventSignal::Step => {
@@ -732,14 +923,14 @@ impl State {
self.add("jan_agent.turn.count", attrs, 1.0);
}
EventSignal::ToolCall { id, name, args } => {
- self.tools.insert((run, id), PendingTool { at, name, args });
+ self.tools.insert((run, id), PendingTool { at, wall, name, args });
}
EventSignal::Permission { tool_name } => {
self.prompted.entry(run).or_default().push(tool_name);
}
EventSignal::ToolResult { id, is_error, refusal, bytes } => {
let session = self.session_of(&run);
- let Some(tool) = self.tools.remove(&(run.clone(), id)) else {
+ let Some(tool) = self.tools.remove(&(run.clone(), id.clone())) else {
return;
};
let prompted = self
@@ -774,7 +965,7 @@ impl State {
],
);
let mut fields: Attrs = vec![
- ("tool_name".into(), AnyValue::Str(tool.name)),
+ ("tool_name".into(), AnyValue::Str(tool.name.clone())),
("success".into(), AnyValue::Bool(success)),
(
"duration_ms".into(),
@@ -787,11 +978,49 @@ impl State {
if let Some(args) = tool.args {
fields.push(("tool_parameters".into(), AnyValue::Str(args)));
}
+ if self.tracing() {
+ let mut attrs = fields.clone();
+ attrs.push(("tool_use_id".into(), AnyValue::Str(id.clone())));
+ attrs.push(("gen_ai.tool.call.id".into(), AnyValue::Str(id.clone())));
+ attrs.push(("gen_ai.tool.name".into(), AnyValue::Str(tool.name.clone())));
+ attrs.push(("gen_ai.operation.name".into(), AnyValue::Str("execute_tool".into())));
+ self.span(
+ "jan_agent.tool",
+ encode::SPAN_KIND_INTERNAL,
+ session.as_deref(),
+ child.as_ref(),
+ tool.wall,
+ wall,
+ (!success).then(|| "tool failed".to_string()),
+ attrs,
+ );
+ }
self.log(wall, "jan_agent.tool_result", !success, session.as_deref(), child.as_ref(), fields);
}
EventSignal::Error { code, message } => {
let session = self.session_of(&run);
let request = self.requests.remove(&run);
+ if let Some(r) = &request {
+ if self.tracing() {
+ let mut attrs = llm_attrs(&[
+ ("model".into(), AnyValue::Str(r.model.clone())),
+ ("provider".into(), AnyValue::Str(r.provider.clone().unwrap_or_default())),
+ ]);
+ attrs.push(("success".into(), AnyValue::Bool(false)));
+ attrs.push(("error.type".into(), AnyValue::Str(code.clone())));
+ attrs.push(("error".into(), AnyValue::Str(message.clone())));
+ self.span(
+ "jan_agent.llm_request",
+ encode::SPAN_KIND_CLIENT,
+ session.as_deref(),
+ child.as_ref(),
+ r.wall,
+ wall,
+ Some(message.clone()),
+ attrs,
+ );
+ }
+ }
let mut fields: Attrs = vec![
("code".into(), AnyValue::Str(code)),
("error".into(), AnyValue::Str(message)),
@@ -935,9 +1164,11 @@ impl Worker {
) {
let mut metric_tick = tokio::time::interval(self.cfg.metric_interval);
let mut logs_tick = tokio::time::interval(self.cfg.logs_interval);
+ let mut traces_tick = tokio::time::interval(self.cfg.traces_interval);
// The first tick of an interval fires at once; skip it.
metric_tick.tick().await;
logs_tick.tick().await;
+ traces_tick.tick().await;
loop {
tokio::select! {
biased;
@@ -952,10 +1183,13 @@ impl Worker {
self.export_all().await;
} else if self.state.pending_logs() >= LOG_BATCH {
self.export_logs().await;
+ } else if self.state.pending_spans() >= SPAN_BATCH {
+ self.export_traces().await;
}
}
_ = metric_tick.tick() => self.export_metrics().await,
_ = logs_tick.tick() => self.export_logs().await,
+ _ = traces_tick.tick() => self.export_traces().await,
}
}
// Whatever the agent already queued is part of the run being reported.
@@ -969,6 +1203,7 @@ impl Worker {
}
async fn export_all(&mut self) {
+ self.export_traces().await;
self.export_logs().await;
self.export_metrics().await;
}
@@ -1006,6 +1241,19 @@ impl Worker {
self.post(&target, body, "logs").await;
}
+ async fn export_traces(&mut self) {
+ let spans = self.state.take_spans();
+ let Some(target) = self.cfg.traces.clone() else { return };
+ if spans.is_empty() {
+ return;
+ }
+ let body = target.protocol.encode(
+ || encode::spans_json(&self.origin, &spans),
+ || encode::spans_proto(&self.origin, &spans),
+ );
+ self.post(&target, body, "traces").await;
+ }
+
/// One POST. Failures are the collector's problem, not the run's: logged
/// at debug (never the URL's headers) and otherwise ignored.
async fn post(&self, target: &Target, body: Vec<u8>, signal: &str) {
diff --git a/src-tauri/src/core/agent/otel/tests.rs b/src-tauri/src/core/agent/otel/tests.rs
index f14ca1a5a..03974624e 100644
--- a/src-tauri/src/core/agent/otel/tests.rs
+++ b/src-tauri/src/core/agent/otel/tests.rs
@@ -585,3 +585,327 @@ fn api_error_messages_are_redacted() {
assert!(!message.contains("supersecret99"), "{message}");
assert!(message.contains("401: invalid key"), "{message}");
}
+
+// ── Traces ───────────────────────────────────────────────────────────────────
+
+fn cfg_traced(extra: &[(&'static str, &'static str)]) -> Config {
+ let extra: Vec<(&str, &str)> = extra.to_vec();
+ let env = move |key: &str| {
+ if key == config::ENABLE_ENV || key == "OTEL_TRACES_EXPORTER" {
+ return Some(if key == config::ENABLE_ENV { "1" } else { "otlp" }.to_string());
+ }
+ extra.iter().find(|(k, _)| *k == key).map(|(_, v)| v.to_string())
+ };
+ config::resolve(&env, None, None).unwrap()
+}
+
+fn tool_call(id: &str, name: &str) -> StreamEvent {
+ StreamEvent::ToolCall { id: id.into(), name: name.into(), args: json!({"command": "echo hi"}) }
+}
+
+fn tool_result(id: &str, is_error: bool) -> StreamEvent {
+ StreamEvent::ToolResult { id: id.into(), content: "hi".into(), is_error, diff: None }
+}
+
+/// One whole turn: prompt, a request that calls a tool, the tool, a final
+/// request, and the run's end.
+fn traced_turn(cfg: Config) -> State {
+ let mut state = fold(
+ cfg,
+ None,
+ &[
+ provenance(None, "sess-1"),
+ StreamEvent::Step { index: 1, max: 0 },
+ usage(100, 10, 40, 5),
+ tool_call("call-1", "bash"),
+ tool_result("call-1", false),
+ provenance(None, "sess-1"),
+ usage(120, 5, 100, 0),
+ ],
+ );
+ state.apply(
+ Instant::now(),
+ 9,
+ Signal::RunEnd { session: Some("sess-1".into()), run_id: None, elapsed: Duration::from_secs(1) },
+ );
+ state
+}
+
+fn span_attr<'a>(span: &'a Span, key: &str) -> Option<&'a AnyValue> {
+ span.attrs.iter().find(|(k, _)| k == key).map(|(_, v)| v)
+}
+
+#[test]
+fn traces_are_off_unless_asked_for() {
+ let mut state = traced_turn(cfg_with(true, true));
+ assert!(state.take_spans().is_empty(), "metrics/logs opt-in must not produce spans");
+}
+
+#[test]
+fn a_turn_is_one_trace_rooted_at_its_interaction() {
+ let spans = traced_turn(cfg_traced(&[])).take_spans();
+ let names: Vec<&str> = spans.iter().map(|s| s.name.as_str()).collect();
+ assert_eq!(
+ names,
+ vec!["jan_agent.llm_request", "jan_agent.tool", "jan_agent.llm_request", "jan_agent.interaction"]
+ );
+ let root = spans.last().unwrap();
+ assert_eq!(root.parent_span_id, None, "no TRACEPARENT: the interaction is the root");
+ for child in &spans[..3] {
+ assert_eq!(child.trace_id, root.trace_id);
+ assert_eq!(child.parent_span_id, Some(root.span_id), "{}", child.name);
+ assert_eq!(span_attr(child, "prompt.id"), span_attr(root, "prompt.id"));
+ }
+ let ids: HashSet<[u8; 8]> = spans.iter().map(|s| s.span_id).collect();
+ assert_eq!(ids.len(), spans.len(), "span ids are unique");
+ assert!(spans.iter().all(|s| s.end_unix_nano >= s.start_unix_nano));
+}
+
+#[test]
+fn llm_request_spans_carry_genai_usage() {
+ let spans = traced_turn(cfg_traced(&[])).take_spans();
+ let llm = &spans[0];
+ assert_eq!(llm.kind, encode::SPAN_KIND_CLIENT);
+ assert_eq!(span_attr(llm, "gen_ai.operation.name"), Some(&AnyValue::Str("chat".into())));
+ assert_eq!(span_attr(llm, "gen_ai.request.model"), Some(&AnyValue::Str("stub-model".into())));
+ assert_eq!(span_attr(llm, "gen_ai.system"), Some(&AnyValue::Str("stub".into())));
+ // Of 100 prompt tokens, 40 were cache reads and 5 cache writes.
+ assert_eq!(span_attr(llm, "input_tokens"), Some(&AnyValue::Int(55)));
+ assert_eq!(span_attr(llm, "gen_ai.usage.input_tokens"), Some(&AnyValue::Int(100)));
+ assert_eq!(span_attr(llm, "gen_ai.usage.output_tokens"), Some(&AnyValue::Int(10)));
+ assert_eq!(span_attr(llm, "cache_read_tokens"), Some(&AnyValue::Int(40)));
+ assert_eq!(span_attr(llm, "cache_creation_tokens"), Some(&AnyValue::Int(5)));
+ assert_eq!(llm.error, None);
+}
+
+#[test]
+fn tool_spans_join_to_the_call_and_record_failure() {
+ let mut state = fold(
+ cfg_traced(&[]),
+ None,
+ &[tool_call("call-9", "bash"), tool_result("call-9", true)],
+ );
+ let spans = state.take_spans();
+ let tool = spans.iter().find(|s| s.name == "jan_agent.tool").unwrap();
+ assert_eq!(span_attr(tool, "tool_use_id"), Some(&AnyValue::Str("call-9".into())));
+ assert_eq!(span_attr(tool, "gen_ai.tool.call.id"), Some(&AnyValue::Str("call-9".into())));
+ assert_eq!(span_attr(tool, "tool_name"), Some(&AnyValue::Str("bash".into())));
+ assert_eq!(span_attr(tool, "success"), Some(&AnyValue::Bool(false)));
+ assert!(tool.error.is_some(), "a failed tool sets status ERROR");
+}
+
+#[test]
+fn span_content_is_gated() {
+ let spans = traced_turn(cfg_traced(&[])).take_spans();
+ let root = spans.last().unwrap();
+ assert_eq!(span_attr(root, "user_prompt"), Some(&AnyValue::Str("<REDACTED>".into())));
+ assert_eq!(span_attr(root, "user_prompt_length"), Some(&AnyValue::Int(11)));
+ let tool = spans.iter().find(|s| s.name == "jan_agent.tool").unwrap();
+ assert_eq!(span_attr(tool, "tool_parameters"), None);
+
+ let spans = traced_turn(cfg_traced(&[("OTEL_LOG_USER_PROMPTS", "1"), ("OTEL_LOG_TOOL_DETAILS", "1")]))
+ .take_spans();
+ let root = spans.last().unwrap();
+ assert_eq!(span_attr(root, "user_prompt"), Some(&AnyValue::Str("secret plan".into())));
+ let tool = spans.iter().find(|s| s.name == "jan_agent.tool").unwrap();
+ assert!(matches!(span_attr(tool, "tool_parameters"), Some(AnyValue::Str(a)) if a.contains("echo hi")));
+}
+
+#[test]
+fn traceparent_makes_the_interaction_a_child_of_the_caller() {
+ let spans = traced_turn(cfg_traced(&[(
+ "TRACEPARENT",
+ "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
+ )]))
+ .take_spans();
+ let root = spans.last().unwrap();
+ assert_eq!(hex::encode(root.trace_id), "4bf92f3577b34da6a3ce929d0e0e4736");
+ assert_eq!(root.parent_span_id.map(hex::encode).as_deref(), Some("00f067aa0ba902b7"));
+ assert!(spans.iter().all(|s| s.trace_id == root.trace_id));
+}
+
+#[test]
+fn a_failed_request_is_an_error_span() {
+ let mut state = fold(
+ cfg_traced(&[]),
+ None,
+ &[
+ provenance(None, "sess-1"),
+ StreamEvent::Error { code: "upstream".into(), message: "429 key sk-abcdefghijklmnop1234".into() },
+ ],
+ );
+ let spans = state.take_spans();
+ let llm = spans.iter().find(|s| s.name == "jan_agent.llm_request").unwrap();
+ let message = llm.error.as_deref().unwrap();
+ assert!(message.contains("429") && !message.contains("sk-abcdefghijklmnop1234"), "{message}");
+ assert_eq!(span_attr(llm, "success"), Some(&AnyValue::Bool(false)));
+}
+
+#[test]
+fn subagent_spans_nest_under_the_parents_interaction() {
+ let mut state = fold(
+ cfg_traced(&[]),
+ None,
+ &[StreamEvent::Subagent {
+ run_id: "r1".into(),
+ name: "explore".into(),
+ event: Box::new(provenance(Some("r1"), "sess-1")),
+ }],
+ );
+ let usage_event = StreamEvent::Subagent {
+ run_id: "r1".into(),
+ name: "explore".into(),
+ event: Box::new(usage(1, 1, 0, 0)),
+ };
+ let cfg = cfg_traced(&[]);
+ if let Some(sig) = classify(&cfg, &usage_event, None) {
+ state.apply(Instant::now(), 3, sig);
+ }
+ state.apply(
+ Instant::now(),
+ 9,
+ Signal::RunEnd { session: Some("sess-1".into()), run_id: None, elapsed: Duration::from_secs(1) },
+ );
+ let spans = state.take_spans();
+ let root = spans.iter().find(|s| s.name == "jan_agent.interaction").unwrap();
+ let llm = spans.iter().find(|s| s.name == "jan_agent.llm_request").unwrap();
+ assert_eq!(llm.parent_span_id, Some(root.span_id));
+ assert_eq!(span_attr(llm, "agent_id"), Some(&AnyValue::Str("r1".into())));
+}
+
+#[tokio::test]
+async fn a_traced_run_posts_spans_to_v1_traces() {
+ for protocol in ["http/json", "http/protobuf"] {
+ let (url, seen) = collector(false).await;
+ let mut cfg = cfg_for(&url, protocol);
+ let base = cfg.metrics.clone().unwrap();
+ cfg.traces = Some(config::Target { url: format!("{url}/v1/traces"), ..base });
+ let t = Telemetry::start(cfg, None, "0.0.0-test");
+ scripted_run(&t);
+ t.shutdown(Duration::from_secs(5)).await;
+ let seen = seen.lock().unwrap().clone();
+ let (_, body) = seen.iter().find(|(p, _)| p == "/v1/traces").unwrap_or_else(|| panic!("{protocol}: no traces POST"));
+ if protocol == "http/json" {
+ let v: Value = serde_json::from_slice(body).unwrap();
+ let names: Vec<&str> = v["resourceSpans"][0]["scopeSpans"][0]["spans"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|s| s["name"].as_str().unwrap())
+ .collect();
+ assert_eq!(names, vec!["jan_agent.llm_request", "jan_agent.interaction"]);
+ } else {
+ assert!(body.windows(21).any(|w| w == b"jan_agent.interaction"));
+ }
+ }
+}
+
+// ── Claude Code compatibility ────────────────────────────────────────────────
+//
+// Each Claude Code signal (https://code.claude.com/docs/en/monitoring-usage,
+// read 2026-09-28) and the jan_agent signal a dashboard built for it should
+// use instead, with the attribute keys that must be present. A row that jan
+// does not emit says why, so dropping a signal fails here instead of silently.
+
+enum Kind {
+ Metric,
+ Event,
+ Span,
+}
+
+enum Jan {
+ Same(&'static str, &'static [&'static str]),
+ Unsupported(&'static str),
+}
+
+const CLAUDE_CODE: &[(&str, Kind, Jan)] = &[
+ ("claude_code.session.count", Kind::Metric, Jan::Same("jan_agent.session.count", &["session.id"])),
+ ("claude_code.token.usage", Kind::Metric, Jan::Same("jan_agent.token.usage", &["session.id", "model", "type"])),
+ ("claude_code.cost.usage", Kind::Metric, Jan::Same("jan_agent.cost.usage", &["session.id", "model"])),
+ ("claude_code.active_time.total", Kind::Metric, Jan::Same("jan_agent.active_time.total", &["session.id"])),
+ ("claude_code.code_edit_tool.decision", Kind::Metric, Jan::Same("jan_agent.tool.count", &["tool_name", "decision"])),
+ ("claude_code.lines_of_code.count", Kind::Metric, Jan::Unsupported("edit tools do not report line counts on the event stream")),
+ ("claude_code.pull_request.count", Kind::Metric, Jan::Unsupported("no PR detection in bash output")),
+ ("claude_code.commit.count", Kind::Metric, Jan::Unsupported("no commit detection in bash output")),
+ ("claude_code.user_prompt", Kind::Event, Jan::Same("jan_agent.user_prompt", &["event.name", "session.id", "prompt.id", "prompt_length"])),
+ ("claude_code.api_request", Kind::Event, Jan::Same("jan_agent.api_request", &["session.id", "prompt.id", "model", "input_tokens", "output_tokens", "cache_read_tokens", "duration_ms"])),
+ ("claude_code.api_error", Kind::Event, Jan::Same("jan_agent.api_error", &["session.id", "prompt.id", "error", "model", "duration_ms"])),
+ ("claude_code.tool_result", Kind::Event, Jan::Same("jan_agent.tool_result", &["session.id", "prompt.id", "tool_name", "success", "duration_ms", "decision", "decision_source"])),
+ ("claude_code.tool_decision", Kind::Event, Jan::Same("jan_agent.tool_decision", &["session.id", "prompt.id", "tool_name", "decision", "source"])),
+ ("claude_code.interaction", Kind::Span, Jan::Same("jan_agent.interaction", &["span.type", "session.id", "prompt.id", "user_prompt", "user_prompt_length", "interaction.sequence", "interaction.duration_ms"])),
+ ("claude_code.llm_request", Kind::Span, Jan::Same("jan_agent.llm_request", &["span.type", "model", "gen_ai.system", "gen_ai.request.model", "duration_ms", "input_tokens", "output_tokens", "cache_read_tokens", "cache_creation_tokens", "success"])),
+ ("claude_code.tool", Kind::Span, Jan::Same("jan_agent.tool", &["span.type", "tool_name", "duration_ms", "tool_use_id", "gen_ai.tool.call.id"])),
+ ("claude_code.tool.execution", Kind::Span, Jan::Unsupported("the event stream has no separate execution start; claude_code.tool's success/duration are on jan_agent.tool")),
+ ("claude_code.tool.blocked_on_user", Kind::Span, Jan::Unsupported("permission waits are not timed yet; decision/source are on jan_agent.tool_decision")),
+ ("claude_code.hook", Kind::Span, Jan::Unsupported("detailed-beta only in Claude Code; hooks do not report to the stream")),
+];
+
+#[test]
+fn every_claude_code_signal_has_a_jan_equivalent_or_a_reason() {
+ let pricer: Pricer = Box::new(|_, _| {
+ Some(TokenRates { prompt_usd: 1e-6, completion_usd: 1e-6, cache_read_usd: None, cache_write_usd: None })
+ });
+ let cfg = Arc::new(cfg_traced(&[]));
+ let mut state = State::new(Arc::clone(&cfg), Some(pricer));
+ let feed = |state: &mut State, e: StreamEvent| {
+ if let Some(sig) = classify(&cfg, &e, None) {
+ state.apply(Instant::now(), 2, sig);
+ }
+ };
+ state.apply(
+ Instant::now(),
+ 1,
+ Signal::RunStart { session: Some("sess-1".into()), run_id: None, prompt: Some((3, None)) },
+ );
+ feed(&mut state, provenance(None, "sess-1"));
+ feed(&mut state, usage(10, 2, 4, 1));
+ feed(&mut state, tool_call("c1", "edit"));
+ feed(&mut state, tool_result("c1", false));
+ feed(&mut state, provenance(None, "sess-1"));
+ feed(&mut state, StreamEvent::Error { code: "upstream".into(), message: "boom".into() });
+ state.apply(
+ Instant::now(),
+ 5,
+ Signal::RunEnd { session: Some("sess-1".into()), run_id: None, elapsed: Duration::from_secs(2) },
+ );
+ let metrics = state.metrics(9, 0);
+ let spans = state.take_spans();
+ let logs = state.take_logs();
+
+ let mut missing = Vec::new();
+ for (theirs, kind, jan) in CLAUDE_CODE {
+ let Jan::Same(ours, keys) = jan else { continue };
+ let keys_of: Vec<Vec<String>> = match kind {
+ Kind::Metric => metrics
+ .iter()
+ .filter(|m| m.name == *ours)
+ .flat_map(|m| m.points.iter().map(|p| p.attrs.iter().map(|(k, _)| k.clone()).collect()))
+ .collect(),
+ Kind::Event => logs
+ .iter()
+ .filter(|l| l.event_name == *ours)
+ .map(|l| l.attrs.iter().map(|(k, _)| k.clone()).collect())
+ .collect(),
+ Kind::Span => spans
+ .iter()
+ .filter(|s| s.name == *ours)
+ .map(|s| s.attrs.iter().map(|(k, _)| k.clone()).collect())
+ .collect(),
+ };
+ if keys_of.is_empty() {
+ missing.push(format!("{theirs} -> {ours}: not emitted"));
+ continue;
+ }
+ for key in *keys {
+ if !keys_of.iter().any(|ks| ks.iter().any(|k| k == key)) {
+ missing.push(format!("{theirs} -> {ours}: no `{key}`"));
+ }
+ }
+ }
+ assert!(missing.is_empty(), "Claude Code parity gaps:\n{}", missing.join("\n"));
+ for (theirs, _, jan) in CLAUDE_CODE {
+ if let Jan::Unsupported(why) = jan {
+ assert!(!why.is_empty(), "{theirs} needs a reason");
+ }
+ }
+}