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): opt-in OpenTelemetry (OTLP) export of metrics and events

thinhlpg53bb9a774b02
diff --git a/docs/src/pages/docs/agent/_meta.json b/docs/src/pages/docs/agent/_meta.json
index 08f6b6cdf..1c12ff4ae 100644
--- a/docs/src/pages/docs/agent/_meta.json
+++ b/docs/src/pages/docs/agent/_meta.json
@@ -25,6 +25,7 @@
"permissions": "Tool Permissions",
"hooks": "Hooks",
"mcp": "MCP",
+ "telemetry": "Telemetry (OpenTelemetry)",
"embedding-separator": { "title": "Embedding", "type": "separator" },
"adk": "Jan ADK",
"adk-nightly": "Nightly ADK Installation",
diff --git a/docs/src/pages/docs/agent/telemetry.mdx b/docs/src/pages/docs/agent/telemetry.mdx
new file mode 100644
index 000000000..a5c525b44
--- /dev/null
+++ b/docs/src/pages/docs/agent/telemetry.mdx
@@ -0,0 +1,188 @@
+---
+title: Telemetry (OpenTelemetry)
+description: Export Jan Agent usage metrics and events over OTLP to your own collector, so a team can see tokens, cost, tool activity and errors in one place.
+keywords: [Jan, Jan Agent, OpenTelemetry, OTLP, telemetry, monitoring, metrics, observability, Grafana, collector]
+---
+
+import { Callout } from 'nextra/components'
+
+# Telemetry (OpenTelemetry)
+
+Jan Agent can export usage **metrics** and **events** 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.
+
+It covers the TUI, `jan cli agent run` (including `--output-format stream-json`) and the
+`jan cli agent rpc` runtime the ADKs drive. Jan Desktop doesn't export it yet.
+
+<Callout type="info">
+Telemetry is **off by default**, and when it's on, data goes only to the endpoint you configure,
+never to Jan. It's separate from the anonymous update-check ping (see
+[CLI](/docs/agent/cli), `JAN_CLI_NO_UPDATE_CHECK`), which is unchanged.
+</Callout>
+
+## Quickstart
+
+Run a local collector that prints what it receives:
+
+```bash
+cat > otel-collector.yaml <<'EOF'
+receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4318
+exporters:
+ debug:
+ verbosity: detailed
+service:
+ pipelines:
+ metrics: { receivers: [otlp], exporters: [debug] }
+ logs: { receivers: [otlp], exporters: [debug] }
+EOF
+docker run --rm -p 4318:4318 \
+ -v "$PWD/otel-collector.yaml:/etc/otelcol/config.yaml" \
+ otel/opentelemetry-collector:latest
+```
+
+Then run the agent with telemetry on:
+
+```bash
+export JAN_AGENT_ENABLE_TELEMETRY=1
+export OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318
+export OTEL_METRIC_EXPORT_INTERVAL=10000 # 10 s instead of 60 s while you try it out
+jan cli agent run "say hi"
+```
+
+The collector prints a `jan_agent.token.usage` metric and a `jan_agent.api_request` event. To
+switch it on permanently, set it in `~/.jan/config.toml` instead of the environment:
+
+```toml
+[telemetry]
+enabled = true
+```
+
+## Turning it on
+
+Telemetry is enabled by the first of these that says anything, highest first:
+
+1. `OTEL_SDK_DISABLED=true` always turns it **off**.
+2. `JAN_AGENT_ENABLE_TELEMETRY` (`1`/`true` or `0`/`false`).
+3. `[telemetry] enabled` in the project's `agent.toml`.
+4. `[telemetry] enabled` in `~/.jan/config.toml`.
+
+Setting `OTEL_EXPORTER_OTLP_ENDPOINT` alone doesn't turn it on. That variable is often set for
+other programs.
+
+## Configuration
+
+Where the data goes is set with the standard OpenTelemetry environment variables, so a collector
+setup you already use for another agent works unchanged.
+
+| Variable | Default | Meaning |
+| --- | --- | --- |
+| `JAN_AGENT_ENABLE_TELEMETRY` | off | Turn the exporter on (`1`) or off (`0`). |
+| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | Base URL. `/v1/metrics` and `/v1/logs` are appended. |
+| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | derived from the base | Full URL for one signal, used as is. |
+| `OTEL_EXPORTER_OTLP_PROTOCOL` (and `_METRICS_` / `_LOGS_` variants) | `http/protobuf` | `http/protobuf` or `http/json`. `grpc` isn't supported yet: Jan logs a warning and uses `http/protobuf`. |
+| `OTEL_EXPORTER_OTLP_HEADERS` (and `_METRICS_` / `_LOGS_` variants) | none | `key=value,key2=value2`, e.g. `Authorization=Bearer%20<token>`. Values are never logged. |
+| `OTEL_EXPORTER_OTLP_TIMEOUT` | `10000` | Per-export timeout in ms. |
+| `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER` | `otlp` | `none` turns that signal off. `console` isn't supported, because stdout carries the RPC and stream-json protocol. |
+| `OTEL_SERVICE_NAME` | `jan-agent` | `service.name` resource attribute. |
+| `OTEL_RESOURCE_ATTRIBUTES` | none | Extra resource attributes, e.g. `tenant.id=acme,deployment.environment=ci`. |
+| `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | How often metrics are exported, in ms. |
+| `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`. |
+
+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.
+
+## Metrics
+
+All metrics are cumulative monotonic sums. Every point carries `session.id` unless
+`OTEL_METRICS_INCLUDE_SESSION_ID=false`.
+
+| Metric | Unit | Attributes |
+| --- | --- | --- |
+| `jan_agent.session.count` | 1 | |
+| `jan_agent.prompt.count` | 1 | |
+| `jan_agent.turn.count` | 1 | `agent` (`main` / `subagent`) |
+| `jan_agent.token.usage` | tokens | `type` (`input` / `output` / `cache_read` / `cache_write`), `model`, `provider` |
+| `jan_agent.cost.usage` | USD | `model`, `provider`. Only for models whose price is in the model catalog. An unpriced model reports nothing, not zero. |
+| `jan_agent.api_request.count` | 1 | `model`, `provider`, `success` |
+| `jan_agent.tool.count` | 1 | `tool_name`, `decision` (`accept` / `reject`), `success` |
+| `jan_agent.active_time.total` | s | Time the top-level run spent working |
+| `jan_agent.compaction.count` | 1 | |
+| `jan_agent.telemetry.dropped` | 1 | Records dropped because the export queue was full |
+
+`input` is prompt tokens not served from or written to the cache, so the four `type`s add up to
+what the provider billed.
+
+## Events
+
+Events are OTLP log records with `event_name` set. Every event carries `session.id` and
+`prompt.id`, which joins all the events a single prompt caused. A subagent's events also carry
+`agent.run_id` and `subagent.name`.
+
+| Event | Attributes |
+| --- | --- |
+| `jan_agent.user_prompt` | `prompt_length`. `prompt` only with `OTEL_LOG_USER_PROMPTS`. |
+| `jan_agent.api_request` | `model`, `provider`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, `duration_ms`, `request_bytes`, `cost_usd` (when priced), `execution_id` (when the provider reports one) |
+| `jan_agent.api_error` | `code`, `error` (message, truncated), `model` and `duration_ms` when a request was in flight |
+| `jan_agent.tool_decision` | `tool_name`, `decision` (`accept` / `reject`), `source` (`config` / `user` / `hook`) |
+| `jan_agent.tool_result` | `tool_name`, `success`, `duration_ms`, `decision`, `decision_source`, `result_size_bytes`. `tool_parameters` only with `OTEL_LOG_TOOL_DETAILS`. |
+| `jan_agent.compaction` | `message_count` |
+| `jan_agent.subagent_result` | `success` |
+
+## Privacy defaults
+
+- Off unless you turn it on, and sent only to your endpoint.
+- Prompt text and tool arguments are left out unless you set `OTEL_LOG_USER_PROMPTS` or
+ `OTEL_LOG_TOOL_DETAILS`. Both are capped at 4 KB when they are included.
+- Tool output and model responses are never exported.
+- API keys, provider credentials, `config.toml` values and the export headers are never exported
+ or logged.
+- Telemetry only reads what the agent already reports. It never changes a request, so
+ prompt caching is unaffected.
+
+## Reliability
+
+Recording a signal never waits: it goes into a bounded in-memory queue. If a collector is slow or
+down, new records are dropped and counted in `jan_agent.telemetry.dropped`, and the turn doesn't
+slow down. Export failures are logged at debug level (`RUST_LOG=debug`) on stderr and never
+printed to stdout.
+
+## With the ADK
+
+The [TypeScript](/docs/agent/adk-ts) and [Python](/docs/agent/adk-python) ADKs start `jan` with
+their own environment plus the `env` option, so either way works:
+
+```ts
+const runtime = new JanRuntime({
+ env: {
+ JAN_AGENT_ENABLE_TELEMETRY: '1',
+ OTEL_EXPORTER_OTLP_ENDPOINT: 'https://otel.example.com',
+ OTEL_EXPORTER_OTLP_HEADERS: 'Authorization=Bearer%20' + token,
+ OTEL_RESOURCE_ATTRIBUTES: 'tenant.id=acme',
+ },
+})
+```
+
+```python
+runtime = JanRuntime(env={
+ "JAN_AGENT_ENABLE_TELEMETRY": "1",
+ "OTEL_EXPORTER_OTLP_ENDPOINT": "https://otel.example.com",
+})
+```
+
+`session.id` on every signal is the RPC `sessionId` your host holds.
+
+## Not yet
+
+- Traces (`interaction` / `llm_request` / `tool` spans) and an inbound `TRACEPARENT`
+- gRPC transport
+- Jan Desktop
+- Admin-enforced (managed) settings
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rs
index 3c51661bb..ebcbe023b 100644
--- a/src-tauri/jan-cli/src/main.rs
+++ b/src-tauri/jan-cli/src/main.rs
@@ -724,7 +724,7 @@ async fn main() {
// TUI runs the same check itself and notes it in the transcript.
// The usage ping is likewise deferred to the TUI's own background task.
let overrides = cli.providers.into_overrides();
- if let Err(e) = cli_agent_ui(
+ let result = cli_agent_ui(
&cli.project,
cli.task,
cli.model,
@@ -739,8 +739,11 @@ async fn main() {
},
cli.resume.into_request(),
)
- .await
- {
+ .await;
+ // `process::exit` skips destructors, so the bounded final export runs
+ // before it. A no-op unless telemetry is on.
+ app_lib::core::agent::otel::shutdown().await;
+ if let Err(e) = result {
eprintln!("Error: {e}");
std::process::exit(1);
}
@@ -797,6 +800,7 @@ async fn main() {
Commands::Mcp { cmd } => handle_mcp_serve(cmd).await,
Commands::Update { check, force } => handle_update(check, force).await,
}
+ app_lib::core::agent::otel::shutdown().await;
}
// ── MCP server handler ─────────────────────────────────────────────────────
@@ -1061,6 +1065,9 @@ async fn handle_agent(cmd: AgentCommands) {
// `make protocol-rpc-schema` use.
AgentCommands::RpcSchema { out } => app_lib::core::cli::rpc_schema::run(out.as_deref()),
};
+ // Before the exit below, which would skip it: the last run's records are
+ // still in the exporter's queue. Bounded, and a no-op unless telemetry is on.
+ app_lib::core::agent::otel::shutdown().await;
if let Err(e) = result {
eprintln!("Error: {e}");
std::process::exit(exit_code(&e));
diff --git a/src-tauri/jan-cli/tests/telemetry_otlp.rs b/src-tauri/jan-cli/tests/telemetry_otlp.rs
new file mode 100644
index 000000000..ee55d3886
--- /dev/null
+++ b/src-tauri/jan-cli/tests/telemetry_otlp.rs
@@ -0,0 +1,200 @@
+//! Opt-in OTLP export, through the real `jan` binary: a scripted provider, a
+//! stand-in collector, and a one-shot stream-json run.
+use std::io::{BufRead, BufReader, Read, Write};
+use std::net::TcpListener;
+use std::path::PathBuf;
+use std::process::{Command, Output, Stdio};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+const REPLY: &str = concat!(
+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",
+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",",
+ "\"content\":\"hi there\"},\"finish_reason\":null}]}\n\n",
+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",
+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],",
+ "\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4,\"total_tokens\":13}}\n\n",
+ "data: [DONE]\n\n",
+);
+
+type Seen = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
+
+/// Answer every HTTP request with `reply`, recording `(path, body)`. Serves as
+/// both the model provider and the collector.
+fn serve(content_type: &'static str, reply: &'static str) -> (String, Seen) {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let seen: Seen = Arc::new(Mutex::new(Vec::new()));
+ let sink = Arc::clone(&seen);
+ std::thread::spawn(move || {
+ for connection in listener.incoming() {
+ let Ok(mut stream) = connection else { break };
+ let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut request_line = String::new();
+ let _ = reader.read_line(&mut request_line);
+ let mut size = 0;
+ loop {
+ let mut line = String::new();
+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
+ break;
+ }
+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") {
+ size = n.trim().parse().unwrap_or(0);
+ }
+ }
+ let mut body = vec![0; size];
+ if reader.read_exact(&mut body).is_err() {
+ continue;
+ }
+ let path = request_line.split_whitespace().nth(1).unwrap_or("").to_string();
+ sink.lock().unwrap().push((path, body));
+ let _ = write!(
+ stream,
+ "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
+ reply.len()
+ );
+ }
+ });
+ (url, seen)
+}
+
+struct Scratch(PathBuf);
+
+impl Scratch {
+ fn new(name: &str) -> Self {
+ let root = std::env::temp_dir().join(format!("jan-otel-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ std::fs::create_dir_all(root.join("home")).unwrap();
+ std::fs::create_dir_all(root.join("project")).unwrap();
+ Self(root)
+ }
+
+ fn command(&self) -> Command {
+ let mut cmd = Command::new(env!("CARGO_BIN_EXE_jan"));
+ cmd.env("HOME", self.0.join("home"))
+ .env("JAN_DATA_FOLDER", self.0.join("jan-data"))
+ .env("JAN_CLI_NO_UPDATE_CHECK", "1");
+ for (key, _) in std::env::vars() {
+ if key.starts_with("OTEL_") || key == "JAN_AGENT_ENABLE_TELEMETRY" {
+ cmd.env_remove(key);
+ }
+ }
+ cmd.env_remove("JAN_API_KEY")
+ .env_remove("OPENAI_API_KEY")
+ .env_remove("ANTHROPIC_API_KEY");
+ cmd
+ }
+
+ fn configure(&self, base_url: &str) {
+ let out = self
+ .command()
+ .args([
+ "config", "set", "--provider", "stub", "--api-key", "test-key", "--base-url",
+ base_url, "--model", "stub-model",
+ ])
+ .output()
+ .unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ }
+
+ fn run(&self, env: &[(&str, &str)]) -> Output {
+ let project = self.0.join("project");
+ let mut cmd = self.command();
+ cmd.args([
+ "cli",
+ "agent",
+ "run",
+ "--project",
+ project.to_str().unwrap(),
+ "--model",
+ "stub-model",
+ "--provider",
+ "stub",
+ "--output-format",
+ "stream-json",
+ "say hi, my password is hunter2",
+ ])
+ .stdin(Stdio::null());
+ for (k, v) in env {
+ cmd.env(k, v);
+ }
+ cmd.output().unwrap()
+ }
+}
+
+impl Drop for Scratch {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+fn stdout_is_protocol_only(out: &Output) {
+ for line in String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.trim().is_empty()) {
+ let record: serde_json::Value =
+ serde_json::from_str(line).unwrap_or_else(|e| panic!("non-JSON stdout {line:?}: {e}"));
+ assert!(record.get("type").is_some(), "{line}");
+ }
+}
+
+#[test]
+fn an_enabled_run_exports_metrics_and_logs_and_keeps_stdout_clean() {
+ let scratch = Scratch::new("on");
+ let (provider, _) = serve("text/event-stream", REPLY);
+ scratch.configure(&format!("{provider}/v1"));
+ let (collector, seen) = serve("application/json", "{}");
+
+ let out = scratch.run(&[
+ ("JAN_AGENT_ENABLE_TELEMETRY", "1"),
+ ("OTEL_EXPORTER_OTLP_ENDPOINT", &collector),
+ ("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json"),
+ ("OTEL_RESOURCE_ATTRIBUTES", "tenant.id=t-1"),
+ ]);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ stdout_is_protocol_only(&out);
+
+ let seen = seen.lock().unwrap().clone();
+ let body = |path: &str| -> serde_json::Value {
+ let (_, body) = seen
+ .iter()
+ .rev()
+ .find(|(p, _)| p == path)
+ .unwrap_or_else(|| panic!("no POST {path}: {:?}", seen.iter().map(|s| &s.0).collect::<Vec<_>>()));
+ serde_json::from_slice(body).unwrap()
+ };
+ let metrics = body("/v1/metrics");
+ let text = metrics.to_string();
+ for name in ["jan_agent.session.count", "jan_agent.token.usage", "jan_agent.prompt.count"] {
+ assert!(text.contains(name), "{name} missing from {text}");
+ }
+ assert!(text.contains("tenant.id") && text.contains("\"stub-model\""), "{text}");
+
+ let all_logs: String = seen
+ .iter()
+ .filter(|(p, _)| p == "/v1/logs")
+ .map(|(_, b)| String::from_utf8_lossy(b).into_owned())
+ .collect();
+ for name in ["jan_agent.user_prompt", "jan_agent.api_request"] {
+ assert!(all_logs.contains(name), "{name} missing from {all_logs}");
+ }
+ // Content is gated off by default, and credentials never travel.
+ assert!(!all_logs.contains("hunter2") && !text.contains("hunter2"));
+ assert!(!all_logs.contains("test-key") && !text.contains("test-key"));
+}
+
+#[test]
+fn nothing_is_sent_unless_telemetry_is_enabled() {
+ let scratch = Scratch::new("off");
+ let (provider, _) = serve("text/event-stream", REPLY);
+ scratch.configure(&format!("{provider}/v1"));
+ let (collector, seen) = serve("application/json", "{}");
+
+ // The endpoint alone is not consent: it may be set for another program.
+ let out = scratch.run(&[
+ ("OTEL_EXPORTER_OTLP_ENDPOINT", &collector),
+ ("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json"),
+ ]);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ std::thread::sleep(Duration::from_millis(200));
+ assert!(seen.lock().unwrap().is_empty(), "{:?}", seen.lock().unwrap());
+}
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rs
index 3223d5003..37f067bfe 100644
--- a/src-tauri/src/core/agent/compaction.rs
+++ b/src-tauri/src/core/agent/compaction.rs
@@ -261,6 +261,9 @@ pub(crate) async fn fire_pre_compact(
ctx: &tauri_plugin_agent_tools::tools::ToolContext<'_>,
message_count: usize,
) {
+ // Every compaction path passes through here, so this is telemetry's one
+ // compaction count too. Inert unless the exporter is on.
+ crate::core::agent::otel::compaction(message_count);
if hooks.is_empty() {
return;
}
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 366488ca5..d5d3731cc 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -56,6 +56,13 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# # Defaults to 👋; set "" for the plain
# # throbber if your terminal draws tofu
#
+# [telemetry] # opt-in OpenTelemetry (OTLP) export of
+# enabled = true # usage metrics and events to YOUR
+# # collector (OTEL_EXPORTER_OTLP_* env);
+# # off by default. A project's agent.toml
+# # [telemetry] and JAN_AGENT_ENABLE_TELEMETRY
+# # win over this
+#
# [providers.my-provider]
# api_key = "sk-..."
# base_url = "https://api.example.com/v1"
@@ -153,10 +160,29 @@ struct GlobalConfigToml {
/// but a human appending to the file would not.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
hooks: Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry>,
+ /// `[telemetry]` -- opt-in OTLP export (`core::agent::otel`). A table, so
+ /// declared after the plain values and before `providers`.
+ #[serde(default, skip_serializing_if = "TelemetrySection::is_empty")]
+ telemetry: TelemetrySection,
#[serde(default)]
providers: HashMap<String, GlobalProviderEntry>,
}
+/// `[telemetry]` in `~/.jan/config.toml` or a project's `agent.toml`. Only the
+/// switch lives here: where the data goes is the standard `OTEL_*` env, so one
+/// collector setup serves every OpenTelemetry-speaking tool unchanged.
+#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
+pub(crate) struct TelemetrySection {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub enabled: Option<bool>,
+}
+
+impl TelemetrySection {
+ fn is_empty(&self) -> bool {
+ self.enabled.is_none()
+ }
+}
+
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
struct GlobalProviderEntry {
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -281,6 +307,14 @@ pub(crate) fn smol_model() -> Result<Option<String>, String> {
Ok(config.smol_model.filter(|m| !m.trim().is_empty()))
}
+/// `[telemetry].enabled` in `~/.jan/config.toml`; `None` when unset. Fails
+/// open to "unset" like every other preference here: telemetry is never a
+/// reason for a session not to start. CLI-only, like its sole caller.
+#[cfg(feature = "cli")]
+pub(crate) fn telemetry_setting() -> Option<bool> {
+ load_raw().ok().and_then(|config| config.telemetry.enabled)
+}
+
/// Whether the TUI should track the mouse (`mouse` in `~/.jan/config.toml`),
/// defaulting to on. A display preference must never block startup, so an
/// unreadable or malformed config yields the default rather than an error.
@@ -809,6 +843,22 @@ mod tests {
});
}
+ #[test]
+ fn telemetry_is_unset_by_default_and_reads_its_table() {
+ with_temp_home(|_| {
+ assert_eq!(telemetry_setting(), None, "missing file");
+ let path = ensure_global_config().expect("ensure");
+ assert_eq!(telemetry_setting(), None, "scaffolded file");
+ std::fs::write(&path, "[telemetry]\nenabled = true\n").unwrap();
+ assert_eq!(telemetry_setting(), Some(true));
+ // A provider write keeps the table.
+ set_provider("p", ProviderUpdate::default()).unwrap();
+ assert_eq!(telemetry_setting(), Some(true));
+ std::fs::write(&path, "not valid toml [[[").unwrap();
+ assert_eq!(telemetry_setting(), None, "fails open to unset");
+ });
+ }
+
#[test]
fn mouse_defaults_on_and_reads_the_toml_key() {
with_temp_home(|_| {
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 86b4a9509..66b8d3be1 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -3368,6 +3368,15 @@ async fn orchestrate_inner(
// hooks fire back to back on the same state.
let request_message_count =
projected_message_count(&transcript, volatile_projection.as_deref(), send_reasoning);
+ // Telemetry's bracket around the same span the hooks bracket: the run
+ // (and the prompt that started it) now, its end and active time when
+ // this is dropped -- on cancellation too. Inert unless the exporter is
+ // on, and it never touches the request.
+ let _telemetry_run = crate::core::agent::otel::RunScope::begin(
+ session_id.as_deref(),
+ run_id.as_deref(),
+ submitted_prompt.as_deref(),
+ );
tools
.fire_hooks(
tauri_plugin_agent_tools::tools::hooks::HookEvent::SessionStart,
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index e75c9440d..2040a88d2 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -38,6 +38,7 @@ pub mod host_schema;
pub mod interaction;
pub mod r#loop;
pub mod memory;
+pub mod otel;
pub mod plan;
pub mod plugin_commands;
pub mod plugins;
diff --git a/src-tauri/src/core/agent/otel/config.rs b/src-tauri/src/core/agent/otel/config.rs
new file mode 100644
index 000000000..37e96fa8b
--- /dev/null
+++ b/src-tauri/src/core/agent/otel/config.rs
@@ -0,0 +1,366 @@
+//! Whether telemetry is on, and where it goes.
+//!
+//! Off unless something turns it on. Precedence for the switch, highest first:
+//! `JAN_AGENT_ENABLE_TELEMETRY` (any explicit value, so `=0` can switch off a
+//! config that enables it), the project's `agent.toml` `[telemetry].enabled`,
+//! then `~/.jan/config.toml` `[telemetry].enabled`. `OTEL_SDK_DISABLED=true`
+//! beats all of them, as the OpenTelemetry spec asks.
+//!
+//! Everything about the destination is read from the standard `OTEL_*`
+//! variables, so a collector setup already written for another agent works
+//! unchanged. Nothing here is ever logged: headers carry credentials.
+
+use std::time::Duration;
+
+/// Wire encoding for an OTLP/HTTP export.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Protocol {
+ HttpProtobuf,
+ HttpJson,
+}
+
+impl Protocol {
+ pub fn content_type(self) -> &'static str {
+ match self {
+ Protocol::HttpProtobuf => "application/x-protobuf",
+ Protocol::HttpJson => "application/json",
+ }
+ }
+}
+
+/// One signal's destination. `None` in [`Config`] means the signal is off.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Target {
+ pub url: String,
+ pub protocol: Protocol,
+ /// Sent with every export. Never logged.
+ pub headers: Vec<(String, String)>,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Config {
+ pub metrics: Option<Target>,
+ pub logs: Option<Target>,
+ /// `service.name` and `OTEL_RESOURCE_ATTRIBUTES`, in order, service first.
+ pub resource: Vec<(String, String)>,
+ pub metric_interval: Duration,
+ pub logs_interval: Duration,
+ pub export_timeout: Duration,
+ /// `OTEL_LOG_USER_PROMPTS`: include prompt text on `user_prompt`.
+ pub log_user_prompts: bool,
+ /// `OTEL_LOG_TOOL_DETAILS`: include tool arguments on `tool_result`.
+ pub log_tool_details: bool,
+ /// `OTEL_METRICS_INCLUDE_SESSION_ID` (default on): tag metric points with
+ /// `session.id`. Off keeps a backend's series count bounded.
+ pub metrics_session_id: bool,
+ /// Human-readable problems with the configuration, for the caller to log.
+ pub warnings: Vec<String>,
+}
+
+pub const DEFAULT_ENDPOINT: &str = "http://localhost:4318";
+pub const DEFAULT_SERVICE_NAME: &str = "jan-agent";
+pub const ENABLE_ENV: &str = "JAN_AGENT_ENABLE_TELEMETRY";
+
+/// `1/true/yes/on` and `0/false/no/off`, case-insensitively; anything else is
+/// no answer at all.
+pub fn parse_flag(value: &str) -> Option<bool> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "1" | "true" | "yes" | "on" => Some(true),
+ "0" | "false" | "no" | "off" => Some(false),
+ _ => None,
+ }
+}
+
+/// Whether telemetry is switched on, given the three places that can say so.
+pub fn enabled(
+ env: &dyn Fn(&str) -> Option<String>,
+ project: Option<bool>,
+ global: Option<bool>,
+) -> bool {
+ if env("OTEL_SDK_DISABLED").as_deref().and_then(parse_flag) == Some(true) {
+ return false;
+ }
+ env(ENABLE_ENV)
+ .as_deref()
+ .and_then(parse_flag)
+ .or(project)
+ .or(global)
+ .unwrap_or(false)
+}
+
+/// Resolve the whole configuration, or `None` when telemetry is off or every
+/// signal was switched off.
+pub fn resolve(
+ env: &dyn Fn(&str) -> Option<String>,
+ project: Option<bool>,
+ global: Option<bool>,
+) -> Option<Config> {
+ if !enabled(env, project, global) {
+ return None;
+ }
+ let get = |key: &str| env(key).map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
+ let mut warnings = Vec::new();
+ let base = get("OTEL_EXPORTER_OTLP_ENDPOINT").unwrap_or_else(|| DEFAULT_ENDPOINT.to_string());
+ let base_protocol = get("OTEL_EXPORTER_OTLP_PROTOCOL");
+ let base_headers = get("OTEL_EXPORTER_OTLP_HEADERS");
+
+ let mut target = |signal: &str, path: &str| -> Option<Target> {
+ let upper = signal.to_ascii_uppercase();
+ match get(&format!("OTEL_{upper}_EXPORTER")).as_deref() {
+ None | Some("otlp") => {}
+ Some("none") => return None,
+ // stdout is the protocol channel for RPC and stream-json, so a
+ // console exporter would corrupt it. Refused everywhere, so the
+ // same environment behaves the same on every surface.
+ Some("console") => {
+ warnings.push(format!(
+ "OTEL_{upper}_EXPORTER=console is not supported (stdout carries the \
+ agent protocol); {signal} are exported over OTLP instead"
+ ));
+ }
+ Some(other) => {
+ warnings.push(format!(
+ "OTEL_{upper}_EXPORTER={other} is not supported; {signal} are exported \
+ over OTLP instead"
+ ));
+ }
+ }
+ let url = get(&format!("OTEL_EXPORTER_OTLP_{upper}_ENDPOINT"))
+ .unwrap_or_else(|| format!("{}/{path}", base.trim_end_matches('/')));
+ let protocol_name = get(&format!("OTEL_EXPORTER_OTLP_{upper}_PROTOCOL"))
+ .or_else(|| base_protocol.clone());
+ let protocol = match protocol_name.as_deref() {
+ None | Some("http/protobuf") => Protocol::HttpProtobuf,
+ Some("http/json") => Protocol::HttpJson,
+ Some(other) => {
+ warnings.push(format!(
+ "OTLP protocol '{other}' is not supported (only http/protobuf and \
+ http/json); using http/protobuf"
+ ));
+ Protocol::HttpProtobuf
+ }
+ };
+ let mut headers = base_headers.as_deref().map(parse_pairs).unwrap_or_default();
+ if let Some(own) = get(&format!("OTEL_EXPORTER_OTLP_{upper}_HEADERS")) {
+ for (k, v) in parse_pairs(&own) {
+ headers.retain(|(existing, _)| !existing.eq_ignore_ascii_case(&k));
+ headers.push((k, v));
+ }
+ }
+ Some(Target { url, protocol, headers })
+ };
+ let metrics = target("metrics", "v1/metrics");
+ let logs = target("logs", "v1/logs");
+ if metrics.is_none() && logs.is_none() {
+ return None;
+ }
+
+ let mut resource = vec![(
+ "service.name".to_string(),
+ get("OTEL_SERVICE_NAME").unwrap_or_else(|| DEFAULT_SERVICE_NAME.to_string()),
+ )];
+ for (k, v) in get("OTEL_RESOURCE_ATTRIBUTES").as_deref().map(parse_pairs).unwrap_or_default() {
+ // OTEL_SERVICE_NAME wins over a service.name in the attribute list.
+ if k == "service.name" && get("OTEL_SERVICE_NAME").is_some() {
+ continue;
+ }
+ resource.retain(|(existing, _)| existing != &k);
+ resource.push((k, v));
+ }
+
+ let millis = |key: &str, default: u64| {
+ Duration::from_millis(
+ get(key)
+ .and_then(|v| v.parse::<u64>().ok())
+ .filter(|v| *v > 0)
+ .unwrap_or(default),
+ )
+ };
+ let gate = |key: &str| get(key).as_deref().and_then(parse_flag).unwrap_or(false);
+ Some(Config {
+ metrics,
+ logs,
+ resource,
+ metric_interval: millis("OTEL_METRIC_EXPORT_INTERVAL", 60_000),
+ logs_interval: millis("OTEL_LOGS_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"),
+ metrics_session_id: get("OTEL_METRICS_INCLUDE_SESSION_ID")
+ .as_deref()
+ .and_then(parse_flag)
+ .unwrap_or(true),
+ warnings,
+ })
+}
+
+/// `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)> {
+ raw.split(',')
+ .filter_map(|pair| {
+ let (k, v) = pair.split_once('=')?;
+ let k = percent_decode(k.trim());
+ (!k.is_empty()).then(|| (k, percent_decode(v.trim())))
+ })
+ .collect()
+}
+
+fn percent_decode(s: &str) -> String {
+ let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
+ let bytes = s.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'%' && i + 2 < bytes.len() {
+ if let (Some(hi), Some(lo)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
+ out.push(hi << 4 | lo);
+ i += 3;
+ continue;
+ }
+ }
+ out.push(bytes[i]);
+ i += 1;
+ }
+ String::from_utf8_lossy(&out).into_owned()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::HashMap;
+
+ fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
+ let map: HashMap<String, String> =
+ pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
+ move |key| map.get(key).cloned()
+ }
+
+ #[test]
+ fn off_by_default() {
+ assert!(resolve(&env(&[]), None, None).is_none());
+ // OTEL_* alone does not opt in: it may be set for some other program.
+ assert!(resolve(&env(&[("OTEL_EXPORTER_OTLP_ENDPOINT", "http://x:4318")]), None, None)
+ .is_none());
+ }
+
+ #[test]
+ fn env_beats_project_beats_global() {
+ assert!(enabled(&env(&[]), None, Some(true)));
+ assert!(!enabled(&env(&[]), Some(false), Some(true)), "agent.toml wins");
+ assert!(enabled(&env(&[]), Some(true), Some(false)));
+ assert!(enabled(&env(&[(ENABLE_ENV, "1")]), Some(false), None), "env wins");
+ assert!(!enabled(&env(&[(ENABLE_ENV, "0")]), Some(true), Some(true)));
+ // An unparseable value is no answer, so the files decide.
+ assert!(enabled(&env(&[(ENABLE_ENV, "maybe")]), None, Some(true)));
+ assert!(
+ !enabled(&env(&[(ENABLE_ENV, "1"), ("OTEL_SDK_DISABLED", "true")]), None, None),
+ "the SDK kill switch wins"
+ );
+ }
+
+ #[test]
+ fn defaults_follow_the_otel_spec() {
+ let c = resolve(&env(&[(ENABLE_ENV, "true")]), None, None).unwrap();
+ let m = c.metrics.unwrap();
+ assert_eq!(m.url, "http://localhost:4318/v1/metrics");
+ assert_eq!(m.protocol, Protocol::HttpProtobuf);
+ assert_eq!(c.logs.unwrap().url, "http://localhost:4318/v1/logs");
+ assert_eq!(c.resource, vec![("service.name".into(), "jan-agent".into())]);
+ assert_eq!(c.metric_interval, Duration::from_secs(60));
+ assert!(!c.log_user_prompts && !c.log_tool_details);
+ assert!(c.metrics_session_id);
+ assert!(c.warnings.is_empty());
+ }
+
+ #[test]
+ fn standard_env_vars_are_honoured() {
+ let c = resolve(
+ &env(&[
+ (ENABLE_ENV, "1"),
+ ("OTEL_EXPORTER_OTLP_ENDPOINT", "https://collector:4318/"),
+ ("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "https://logs.example/ingest"),
+ ("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json"),
+ ("OTEL_EXPORTER_OTLP_HEADERS", "Authorization=Bearer%20abc,x-team=a"),
+ ("OTEL_EXPORTER_OTLP_METRICS_HEADERS", "x-team=b"),
+ ("OTEL_SERVICE_NAME", "robot-studio"),
+ ("OTEL_RESOURCE_ATTRIBUTES", "service.name=ignored,tenant.id=t1"),
+ ("OTEL_METRIC_EXPORT_INTERVAL", "1000"),
+ ("OTEL_LOG_USER_PROMPTS", "1"),
+ ("OTEL_METRICS_INCLUDE_SESSION_ID", "false"),
+ ]),
+ None,
+ None,
+ )
+ .unwrap();
+ let m = c.metrics.unwrap();
+ assert_eq!(m.url, "https://collector:4318/v1/metrics");
+ assert_eq!(m.protocol, Protocol::HttpJson);
+ assert_eq!(
+ m.headers,
+ vec![
+ ("Authorization".into(), "Bearer abc".into()),
+ ("x-team".into(), "b".into())
+ ]
+ );
+ let l = c.logs.unwrap();
+ assert_eq!(l.url, "https://logs.example/ingest", "signal URL is used as-is");
+ assert_eq!(l.headers[1], ("x-team".into(), "a".into()));
+ assert_eq!(
+ c.resource,
+ vec![
+ ("service.name".into(), "robot-studio".into()),
+ ("tenant.id".into(), "t1".into())
+ ]
+ );
+ assert_eq!(c.metric_interval, Duration::from_secs(1));
+ assert!(c.log_user_prompts && !c.log_tool_details);
+ assert!(!c.metrics_session_id);
+ }
+
+ #[test]
+ fn grpc_and_console_fall_back_with_a_warning() {
+ let c = resolve(
+ &env(&[
+ (ENABLE_ENV, "1"),
+ ("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc"),
+ ("OTEL_LOGS_EXPORTER", "console"),
+ ]),
+ None,
+ None,
+ )
+ .unwrap();
+ assert_eq!(c.metrics.unwrap().protocol, Protocol::HttpProtobuf);
+ assert!(c.logs.is_some());
+ assert_eq!(c.warnings.len(), 3, "{:?}", c.warnings);
+ }
+
+ #[test]
+ fn a_signal_can_be_switched_off() {
+ let c = resolve(&env(&[(ENABLE_ENV, "1"), ("OTEL_LOGS_EXPORTER", "none")]), None, None)
+ .unwrap();
+ assert!(c.metrics.is_some() && c.logs.is_none());
+ assert!(resolve(
+ &env(&[
+ (ENABLE_ENV, "1"),
+ ("OTEL_LOGS_EXPORTER", "none"),
+ ("OTEL_METRICS_EXPORTER", "none")
+ ]),
+ None,
+ None
+ )
+ .is_none());
+ }
+
+ #[test]
+ fn pairs_skip_malformed_members_and_decode_values() {
+ assert_eq!(
+ parse_pairs("a=1, bad ,=x,b=%3D%2C,c=50%"),
+ vec![
+ ("a".into(), "1".into()),
+ ("b".into(), "=,".into()),
+ ("c".into(), "50%".into())
+ ]
+ );
+ }
+}
diff --git a/src-tauri/src/core/agent/otel/encode.rs b/src-tauri/src/core/agent/otel/encode.rs
new file mode 100644
index 000000000..9c43bf1de
--- /dev/null
+++ b/src-tauri/src/core/agent/otel/encode.rs
@@ -0,0 +1,446 @@
+//! OTLP wire encoding for the two signals this exporter sends: cumulative
+//! monotonic sums (metrics) and event log records (logs).
+//!
+//! Hand-rolled rather than generated: the subset is small and stable (OTLP v1
+//! is frozen for these messages), and carrying `prost` + the generated proto
+//! types for a dozen fields would add build time to every `cli` build for no
+//! behaviour we need. Both encodings come from the same model, so the JSON a
+//! test can read and the protobuf a collector usually wants cannot disagree.
+//!
+//! Field numbers follow `opentelemetry/proto/{common,resource,metrics,logs}/v1`
+//! and `collector/{metrics,logs}/v1`. OTLP/JSON rules applied here: lowerCamel
+//! field names, 64-bit integers as decimal strings, enums as integers.
+
+use serde_json::{json, Value};
+
+/// An attribute value. Only the scalar kinds this exporter emits.
+#[derive(Debug, Clone, PartialEq)]
+pub enum AnyValue {
+ Str(String),
+ Int(i64),
+ Double(f64),
+ Bool(bool),
+}
+
+pub type Attrs = Vec<(String, AnyValue)>;
+
+/// One point of a cumulative, monotonic sum.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Point {
+ pub attrs: Attrs,
+ pub start_unix_nano: u64,
+ pub time_unix_nano: u64,
+ pub value: PointValue,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum PointValue {
+ Int(i64),
+ Double(f64),
+}
+
+/// A counter, exported as an OTLP `Sum` (cumulative, monotonic).
+#[derive(Debug, Clone, PartialEq)]
+pub struct Metric {
+ pub name: String,
+ pub description: String,
+ pub unit: String,
+ pub points: Vec<Point>,
+}
+
+/// One event, exported as an OTLP `LogRecord` carrying `event_name`.
+#[derive(Debug, Clone, PartialEq)]
+pub struct LogRecord {
+ pub time_unix_nano: u64,
+ /// OTLP `SeverityNumber`: 9 = INFO, 17 = ERROR.
+ pub severity_number: u32,
+ pub severity_text: &'static str,
+ pub event_name: String,
+ pub attrs: Attrs,
+}
+
+/// Who produced the batch: resource attributes plus the instrumentation scope.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Origin {
+ pub resource: Attrs,
+ pub scope_name: String,
+ pub scope_version: String,
+}
+
+// ── OTLP/JSON ────────────────────────────────────────────────────────────────
+
+fn any_json(value: &AnyValue) -> Value {
+ match value {
+ AnyValue::Str(s) => json!({ "stringValue": s }),
+ AnyValue::Int(i) => json!({ "intValue": i.to_string() }),
+ AnyValue::Double(d) => json!({ "doubleValue": d }),
+ AnyValue::Bool(b) => json!({ "boolValue": b }),
+ }
+}
+
+fn attrs_json(attrs: &Attrs) -> Value {
+ Value::Array(
+ attrs
+ .iter()
+ .map(|(k, v)| json!({ "key": k, "value": any_json(v) }))
+ .collect(),
+ )
+}
+
+fn origin_json(origin: &Origin) -> (Value, Value) {
+ (
+ json!({ "attributes": attrs_json(&origin.resource) }),
+ json!({ "name": origin.scope_name, "version": origin.scope_version }),
+ )
+}
+
+pub fn metrics_json(origin: &Origin, metrics: &[Metric]) -> Vec<u8> {
+ let (resource, scope) = origin_json(origin);
+ let metrics: Vec<Value> = metrics
+ .iter()
+ .map(|m| {
+ let points: Vec<Value> = m
+ .points
+ .iter()
+ .map(|p| {
+ let mut point = json!({
+ "attributes": attrs_json(&p.attrs),
+ "startTimeUnixNano": p.start_unix_nano.to_string(),
+ "timeUnixNano": p.time_unix_nano.to_string(),
+ });
+ match p.value {
+ PointValue::Int(i) => point["asInt"] = json!(i.to_string()),
+ PointValue::Double(d) => point["asDouble"] = json!(d),
+ }
+ point
+ })
+ .collect();
+ json!({
+ "name": m.name,
+ "description": m.description,
+ "unit": m.unit,
+ // 2 = AGGREGATION_TEMPORALITY_CUMULATIVE
+ "sum": { "dataPoints": points, "aggregationTemporality": 2, "isMonotonic": true },
+ })
+ })
+ .collect();
+ serde_json::to_vec(&json!({
+ "resourceMetrics": [{
+ "resource": resource,
+ "scopeMetrics": [{ "scope": scope, "metrics": metrics }],
+ }]
+ }))
+ .unwrap_or_default()
+}
+
+pub fn logs_json(origin: &Origin, records: &[LogRecord]) -> Vec<u8> {
+ let (resource, scope) = origin_json(origin);
+ let records: Vec<Value> = records
+ .iter()
+ .map(|r| {
+ json!({
+ "timeUnixNano": r.time_unix_nano.to_string(),
+ "observedTimeUnixNano": r.time_unix_nano.to_string(),
+ "severityNumber": r.severity_number,
+ "severityText": r.severity_text,
+ "eventName": r.event_name,
+ "body": { "stringValue": r.event_name },
+ "attributes": attrs_json(&r.attrs),
+ })
+ })
+ .collect();
+ serde_json::to_vec(&json!({
+ "resourceLogs": [{
+ "resource": resource,
+ "scopeLogs": [{ "scope": scope, "logRecords": records }],
+ }]
+ }))
+ .unwrap_or_default()
+}
+
+// ── OTLP/protobuf ────────────────────────────────────────────────────────────
+
+const VARINT: u64 = 0;
+const FIXED64: u64 = 1;
+const LEN: u64 = 2;
+
+fn varint(buf: &mut Vec<u8>, mut v: u64) {
+ while v >= 0x80 {
+ buf.push((v as u8) | 0x80);
+ v >>= 7;
+ }
+ buf.push(v as u8);
+}
+
+fn tag(buf: &mut Vec<u8>, field: u64, wire: u64) {
+ varint(buf, (field << 3) | wire);
+}
+
+fn pb_str(buf: &mut Vec<u8>, field: u64, s: &str) {
+ pb_bytes(buf, field, s.as_bytes());
+}
+
+fn pb_bytes(buf: &mut Vec<u8>, field: u64, bytes: &[u8]) {
+ tag(buf, field, LEN);
+ varint(buf, bytes.len() as u64);
+ buf.extend_from_slice(bytes);
+}
+
+fn pb_fixed64(buf: &mut Vec<u8>, field: u64, v: u64) {
+ tag(buf, field, FIXED64);
+ buf.extend_from_slice(&v.to_le_bytes());
+}
+
+fn pb_varint(buf: &mut Vec<u8>, field: u64, v: u64) {
+ tag(buf, field, VARINT);
+ varint(buf, v);
+}
+
+/// `AnyValue { string_value = 1; bool_value = 2; int_value = 3; double_value = 4 }`.
+/// A oneof member is written even at its default: presence is the value.
+fn any_pb(value: &AnyValue) -> Vec<u8> {
+ let mut b = Vec::new();
+ match value {
+ AnyValue::Str(s) => pb_str(&mut b, 1, s),
+ AnyValue::Bool(v) => pb_varint(&mut b, 2, *v as u64),
+ AnyValue::Int(i) => pb_varint(&mut b, 3, *i as u64),
+ AnyValue::Double(d) => pb_fixed64(&mut b, 4, d.to_bits()),
+ }
+ b
+}
+
+/// `KeyValue { key = 1; value = 2 }`, each appended as field `field` of `buf`.
+fn attrs_pb(buf: &mut Vec<u8>, field: u64, attrs: &Attrs) {
+ for (k, v) in attrs {
+ let mut kv = Vec::new();
+ pb_str(&mut kv, 1, k);
+ pb_bytes(&mut kv, 2, &any_pb(v));
+ pb_bytes(buf, field, &kv);
+ }
+}
+
+/// `Resource { attributes = 1 }` and `InstrumentationScope { name = 1; version = 2 }`.
+fn origin_pb(origin: &Origin) -> (Vec<u8>, Vec<u8>) {
+ let mut resource = Vec::new();
+ attrs_pb(&mut resource, 1, &origin.resource);
+ let mut scope = Vec::new();
+ pb_str(&mut scope, 1, &origin.scope_name);
+ pb_str(&mut scope, 2, &origin.scope_version);
+ (resource, scope)
+}
+
+/// `ExportMetricsServiceRequest { resource_metrics = 1 }` ->
+/// `ResourceMetrics { resource = 1; scope_metrics = 2 }` ->
+/// `ScopeMetrics { scope = 1; metrics = 2 }` ->
+/// `Metric { name = 1; description = 2; unit = 3; sum = 7 }` ->
+/// `Sum { data_points = 1; aggregation_temporality = 2; is_monotonic = 3 }` ->
+/// `NumberDataPoint { start = 2; time = 3; as_double = 4; as_int = 6; attributes = 7 }`.
+pub fn metrics_proto(origin: &Origin, metrics: &[Metric]) -> Vec<u8> {
+ let (resource, scope) = origin_pb(origin);
+ let mut scope_metrics = Vec::new();
+ pb_bytes(&mut scope_metrics, 1, &scope);
+ for m in metrics {
+ let mut sum = Vec::new();
+ for p in &m.points {
+ let mut point = Vec::new();
+ pb_fixed64(&mut point, 2, p.start_unix_nano);
+ pb_fixed64(&mut point, 3, p.time_unix_nano);
+ match p.value {
+ PointValue::Double(d) => pb_fixed64(&mut point, 4, d.to_bits()),
+ // sfixed64: the same 8 little-endian bytes as fixed64.
+ PointValue::Int(i) => pb_fixed64(&mut point, 6, i as u64),
+ }
+ attrs_pb(&mut point, 7, &p.attrs);
+ pb_bytes(&mut sum, 1, &point);
+ }
+ pb_varint(&mut sum, 2, 2);
+ pb_varint(&mut sum, 3, 1);
+ let mut metric = Vec::new();
+ pb_str(&mut metric, 1, &m.name);
+ pb_str(&mut metric, 2, &m.description);
+ pb_str(&mut metric, 3, &m.unit);
+ pb_bytes(&mut metric, 7, &sum);
+ pb_bytes(&mut scope_metrics, 2, &metric);
+ }
+ let mut resource_metrics = Vec::new();
+ pb_bytes(&mut resource_metrics, 1, &resource);
+ pb_bytes(&mut resource_metrics, 2, &scope_metrics);
+ let mut request = Vec::new();
+ pb_bytes(&mut request, 1, &resource_metrics);
+ request
+}
+
+/// `ExportLogsServiceRequest { resource_logs = 1 }` ->
+/// `ResourceLogs { resource = 1; scope_logs = 2 }` ->
+/// `ScopeLogs { scope = 1; log_records = 2 }` ->
+/// `LogRecord { time = 1; severity_number = 2; severity_text = 3; body = 5;
+/// attributes = 6; observed_time = 11; event_name = 12 }`.
+pub fn logs_proto(origin: &Origin, records: &[LogRecord]) -> Vec<u8> {
+ let (resource, scope) = origin_pb(origin);
+ let mut scope_logs = Vec::new();
+ pb_bytes(&mut scope_logs, 1, &scope);
+ for r in records {
+ let mut record = Vec::new();
+ pb_fixed64(&mut record, 1, r.time_unix_nano);
+ pb_varint(&mut record, 2, r.severity_number as u64);
+ pb_str(&mut record, 3, r.severity_text);
+ pb_bytes(&mut record, 5, &any_pb(&AnyValue::Str(r.event_name.clone())));
+ attrs_pb(&mut record, 6, &r.attrs);
+ pb_fixed64(&mut record, 11, r.time_unix_nano);
+ pb_str(&mut record, 12, &r.event_name);
+ pb_bytes(&mut scope_logs, 2, &record);
+ }
+ let mut resource_logs = Vec::new();
+ pb_bytes(&mut resource_logs, 1, &resource);
+ pb_bytes(&mut resource_logs, 2, &scope_logs);
+ let mut request = Vec::new();
+ pb_bytes(&mut request, 1, &resource_logs);
+ request
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn origin() -> Origin {
+ Origin {
+ resource: vec![("service.name".into(), AnyValue::Str("jan-agent".into()))],
+ scope_name: "jan-agent".into(),
+ scope_version: "1.2.3".into(),
+ }
+ }
+
+ fn counter() -> Metric {
+ Metric {
+ name: "jan_agent.token.usage".into(),
+ description: "tokens".into(),
+ unit: "tokens".into(),
+ points: vec![Point {
+ attrs: vec![("type".into(), AnyValue::Str("input".into()))],
+ start_unix_nano: 1,
+ time_unix_nano: 2,
+ value: PointValue::Int(42),
+ }],
+ }
+ }
+
+ /// Walk one level of a protobuf message: (field number, wire type, payload).
+ fn fields(mut b: &[u8]) -> Vec<(u64, u64, Vec<u8>)> {
+ fn read_varint(b: &mut &[u8]) -> u64 {
+ let mut v = 0u64;
+ let mut shift = 0;
+ loop {
+ let byte = b[0];
+ *b = &b[1..];
+ v |= ((byte & 0x7f) as u64) << shift;
+ if byte & 0x80 == 0 {
+ return v;
+ }
+ shift += 7;
+ }
+ }
+ let mut out = Vec::new();
+ while !b.is_empty() {
+ let key = read_varint(&mut b);
+ let (field, wire) = (key >> 3, key & 7);
+ let payload = match wire {
+ 0 => read_varint(&mut b).to_le_bytes().to_vec(),
+ 1 => {
+ let p = b[..8].to_vec();
+ b = &b[8..];
+ p
+ }
+ 2 => {
+ let n = read_varint(&mut b) as usize;
+ let p = b[..n].to_vec();
+ b = &b[n..];
+ p
+ }
+ other => panic!("unexpected wire type {other}"),
+ };
+ out.push((field, wire, payload));
+ }
+ out
+ }
+
+ fn only(b: &[u8], field: u64) -> Vec<u8> {
+ let found: Vec<_> = fields(b).into_iter().filter(|f| f.0 == field).collect();
+ assert_eq!(found.len(), 1, "field {field} once in {b:?}");
+ found.into_iter().next().unwrap().2
+ }
+
+ #[test]
+ fn a_key_value_encodes_to_the_canonical_bytes() {
+ let mut b = Vec::new();
+ attrs_pb(&mut b, 1, &vec![("a".into(), AnyValue::Str("b".into()))]);
+ // field 1 LEN(8) { key: "a", value: AnyValue { string_value: "b" } }
+ assert_eq!(b, vec![0x0a, 8, 0x0a, 1, b'a', 0x12, 3, 0x0a, 1, b'b']);
+ }
+
+ #[test]
+ fn metrics_protobuf_nests_a_cumulative_sum_under_its_resource() {
+ let bytes = metrics_proto(&origin(), &[counter()]);
+ let resource_metrics = only(&bytes, 1);
+ let scope_metrics = only(&resource_metrics, 2);
+ let metric = only(&scope_metrics, 2);
+ assert_eq!(only(&metric, 1), b"jan_agent.token.usage");
+ let sum = only(&metric, 7);
+ assert_eq!(only(&sum, 2)[0], 2, "cumulative");
+ assert_eq!(only(&sum, 3)[0], 1, "monotonic");
+ let point = only(&sum, 1);
+ assert_eq!(i64::from_le_bytes(only(&point, 6).try_into().unwrap()), 42);
+ let resource = only(&resource_metrics, 1);
+ let kv = only(&resource, 1);
+ assert_eq!(only(&kv, 1), b"service.name");
+ }
+
+ #[test]
+ fn logs_protobuf_carries_the_event_name() {
+ let record = LogRecord {
+ time_unix_nano: 7,
+ severity_number: 9,
+ severity_text: "INFO",
+ event_name: "jan_agent.user_prompt".into(),
+ attrs: vec![("prompt_length".into(), AnyValue::Int(5))],
+ };
+ let bytes = logs_proto(&origin(), &[record]);
+ let scope_logs = only(&only(&bytes, 1), 2);
+ let log = only(&scope_logs, 2);
+ assert_eq!(only(&log, 12), b"jan_agent.user_prompt");
+ assert_eq!(u64::from_le_bytes(only(&log, 1).try_into().unwrap()), 7);
+ }
+
+ #[test]
+ fn json_follows_the_otlp_json_mapping() {
+ let v: Value = serde_json::from_slice(&metrics_json(&origin(), &[counter()])).unwrap();
+ let metric = &v["resourceMetrics"][0]["scopeMetrics"][0]["metrics"][0];
+ assert_eq!(metric["name"], "jan_agent.token.usage");
+ assert_eq!(metric["sum"]["aggregationTemporality"], 2);
+ assert_eq!(metric["sum"]["isMonotonic"], true);
+ let point = &metric["sum"]["dataPoints"][0];
+ // 64-bit integers travel as strings in OTLP/JSON.
+ assert_eq!(point["asInt"], "42");
+ assert_eq!(point["timeUnixNano"], "2");
+ assert_eq!(point["attributes"][0]["value"]["stringValue"], "input");
+ assert_eq!(
+ v["resourceMetrics"][0]["resource"]["attributes"][0]["key"],
+ "service.name"
+ );
+
+ let logs: Value = serde_json::from_slice(&logs_json(
+ &origin(),
+ &[LogRecord {
+ time_unix_nano: 7,
+ severity_number: 17,
+ severity_text: "ERROR",
+ event_name: "jan_agent.api_error".into(),
+ attrs: vec![("success".into(), AnyValue::Bool(false))],
+ }],
+ ))
+ .unwrap();
+ let record = &logs["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0];
+ assert_eq!(record["eventName"], "jan_agent.api_error");
+ assert_eq!(record["severityNumber"], 17);
+ assert_eq!(record["attributes"][0]["value"]["boolValue"], false);
+ }
+}
diff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rs
new file mode 100644
index 000000000..d2ccefa69
--- /dev/null
+++ b/src-tauri/src/core/agent/otel/mod.rs
@@ -0,0 +1,999 @@
+//! 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).
+//!
+//! 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
+//! ping (`cli::telemetry`), which goes to Jan; this goes only to the user's
+//! endpoint.
+//!
+//! One sink, fed from what the engine already reports:
+//!
+//! - every surface (TUI, `cli agent run`, RPC) hands the [`StreamEvent`]s it
+//! consumes to [`observe`], so a child's events arrive in their `Subagent`
+//! bracket and are attributed to its run;
+//! - the loop's own lifecycle points (next to the `SessionStart`/`SessionEnd`
+//! and `UserPromptSubmit` hooks, and `PreCompact`) call [`RunScope::begin`]
+//! and [`compaction`], which the event stream cannot tell.
+//!
+//! The calling side does almost nothing: it turns the event into a small owned
+//! [`Signal`] and `try_send`s it on a bounded queue. A full queue drops the
+//! signal and counts it; nothing on the agent's path ever waits on telemetry.
+//! Aggregation and export happen on one background task, which POSTs to the
+//! collector on the configured intervals, after each top-level run, and once at
+//! shutdown (bounded by [`SHUTDOWN_TIMEOUT`]). Export failures are logged at
+//! debug level and never reach stdout, which is the protocol channel for RPC
+//! and stream-json.
+//!
+//! Nothing here touches a request body: telemetry only reads what the loop
+//! already emitted, so the prompt-cache prefix is unaffected.
+
+pub mod config;
+pub mod encode;
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+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};
+
+/// Signals that can wait for the worker. Generous: a busy turn emits a few
+/// dozen, and the worker drains continuously.
+pub const QUEUE_CAPACITY: usize = 4096;
+/// How long [`shutdown`] waits for the final export before giving up.
+pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
+/// Logs buffered before an early export, whatever the interval.
+const LOG_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`.
+const ERROR_CAP: usize = 512;
+
+/// Per-token prices for `(provider, model)`, when the catalog knows them.
+pub type Pricer = Box<dyn Fn(Option<&str>, &str) -> Option<TokenRates> + Send + Sync>;
+
+/// A subagent's identity, carried on every signal its events produce.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct Child {
+ pub run_id: String,
+ pub name: String,
+}
+
+/// What the calling side hands the worker: small, owned, and already stripped
+/// of anything a content gate withholds.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Signal {
+ RunStart {
+ session: Option<String>,
+ /// `Some` for a child run.
+ run_id: Option<String>,
+ /// The submitted prompt's length in chars, and its text only when
+ /// `OTEL_LOG_USER_PROMPTS` is on. `None` for a child (its task is not a
+ /// user prompt) and for a run with no new prompt.
+ prompt: Option<(usize, Option<String>)>,
+ },
+ RunEnd {
+ session: Option<String>,
+ run_id: Option<String>,
+ elapsed: Duration,
+ },
+ Compaction {
+ message_count: usize,
+ },
+ Event {
+ child: Option<Child>,
+ event: EventSignal,
+ },
+ Flush,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum EventSignal {
+ Request {
+ session: Option<String>,
+ provider: Option<String>,
+ model: String,
+ body_bytes: u64,
+ },
+ Usage {
+ tokens: Tokens,
+ execution_id: Option<String>,
+ },
+ Step,
+ ToolCall {
+ id: String,
+ name: String,
+ /// Serialized arguments, only when `OTEL_LOG_TOOL_DETAILS` is on.
+ args: Option<String>,
+ },
+ ToolResult {
+ id: String,
+ is_error: bool,
+ refusal: Option<Refusal>,
+ bytes: usize,
+ },
+ Permission {
+ tool_name: String,
+ },
+ Error {
+ code: String,
+ message: String,
+ },
+ SubagentEnd {
+ failed: bool,
+ },
+}
+
+/// One request's token counts, as [`Usage`] reports them (`cached` and
+/// `written` are shares of `prompt`). Omitted counts are zero.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct Tokens {
+ pub prompt: u64,
+ pub completion: u64,
+ pub cached: u64,
+ pub written: u64,
+}
+
+impl From<&Usage> for Tokens {
+ fn from(u: &Usage) -> Self {
+ Self {
+ prompt: u.prompt_tokens.unwrap_or(0),
+ completion: u.completion_tokens.unwrap_or(0),
+ cached: u.cached_tokens.unwrap_or(0),
+ written: u.cache_write_tokens.unwrap_or(0),
+ }
+ }
+}
+
+/// Why a tool call never ran, read off the loop's stable refusal messages.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Refusal {
+ /// The user answered a permission prompt with deny.
+ User,
+ /// Project policy, plan mode or the hidden Jan home.
+ Config,
+ /// A `PreToolUse` hook said no.
+ Hook,
+}
+
+impl Refusal {
+ fn source(self) -> &'static str {
+ match self {
+ Refusal::User => "user",
+ Refusal::Config => "config",
+ Refusal::Hook => "hook",
+ }
+ }
+}
+
+/// Classify a tool result the loop produced without running the tool. The
+/// messages are the loop's own (`denied_by_policy_msg`, `hook_denied_msg`, the
+/// user-deny arm), so this only ever reads the head of an `ERROR:` result.
+pub fn refusal_of(content: &str) -> Option<Refusal> {
+ if !content.starts_with("ERROR:") {
+ return None;
+ }
+ let head: String = content.chars().take(300).collect();
+ if head.contains("denied by user") {
+ Some(Refusal::User)
+ } else if head.contains("denied by project policy")
+ || head.contains("unavailable in plan_mode_read_only")
+ || head.contains("refused: the Jan home")
+ {
+ Some(Refusal::Config)
+ } else if head.starts_with("ERROR: tool '") && head.contains("' denied: ") {
+ Some(Refusal::Hook)
+ } else {
+ None
+ }
+}
+
+fn truncate(s: &str, cap: usize) -> String {
+ if s.len() <= cap {
+ return s.to_string();
+ }
+ let mut end = cap;
+ while !s.is_char_boundary(end) {
+ end -= 1;
+ }
+ format!("{}…", &s[..end])
+}
+
+/// The signal an event contributes, if any. Content is dropped here, on the
+/// calling side, so a gated value never even reaches the queue.
+pub fn classify(cfg: &Config, event: &StreamEvent, child: Option<Child>) -> Option<Signal> {
+ let event = match event {
+ StreamEvent::Subagent { run_id, name, event } => {
+ return classify(
+ cfg,
+ event,
+ Some(Child { run_id: run_id.clone(), name: name.clone() }),
+ );
+ }
+ StreamEvent::RequestProvenance { session_id, provider, model, body_bytes, .. } => {
+ EventSignal::Request {
+ session: session_id.clone(),
+ provider: provider.clone(),
+ model: model.clone(),
+ body_bytes: *body_bytes,
+ }
+ }
+ StreamEvent::TurnUsage { usage, execution_id } => EventSignal::Usage {
+ tokens: Tokens::from(usage),
+ execution_id: execution_id.clone(),
+ },
+ StreamEvent::Step { .. } => EventSignal::Step,
+ StreamEvent::ToolCall { id, name, args } => EventSignal::ToolCall {
+ id: id.clone(),
+ name: name.clone(),
+ args: cfg
+ .log_tool_details
+ .then(|| truncate(&args.to_string(), CONTENT_CAP)),
+ },
+ StreamEvent::ToolResult { id, content, is_error, .. } => EventSignal::ToolResult {
+ id: id.clone(),
+ is_error: *is_error,
+ refusal: refusal_of(content),
+ bytes: content.len(),
+ },
+ StreamEvent::PermissionRequest { tool_name, .. } => EventSignal::Permission {
+ tool_name: tool_name.clone(),
+ },
+ StreamEvent::Error { code, message } => EventSignal::Error {
+ code: code.clone(),
+ message: truncate(message, ERROR_CAP),
+ },
+ StreamEvent::SubagentEnd { run_id, name, error } => {
+ return Some(Signal::Event {
+ child: Some(Child { run_id: run_id.clone(), name: name.clone() }),
+ event: EventSignal::SubagentEnd { failed: error.is_some() },
+ });
+ }
+ _ => return None,
+ };
+ Some(Signal::Event { child, event })
+}
+
+/// A running exporter: the bounded queue into its worker, and the worker.
+pub struct Telemetry {
+ cfg: Arc<Config>,
+ tx: mpsc::Sender<(Instant, u64, Signal)>,
+ dropped: Arc<AtomicU64>,
+ stop: Mutex<Option<oneshot::Sender<()>>>,
+ worker: Mutex<Option<tokio::task::JoinHandle<()>>>,
+}
+
+fn wall_nanos() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_nanos() as u64)
+ .unwrap_or(0)
+}
+
+impl Telemetry {
+ /// Start the worker on the current tokio runtime.
+ pub fn start(cfg: Config, pricer: Option<Pricer>, version: &str) -> Self {
+ Self::with_capacity(cfg, pricer, version, QUEUE_CAPACITY)
+ }
+
+ pub fn with_capacity(
+ cfg: Config,
+ pricer: Option<Pricer>,
+ version: &str,
+ capacity: usize,
+ ) -> Self {
+ let cfg = Arc::new(cfg);
+ let (tx, rx) = mpsc::channel(capacity.max(1));
+ let (stop_tx, stop_rx) = oneshot::channel();
+ let dropped = Arc::new(AtomicU64::new(0));
+ let worker = Worker::new(Arc::clone(&cfg), pricer, version, Arc::clone(&dropped));
+ let handle = tokio::spawn(worker.run(rx, stop_rx));
+ Self {
+ cfg,
+ tx,
+ dropped,
+ stop: Mutex::new(Some(stop_tx)),
+ worker: Mutex::new(Some(handle)),
+ }
+ }
+
+ pub fn config(&self) -> &Config {
+ &self.cfg
+ }
+
+ /// Queue a signal without waiting. A full queue drops it and counts it.
+ pub fn send(&self, signal: Signal) {
+ if self.tx.try_send((Instant::now(), wall_nanos(), signal)).is_err() {
+ self.dropped.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+
+ pub fn observe(&self, event: &StreamEvent) {
+ if let Some(signal) = classify(&self.cfg, event, None) {
+ self.send(signal);
+ }
+ }
+
+ pub fn dropped(&self) -> u64 {
+ self.dropped.load(Ordering::Relaxed)
+ }
+
+ /// Export what is buffered and stop the worker, waiting at most `timeout`.
+ pub async fn shutdown(&self, timeout: Duration) {
+ if let Some(stop) = self.stop.lock().unwrap_or_else(|e| e.into_inner()).take() {
+ let _ = stop.send(());
+ }
+ let handle = self.worker.lock().unwrap_or_else(|e| e.into_inner()).take();
+ if let Some(handle) = handle {
+ if tokio::time::timeout(timeout, handle).await.is_err() {
+ log::debug!("telemetry: final export did not finish within {timeout:?}");
+ }
+ }
+ }
+}
+
+// ── The process-wide exporter ────────────────────────────────────────────────
+
+static GLOBAL: OnceLock<Telemetry> = OnceLock::new();
+
+fn global() -> Option<&'static Telemetry> {
+ GLOBAL.get()
+}
+
+/// Turn the exporter on for this process when the configuration says so.
+/// Idempotent: the first call decides. Must run inside a tokio runtime.
+pub fn init(
+ project_enabled: Option<bool>,
+ global_enabled: Option<bool>,
+ pricer: impl FnOnce() -> Option<Pricer>,
+ version: &str,
+) -> bool {
+ if GLOBAL.get().is_some() {
+ return true;
+ }
+ // The worker is a tokio task; a caller outside a runtime cannot host one.
+ if tokio::runtime::Handle::try_current().is_err() {
+ return false;
+ }
+ let env = |key: &str| std::env::var(key).ok();
+ let Some(cfg) = config::resolve(&env, project_enabled, global_enabled) else {
+ return false;
+ };
+ for warning in &cfg.warnings {
+ log::warn!("telemetry: {warning}");
+ }
+ let _ = GLOBAL.set(Telemetry::start(cfg, pricer(), version));
+ true
+}
+
+/// Hand one consumed event to the exporter, if it is on.
+pub fn observe(event: &StreamEvent) {
+ if let Some(t) = global() {
+ t.observe(event);
+ }
+}
+
+/// A compaction is about to run (reported from `PreCompact`'s call site).
+pub fn compaction(message_count: usize) {
+ if let Some(t) = global() {
+ t.send(Signal::Compaction { message_count });
+ }
+}
+
+/// Export whatever is buffered and stop, bounded by [`SHUTDOWN_TIMEOUT`].
+pub async fn shutdown() {
+ if let Some(t) = global() {
+ t.shutdown(SHUTDOWN_TIMEOUT).await;
+ }
+}
+
+/// Brackets one orchestration run: reports its start (and the prompt that
+/// started it) now, and its end and active time when dropped -- so a cancelled
+/// run, whose future is dropped mid-await, is still accounted for.
+pub struct RunScope {
+ session: Option<String>,
+ run_id: Option<String>,
+ started: Instant,
+ armed: bool,
+}
+
+impl RunScope {
+ pub fn begin(session: Option<&str>, run_id: Option<&str>, prompt: Option<&str>) -> Self {
+ let armed = match global() {
+ Some(t) => {
+ let prompt = run_id.is_none().then_some(prompt).flatten().map(|p| {
+ (
+ p.chars().count(),
+ t.cfg.log_user_prompts.then(|| truncate(p, CONTENT_CAP)),
+ )
+ });
+ t.send(Signal::RunStart {
+ session: session.map(str::to_string),
+ run_id: run_id.map(str::to_string),
+ prompt,
+ });
+ true
+ }
+ None => false,
+ };
+ Self {
+ session: session.map(str::to_string),
+ run_id: run_id.map(str::to_string),
+ started: Instant::now(),
+ armed,
+ }
+ }
+}
+
+impl Drop for RunScope {
+ fn drop(&mut self) {
+ if !self.armed {
+ return;
+ }
+ if let Some(t) = global() {
+ t.send(Signal::RunEnd {
+ session: self.session.take(),
+ run_id: self.run_id.take(),
+ elapsed: self.started.elapsed(),
+ });
+ }
+ }
+}
+
+// ── Aggregation ──────────────────────────────────────────────────────────────
+
+/// `(name, description, unit, is_double)` for every metric this exports.
+const METRICS: &[(&str, &str, &str, bool)] = &[
+ ("jan_agent.session.count", "Sessions started", "1", false),
+ ("jan_agent.prompt.count", "User prompts submitted", "1", false),
+ ("jan_agent.turn.count", "Agent loop turns (model requests that start a step)", "1", false),
+ ("jan_agent.token.usage", "Tokens used, by type", "tokens", false),
+ ("jan_agent.cost.usage", "Estimated cost from the model catalog's published prices", "USD", true),
+ ("jan_agent.api_request.count", "Provider requests, by outcome", "1", false),
+ ("jan_agent.tool.count", "Tool calls, by tool, decision and outcome", "1", false),
+ ("jan_agent.active_time.total", "Time the agent spent running", "s", true),
+ ("jan_agent.compaction.count", "History compactions", "1", false),
+ ("jan_agent.telemetry.dropped", "Telemetry signals dropped on a full queue", "1", false),
+];
+
+type SeriesKey = (&'static str, Vec<(String, String)>);
+
+#[derive(Debug)]
+struct PendingRequest {
+ at: Instant,
+ model: String,
+ provider: Option<String>,
+ body_bytes: u64,
+}
+
+#[derive(Debug)]
+struct PendingTool {
+ at: Instant,
+ name: String,
+ args: Option<String>,
+}
+
+/// 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 {
+ cfg: Arc<Config>,
+ pricer: Option<Pricer>,
+ start_nanos: u64,
+ counters: BTreeMap<SeriesKey, f64>,
+ logs: Vec<LogRecord>,
+ sessions_seen: HashSet<String>,
+ /// The session each run (`None` = the main run) last reported, from its
+ /// provenance, so tool and usage records can carry it.
+ run_session: HashMap<Option<String>, String>,
+ requests: HashMap<Option<String>, PendingRequest>,
+ tools: HashMap<(Option<String>, String), PendingTool>,
+ /// Tools a permission prompt was raised for and not yet resolved, per run.
+ prompted: HashMap<Option<String>, Vec<String>>,
+ prompt_id: Option<String>,
+ main_session: Option<String>,
+}
+
+fn metric_attr(key: &str, value: impl Into<String>) -> (String, String) {
+ (key.to_string(), value.into())
+}
+
+impl State {
+ pub fn new(cfg: Arc<Config>, pricer: Option<Pricer>) -> Self {
+ Self {
+ cfg,
+ pricer,
+ start_nanos: wall_nanos(),
+ counters: BTreeMap::new(),
+ logs: Vec::new(),
+ sessions_seen: HashSet::new(),
+ run_session: HashMap::new(),
+ requests: HashMap::new(),
+ tools: HashMap::new(),
+ prompted: HashMap::new(),
+ prompt_id: None,
+ main_session: None,
+ }
+ }
+
+ fn add(&mut self, name: &'static str, mut attrs: Vec<(String, String)>, by: f64) {
+ if by <= 0.0 {
+ return;
+ }
+ attrs.sort();
+ *self.counters.entry((name, attrs)).or_insert(0.0) += by;
+ }
+
+ /// `session.id` for a metric point, unless the user opted out of it.
+ fn session_attr(&self, session: Option<&str>) -> Vec<(String, String)> {
+ match session {
+ Some(s) if self.cfg.metrics_session_id => vec![metric_attr("session.id", s)],
+ _ => Vec::new(),
+ }
+ }
+
+ fn session_of(&self, run: &Option<String>) -> Option<String> {
+ self.run_session
+ .get(run)
+ .or_else(|| self.run_session.get(&None))
+ .cloned()
+ .or_else(|| self.main_session.clone())
+ }
+
+ fn log(
+ &mut self,
+ at: u64,
+ name: &str,
+ error: bool,
+ session: Option<&str>,
+ child: Option<&Child>,
+ mut attrs: Attrs,
+ ) {
+ let mut all: Attrs = vec![("event.name".into(), AnyValue::Str(name.to_string()))];
+ if let Some(s) = session {
+ all.push(("session.id".into(), AnyValue::Str(s.to_string())));
+ }
+ if let Some(p) = &self.prompt_id {
+ all.push(("prompt.id".into(), AnyValue::Str(p.clone())));
+ }
+ if let Some(c) = child {
+ all.push(("agent.run_id".into(), AnyValue::Str(c.run_id.clone())));
+ all.push(("subagent.name".into(), AnyValue::Str(c.name.clone())));
+ }
+ all.append(&mut attrs);
+ self.logs.push(LogRecord {
+ time_unix_nano: at,
+ severity_number: if error { 17 } else { 9 },
+ severity_text: if error { "ERROR" } else { "INFO" },
+ event_name: name.to_string(),
+ attrs: all,
+ });
+ }
+
+ 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.main_session = session.clone();
+ if let Some(s) = &session {
+ self.run_session.insert(None, s.clone());
+ if self.sessions_seen.insert(s.clone()) {
+ let attrs = self.session_attr(Some(s));
+ self.add("jan_agent.session.count", attrs, 1.0);
+ }
+ }
+ }
+ if let Some((length, text)) = prompt {
+ self.prompt_id = Some(uuid::Uuid::new_v4().to_string());
+ let attrs = self.session_attr(session.as_deref());
+ self.add("jan_agent.prompt.count", attrs, 1.0);
+ let mut fields: Attrs =
+ vec![("prompt_length".into(), AnyValue::Int(length as i64))];
+ if let Some(text) = text {
+ fields.push(("prompt".into(), AnyValue::Str(text)));
+ }
+ self.log(wall, "jan_agent.user_prompt", false, session.as_deref(), None, fields);
+ }
+ }
+ Signal::RunEnd { session, run_id, elapsed } => {
+ // Only the top-level run: a child's time overlaps its parent's.
+ 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());
+ }
+ }
+ Signal::Compaction { message_count } => {
+ let session = self.main_session.clone();
+ let attrs = self.session_attr(session.as_deref());
+ self.add("jan_agent.compaction.count", attrs, 1.0);
+ self.log(
+ wall,
+ "jan_agent.compaction",
+ false,
+ session.as_deref(),
+ None,
+ vec![("message_count".into(), AnyValue::Int(message_count as i64))],
+ );
+ }
+ Signal::Event { child, event } => self.apply_event(at, wall, child, event),
+ Signal::Flush => {}
+ }
+ }
+
+ fn apply_event(&mut self, at: Instant, wall: u64, child: Option<Child>, event: EventSignal) {
+ let run = child.as_ref().map(|c| c.run_id.clone());
+ match event {
+ EventSignal::Request { session, provider, model, body_bytes } => {
+ if let Some(s) = session {
+ self.run_session.insert(run.clone(), s);
+ }
+ self.requests.insert(run, PendingRequest { at, model, provider, body_bytes });
+ }
+ EventSignal::Usage { tokens, execution_id } => {
+ let session = self.session_of(&run);
+ let request = self.requests.remove(&run);
+ let (model, provider) = request
+ .as_ref()
+ .map(|r| (r.model.clone(), r.provider.clone()))
+ .unwrap_or_else(|| ("unknown".to_string(), None));
+ let prompt = tokens.prompt;
+ let cached = tokens.cached.min(prompt);
+ let written = tokens.written.min(prompt - cached);
+ let input = prompt - cached - written;
+ let output = tokens.completion;
+ let mut base = self.session_attr(session.as_deref());
+ base.push(metric_attr("model", model.clone()));
+ if let Some(p) = &provider {
+ base.push(metric_attr("provider", p.clone()));
+ }
+ for (kind, n) in [
+ ("input", input),
+ ("output", output),
+ ("cache_read", cached),
+ ("cache_write", written),
+ ] {
+ let mut attrs = base.clone();
+ attrs.push(metric_attr("type", kind));
+ self.add("jan_agent.token.usage", attrs, n as f64);
+ }
+ let cost = self
+ .pricer
+ .as_ref()
+ .and_then(|price| price(provider.as_deref(), &model))
+ .map(|rates| rates.cost_usd(prompt, output, cached, written));
+ if let Some(cost) = cost {
+ self.add("jan_agent.cost.usage", base.clone(), cost);
+ }
+ let mut ok = base;
+ ok.push(metric_attr("success", "true"));
+ self.add("jan_agent.api_request.count", ok, 1.0);
+ let mut fields: Attrs = vec![
+ ("model".into(), AnyValue::Str(model)),
+ ("input_tokens".into(), AnyValue::Int(input as i64)),
+ ("output_tokens".into(), AnyValue::Int(output as i64)),
+ ("cache_read_tokens".into(), AnyValue::Int(cached as i64)),
+ ("cache_write_tokens".into(), AnyValue::Int(written as i64)),
+ ];
+ if let Some(p) = provider {
+ fields.push(("provider".into(), AnyValue::Str(p)));
+ }
+ if let Some(r) = &request {
+ let ms = at.saturating_duration_since(r.at).as_millis() as i64;
+ fields.push(("duration_ms".into(), AnyValue::Int(ms)));
+ fields.push(("request_bytes".into(), AnyValue::Int(r.body_bytes as i64)));
+ }
+ if let Some(cost) = cost {
+ fields.push(("cost_usd".into(), AnyValue::Double(cost)));
+ }
+ if let Some(id) = execution_id {
+ fields.push(("execution_id".into(), AnyValue::Str(id)));
+ }
+ self.log(wall, "jan_agent.api_request", false, session.as_deref(), child.as_ref(), fields);
+ }
+ EventSignal::Step => {
+ let mut attrs = Vec::new();
+ attrs.push(metric_attr("agent", if child.is_some() { "subagent" } else { "main" }));
+ self.add("jan_agent.turn.count", attrs, 1.0);
+ }
+ EventSignal::ToolCall { id, name, args } => {
+ self.tools.insert((run, id), PendingTool { at, 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 {
+ return;
+ };
+ let prompted = self
+ .prompted
+ .get_mut(&run)
+ .and_then(|names| {
+ let at = names.iter().position(|n| *n == tool.name)?;
+ Some(names.remove(at))
+ })
+ .is_some();
+ let (decision, source) = match refusal {
+ Some(r) => ("reject", r.source()),
+ None if prompted => ("accept", "user"),
+ None => ("accept", "config"),
+ };
+ let success = !is_error;
+ let mut attrs = self.session_attr(session.as_deref());
+ attrs.push(metric_attr("tool_name", tool.name.clone()));
+ attrs.push(metric_attr("decision", decision));
+ attrs.push(metric_attr("success", success.to_string()));
+ self.add("jan_agent.tool.count", attrs, 1.0);
+ self.log(
+ wall,
+ "jan_agent.tool_decision",
+ false,
+ session.as_deref(),
+ child.as_ref(),
+ vec![
+ ("tool_name".into(), AnyValue::Str(tool.name.clone())),
+ ("decision".into(), AnyValue::Str(decision.into())),
+ ("source".into(), AnyValue::Str(source.into())),
+ ],
+ );
+ let mut fields: Attrs = vec![
+ ("tool_name".into(), AnyValue::Str(tool.name)),
+ ("success".into(), AnyValue::Bool(success)),
+ (
+ "duration_ms".into(),
+ AnyValue::Int(at.saturating_duration_since(tool.at).as_millis() as i64),
+ ),
+ ("decision".into(), AnyValue::Str(decision.into())),
+ ("decision_source".into(), AnyValue::Str(source.into())),
+ ("result_size_bytes".into(), AnyValue::Int(bytes as i64)),
+ ];
+ if let Some(args) = tool.args {
+ fields.push(("tool_parameters".into(), AnyValue::Str(args)));
+ }
+ 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);
+ let mut fields: Attrs = vec![
+ ("code".into(), AnyValue::Str(code)),
+ ("error".into(), AnyValue::Str(message)),
+ ];
+ if let Some(r) = request {
+ let mut attrs = self.session_attr(session.as_deref());
+ attrs.push(metric_attr("model", r.model.clone()));
+ if let Some(p) = &r.provider {
+ attrs.push(metric_attr("provider", p.clone()));
+ }
+ attrs.push(metric_attr("success", "false"));
+ self.add("jan_agent.api_request.count", attrs, 1.0);
+ fields.push(("model".into(), AnyValue::Str(r.model)));
+ fields.push((
+ "duration_ms".into(),
+ AnyValue::Int(at.saturating_duration_since(r.at).as_millis() as i64),
+ ));
+ }
+ self.log(wall, "jan_agent.api_error", true, session.as_deref(), child.as_ref(), fields);
+ }
+ EventSignal::SubagentEnd { failed } => {
+ let session = self.session_of(&None);
+ self.log(
+ wall,
+ "jan_agent.subagent_result",
+ failed,
+ session.as_deref(),
+ child.as_ref(),
+ vec![("success".into(), AnyValue::Bool(!failed))],
+ );
+ // The child's bookkeeping ends with it.
+ self.requests.remove(&run);
+ self.run_session.remove(&run);
+ self.prompted.remove(&run);
+ self.tools.retain(|(r, _), _| *r != run);
+ }
+ }
+ }
+
+ pub fn take_logs(&mut self) -> Vec<LogRecord> {
+ std::mem::take(&mut self.logs)
+ }
+
+ pub fn pending_logs(&self) -> usize {
+ self.logs.len()
+ }
+
+ /// Every series so far, cumulative since the exporter started.
+ pub fn metrics(&self, now: u64, dropped: u64) -> Vec<Metric> {
+ let mut by_name: BTreeMap<&'static str, Vec<Point>> = BTreeMap::new();
+ let dropped_key = ("jan_agent.telemetry.dropped", Vec::new());
+ let dropped_entry = (dropped > 0).then_some((&dropped_key, dropped as f64));
+ for ((name, attrs), value) in self
+ .counters
+ .iter()
+ .map(|(k, v)| (k, *v))
+ .chain(dropped_entry)
+ {
+ let is_double = METRICS.iter().find(|m| m.0 == *name).is_some_and(|m| m.3);
+ by_name.entry(name).or_default().push(Point {
+ attrs: attrs
+ .iter()
+ .map(|(k, v)| (k.clone(), AnyValue::Str(v.clone())))
+ .collect(),
+ start_unix_nano: self.start_nanos,
+ time_unix_nano: now,
+ value: if is_double {
+ PointValue::Double(value)
+ } else {
+ PointValue::Int(value as i64)
+ },
+ });
+ }
+ by_name
+ .into_iter()
+ .map(|(name, points)| {
+ let (_, description, unit, _) =
+ METRICS.iter().find(|m| m.0 == name).copied().unwrap_or((name, "", "", false));
+ Metric {
+ name: name.to_string(),
+ description: description.to_string(),
+ unit: unit.to_string(),
+ points,
+ }
+ })
+ .collect()
+ }
+}
+
+// ── Export ───────────────────────────────────────────────────────────────────
+
+struct Worker {
+ cfg: Arc<Config>,
+ state: State,
+ origin: Origin,
+ dropped: Arc<AtomicU64>,
+ client: reqwest::Client,
+ /// Whether any metric changed since the last export, so an idle process
+ /// does not re-send the same totals every interval.
+ metrics_dirty: bool,
+}
+
+impl Worker {
+ fn new(cfg: Arc<Config>, pricer: Option<Pricer>, version: &str, dropped: Arc<AtomicU64>) -> Self {
+ let mut resource: Attrs = cfg
+ .resource
+ .iter()
+ .map(|(k, v)| (k.clone(), AnyValue::Str(v.clone())))
+ .collect();
+ for (k, v) in [
+ ("service.version", version.to_string()),
+ ("os.type", std::env::consts::OS.to_string()),
+ ("host.arch", std::env::consts::ARCH.to_string()),
+ ] {
+ if !resource.iter().any(|(existing, _)| existing == k) {
+ resource.push((k.to_string(), AnyValue::Str(v)));
+ }
+ }
+ let client = reqwest::Client::builder()
+ .timeout(cfg.export_timeout)
+ .build()
+ .unwrap_or_default();
+ Self {
+ state: State::new(Arc::clone(&cfg), pricer),
+ origin: Origin {
+ resource,
+ scope_name: "jan-agent".to_string(),
+ scope_version: version.to_string(),
+ },
+ cfg,
+ dropped,
+ client,
+ metrics_dirty: false,
+ }
+ }
+
+ async fn run(
+ mut self,
+ mut rx: mpsc::Receiver<(Instant, u64, Signal)>,
+ mut stop: oneshot::Receiver<()>,
+ ) {
+ let mut metric_tick = tokio::time::interval(self.cfg.metric_interval);
+ let mut logs_tick = tokio::time::interval(self.cfg.logs_interval);
+ // The first tick of an interval fires at once; skip it.
+ metric_tick.tick().await;
+ logs_tick.tick().await;
+ loop {
+ tokio::select! {
+ biased;
+ _ = &mut stop => break,
+ message = rx.recv() => {
+ let Some((at, wall, signal)) = message else { break };
+ let flush = matches!(signal, Signal::Flush)
+ || matches!(signal, Signal::RunEnd { run_id: None, .. });
+ self.metrics_dirty |= !matches!(signal, Signal::Flush);
+ self.state.apply(at, wall, signal);
+ if flush {
+ self.export_all().await;
+ } else if self.state.pending_logs() >= LOG_BATCH {
+ self.export_logs().await;
+ }
+ }
+ _ = metric_tick.tick() => self.export_metrics().await,
+ _ = logs_tick.tick() => self.export_logs().await,
+ }
+ }
+ // Whatever the agent already queued is part of the run being reported.
+ while let Ok((at, wall, signal)) = rx.try_recv() {
+ self.metrics_dirty = true;
+ self.state.apply(at, wall, signal);
+ }
+ // Dirty only if something changed since the last export: a run's end
+ // already exported, and resending identical totals is noise.
+ self.export_all().await;
+ }
+
+ async fn export_all(&mut self) {
+ self.export_logs().await;
+ self.export_metrics().await;
+ }
+
+ async fn export_metrics(&mut self) {
+ let Some(target) = self.cfg.metrics.clone() else { return };
+ if !self.metrics_dirty {
+ return;
+ }
+ let metrics = self.state.metrics(wall_nanos(), self.dropped.load(Ordering::Relaxed));
+ if metrics.is_empty() {
+ return;
+ }
+ self.metrics_dirty = false;
+ let body = match target.protocol {
+ config::Protocol::HttpJson => encode::metrics_json(&self.origin, &metrics),
+ config::Protocol::HttpProtobuf => encode::metrics_proto(&self.origin, &metrics),
+ };
+ self.post(&target, body, "metrics").await;
+ }
+
+ async fn export_logs(&mut self) {
+ let Some(target) = self.cfg.logs.clone() else {
+ self.state.take_logs();
+ return;
+ };
+ let logs = self.state.take_logs();
+ if logs.is_empty() {
+ return;
+ }
+ let body = match target.protocol {
+ config::Protocol::HttpJson => encode::logs_json(&self.origin, &logs),
+ config::Protocol::HttpProtobuf => encode::logs_proto(&self.origin, &logs),
+ };
+ self.post(&target, body, "logs").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) {
+ let mut request = self
+ .client
+ .post(&target.url)
+ .header(reqwest::header::CONTENT_TYPE, target.protocol.content_type())
+ .body(body);
+ for (k, v) in &target.headers {
+ request = request.header(k.as_str(), v.as_str());
+ }
+ match request.send().await {
+ Ok(response) if response.status().is_success() => {}
+ Ok(response) => {
+ log::debug!("telemetry: {signal} export rejected: HTTP {}", response.status())
+ }
+ Err(e) => log::debug!("telemetry: {signal} export failed: {}", e.without_url()),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/src-tauri/src/core/agent/otel/tests.rs b/src-tauri/src/core/agent/otel/tests.rs
new file mode 100644
index 000000000..e3b4e692f
--- /dev/null
+++ b/src-tauri/src/core/agent/otel/tests.rs
@@ -0,0 +1,510 @@
+use super::*;
+use serde_json::{json, Value};
+use std::time::Duration;
+
+fn cfg_with(prompts: bool, tools: bool) -> Config {
+ let env = move |key: &str| match key {
+ config::ENABLE_ENV => Some("1".to_string()),
+ "OTEL_LOG_USER_PROMPTS" if prompts => Some("1".to_string()),
+ "OTEL_LOG_TOOL_DETAILS" if tools => Some("1".to_string()),
+ _ => None,
+ };
+ config::resolve(&env, None, None).unwrap()
+}
+
+fn provenance(run: Option<&str>, session: &str) -> StreamEvent {
+ StreamEvent::RequestProvenance {
+ run_id: run.map(str::to_string),
+ session_id: Some(session.into()),
+ provider: Some("stub".into()),
+ model: "stub-model".into(),
+ api_type: None,
+ request_sha256: "0".repeat(64),
+ body_bytes: 123,
+ tools_sha256: None,
+ images: Vec::new(),
+ }
+}
+
+fn usage(prompt: u64, completion: u64, cached: u64, written: u64) -> StreamEvent {
+ StreamEvent::TurnUsage {
+ usage: Usage {
+ prompt_tokens: Some(prompt),
+ completion_tokens: Some(completion),
+ total_tokens: Some(prompt + completion),
+ cached_tokens: Some(cached),
+ cache_write_tokens: Some(written),
+ },
+ execution_id: None,
+ }
+}
+
+/// Feed `events` through the same classification the sink uses.
+fn fold(cfg: Config, pricer: Option<Pricer>, events: &[StreamEvent]) -> State {
+ let cfg = Arc::new(cfg);
+ let mut state = State::new(Arc::clone(&cfg), pricer);
+ state.apply(
+ Instant::now(),
+ 1,
+ Signal::RunStart {
+ session: Some("sess-1".into()),
+ run_id: None,
+ prompt: Some((11, cfg.log_user_prompts.then(|| "secret plan".to_string()))),
+ },
+ );
+ for event in events {
+ if let Some(signal) = classify(&cfg, event, None) {
+ state.apply(Instant::now(), 2, signal);
+ }
+ }
+ state
+}
+
+fn point(state: &State, name: &str, want: &[(&str, &str)]) -> Option<PointValue> {
+ state
+ .metrics(3, 0)
+ .into_iter()
+ .find(|m| m.name == name)?
+ .points
+ .into_iter()
+ .find(|p| {
+ want.iter().all(|(k, v)| {
+ p.attrs.iter().any(|(pk, pv)| pk == k && *pv == AnyValue::Str(v.to_string()))
+ })
+ })
+ .map(|p| p.value)
+}
+
+fn log_names(logs: &[LogRecord]) -> Vec<&str> {
+ logs.iter().map(|l| l.event_name.as_str()).collect()
+}
+
+fn attr<'a>(record: &'a LogRecord, key: &str) -> Option<&'a AnyValue> {
+ record.attrs.iter().find(|(k, _)| k == key).map(|(_, v)| v)
+}
+
+#[test]
+fn usage_splits_tokens_by_type_with_model_and_provider() {
+ let state = fold(
+ cfg_with(false, false),
+ Some(Box::new(|provider, model| {
+ (provider == Some("stub") && model == "stub-model").then_some(TokenRates {
+ prompt_usd: 1.0,
+ completion_usd: 2.0,
+ cache_read_usd: Some(0.5),
+ cache_write_usd: None,
+ })
+ })),
+ &[
+ provenance(None, "sess-1"),
+ StreamEvent::Step { index: 1, max: 0 },
+ usage(100, 10, 30, 20),
+ ],
+ );
+ let tokens = |kind| point(&state, "jan_agent.token.usage", &[("type", kind), ("model", "stub-model"), ("provider", "stub"), ("session.id", "sess-1")]);
+ // `cached` and `cache_write` are shares of `prompt_tokens`, so input is
+ // what is left of it.
+ assert_eq!(tokens("input"), Some(PointValue::Int(50)));
+ assert_eq!(tokens("output"), Some(PointValue::Int(10)));
+ assert_eq!(tokens("cache_read"), Some(PointValue::Int(30)));
+ assert_eq!(tokens("cache_write"), Some(PointValue::Int(20)));
+ // 50*1 + 30*0.5 + 20*1 (no write rate: the prompt rate) + 10*2
+ assert_eq!(
+ point(&state, "jan_agent.cost.usage", &[("model", "stub-model")]),
+ Some(PointValue::Double(105.0))
+ );
+ assert_eq!(point(&state, "jan_agent.session.count", &[]), Some(PointValue::Int(1)));
+ assert_eq!(point(&state, "jan_agent.turn.count", &[("agent", "main")]), Some(PointValue::Int(1)));
+ let logs = state.logs.clone();
+ assert_eq!(log_names(&logs), vec!["jan_agent.user_prompt", "jan_agent.api_request"]);
+ let request = &logs[1];
+ assert_eq!(attr(request, "input_tokens"), Some(&AnyValue::Int(50)));
+ assert_eq!(attr(request, "request_bytes"), Some(&AnyValue::Int(123)));
+ assert!(attr(request, "duration_ms").is_some());
+ // Joined to the prompt that caused it.
+ assert_eq!(attr(request, "prompt.id"), attr(&logs[0], "prompt.id"));
+ assert!(attr(request, "prompt.id").is_some());
+}
+
+#[test]
+fn an_unpriced_model_reports_no_cost_rather_than_zero() {
+ let state = fold(cfg_with(false, false), None, &[provenance(None, "s"), usage(10, 1, 0, 0)]);
+ assert!(point(&state, "jan_agent.cost.usage", &[]).is_none());
+}
+
+#[test]
+fn prompt_text_and_tool_arguments_are_gated() {
+ let events = [
+ StreamEvent::ToolCall {
+ id: "t1".into(),
+ name: "bash".into(),
+ args: json!({ "command": "cat ~/.ssh/id_rsa" }),
+ },
+ StreamEvent::ToolResult {
+ id: "t1".into(),
+ content: "PRIVATE KEY".into(),
+ is_error: false,
+ diff: None,
+ },
+ ];
+ let everything = |state: &State| {
+ let body = encode::logs_json(
+ &Origin { resource: Vec::new(), scope_name: String::new(), scope_version: String::new() },
+ &state.logs,
+ );
+ String::from_utf8(body).unwrap()
+ };
+
+ let closed = everything(&fold(cfg_with(false, false), None, &events));
+ assert!(!closed.contains("secret plan"), "{closed}");
+ assert!(!closed.contains("id_rsa"), "{closed}");
+ assert!(closed.contains("prompt_length"));
+
+ let prompts = everything(&fold(cfg_with(true, false), None, &events));
+ assert!(prompts.contains("secret plan"));
+ assert!(!prompts.contains("id_rsa"));
+
+ let tools = everything(&fold(cfg_with(false, true), None, &events));
+ assert!(!tools.contains("secret plan"));
+ assert!(tools.contains("id_rsa"));
+
+ // Tool *output* has no gate in this slice: it is never exported at all.
+ let all = everything(&fold(cfg_with(true, true), None, &events));
+ assert!(!all.contains("PRIVATE KEY"));
+}
+
+#[test]
+fn the_gate_applies_before_the_queue() {
+ let cfg = cfg_with(false, false);
+ let signal = classify(
+ &cfg,
+ &StreamEvent::ToolCall { id: "t".into(), name: "write".into(), args: json!({"x": 1}) },
+ None,
+ );
+ assert_eq!(
+ signal,
+ Some(Signal::Event {
+ child: None,
+ event: EventSignal::ToolCall { id: "t".into(), name: "write".into(), args: None }
+ })
+ );
+}
+
+#[test]
+fn tool_decisions_name_their_source() {
+ let call = |id: &str, name: &str| StreamEvent::ToolCall {
+ id: id.into(),
+ name: name.into(),
+ args: json!({}),
+ };
+ let result = |id: &str, content: &str| StreamEvent::ToolResult {
+ id: id.into(),
+ content: content.into(),
+ is_error: content.starts_with("ERROR"),
+ diff: None,
+ };
+ let state = fold(
+ cfg_with(false, false),
+ None,
+ &[
+ call("a", "read"),
+ result("a", "file text"),
+ call("b", "bash"),
+ StreamEvent::PermissionRequest {
+ request_id: "p".into(),
+ tool_name: "bash".into(),
+ capability: "exec".into(),
+ path: None,
+ command: Some("ls".into()),
+ diff: None,
+ prompt_kind: "exec".into(),
+ offers_always: true,
+ },
+ result("b", "ERROR: tool 'bash' denied by user"),
+ call("c", "write"),
+ result("c", "ERROR: tool 'write' denied by project policy (see [tools] deny in x)"),
+ call("d", "edit"),
+ result("d", "ERROR: tool 'edit' denied: no edits on Fridays"),
+ call("e", "bash"),
+ result("e", "ERROR: command failed"),
+ ],
+ );
+ let decisions: Vec<(String, String)> = state
+ .logs
+ .iter()
+ .filter(|l| l.event_name == "jan_agent.tool_decision")
+ .map(|l| {
+ let s = |k| match attr(l, k) {
+ Some(AnyValue::Str(s)) => s.clone(),
+ other => panic!("{k}: {other:?}"),
+ };
+ (s("decision"), s("source"))
+ })
+ .collect();
+ let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
+ assert_eq!(
+ decisions,
+ vec![
+ pair("accept", "config"),
+ pair("reject", "user"),
+ pair("reject", "config"),
+ pair("reject", "hook"),
+ pair("accept", "config"),
+ ]
+ );
+ assert_eq!(
+ point(&state, "jan_agent.tool.count", &[("tool_name", "bash"), ("decision", "accept"), ("success", "false")]),
+ Some(PointValue::Int(1))
+ );
+ assert_eq!(
+ point(&state, "jan_agent.tool.count", &[("tool_name", "read"), ("success", "true")]),
+ Some(PointValue::Int(1))
+ );
+}
+
+#[test]
+fn a_subagents_signals_carry_its_run_and_the_parent_session() {
+ let wrapped = |event: StreamEvent| StreamEvent::Subagent {
+ run_id: "run-7".into(),
+ name: "scout".into(),
+ event: Box::new(event),
+ };
+ let state = fold(
+ cfg_with(false, false),
+ None,
+ &[
+ provenance(None, "sess-1"),
+ wrapped(provenance(Some("run-7"), "sess-1")),
+ wrapped(StreamEvent::Step { index: 1, max: 0 }),
+ wrapped(usage(4, 2, 0, 0)),
+ StreamEvent::SubagentEnd { run_id: "run-7".into(), name: "scout".into(), error: None },
+ ],
+ );
+ let request = state
+ .logs
+ .iter()
+ .find(|l| l.event_name == "jan_agent.api_request")
+ .unwrap();
+ assert_eq!(attr(request, "agent.run_id"), Some(&AnyValue::Str("run-7".into())));
+ assert_eq!(attr(request, "subagent.name"), Some(&AnyValue::Str("scout".into())));
+ assert_eq!(attr(request, "session.id"), Some(&AnyValue::Str("sess-1".into())));
+ assert_eq!(point(&state, "jan_agent.turn.count", &[("agent", "subagent")]), Some(PointValue::Int(1)));
+ assert!(state.logs.iter().any(|l| l.event_name == "jan_agent.subagent_result"));
+}
+
+#[test]
+fn an_error_after_a_request_counts_a_failed_request() {
+ let state = fold(
+ cfg_with(false, false),
+ None,
+ &[
+ provenance(None, "s"),
+ StreamEvent::Error { code: "error".into(), message: "HTTP 500".into() },
+ ],
+ );
+ let error = state.logs.iter().find(|l| l.event_name == "jan_agent.api_error").unwrap();
+ assert_eq!(error.severity_number, 17);
+ assert_eq!(attr(error, "model"), Some(&AnyValue::Str("stub-model".into())));
+ assert_eq!(
+ point(&state, "jan_agent.api_request.count", &[("success", "false")]),
+ Some(PointValue::Int(1))
+ );
+}
+
+#[test]
+fn session_id_can_be_kept_off_metric_points() {
+ let env = |key: &str| match key {
+ config::ENABLE_ENV => Some("1".into()),
+ "OTEL_METRICS_INCLUDE_SESSION_ID" => Some("false".into()),
+ _ => None,
+ };
+ let state = fold(config::resolve(&env, None, None).unwrap(), None, &[provenance(None, "s"), usage(1, 1, 0, 0)]);
+ for metric in state.metrics(3, 0) {
+ for p in metric.points {
+ assert!(p.attrs.iter().all(|(k, _)| k != "session.id"), "{}", metric.name);
+ }
+ }
+ // Events still carry it: they are the join key, one record each.
+ assert!(state.logs.iter().all(|l| attr(l, "session.id").is_some()));
+}
+
+/// A tokio listener standing in for a collector: records `(path, body)` of
+/// every POST, answers 200 or, when `stall`, never answers at all.
+async fn collector(stall: bool) -> (String, Arc<Mutex<Vec<(String, Vec<u8>)>>>) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let seen = Arc::new(Mutex::new(Vec::new()));
+ let sink = Arc::clone(&seen);
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ let sink = Arc::clone(&sink);
+ tokio::spawn(async move {
+ if stall {
+ tokio::time::sleep(Duration::from_secs(3600)).await;
+ return;
+ }
+ let mut buf = Vec::new();
+ let mut chunk = [0u8; 8192];
+ loop {
+ let n = stream.read(&mut chunk).await.unwrap_or(0);
+ if n == 0 {
+ return;
+ }
+ buf.extend_from_slice(&chunk[..n]);
+ let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") else {
+ continue;
+ };
+ let head = String::from_utf8_lossy(&buf[..end]).to_string();
+ let length: usize = head
+ .lines()
+ .find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse().unwrap_or(0)))
+ .unwrap_or(0);
+ if buf.len() < end + 4 + length {
+ continue;
+ }
+ let path = head.split_whitespace().nth(1).unwrap_or("").to_string();
+ sink.lock().unwrap().push((path, buf[end + 4..end + 4 + length].to_vec()));
+ let _ = stream
+ .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+ .await;
+ return;
+ }
+ });
+ }
+ });
+ (url, seen)
+}
+
+fn cfg_for(url: &str, protocol: &str) -> Config {
+ let url = url.to_string();
+ let protocol = protocol.to_string();
+ let env = move |key: &str| match key {
+ config::ENABLE_ENV => Some("1".to_string()),
+ "OTEL_EXPORTER_OTLP_ENDPOINT" => Some(url.clone()),
+ "OTEL_EXPORTER_OTLP_PROTOCOL" => Some(protocol.clone()),
+ "OTEL_EXPORTER_OTLP_TIMEOUT" => Some("500".to_string()),
+ _ => None,
+ };
+ config::resolve(&env, None, None).unwrap()
+}
+
+fn scripted_run(t: &Telemetry) {
+ t.send(Signal::RunStart {
+ session: Some("sess-1".into()),
+ run_id: None,
+ prompt: Some((5, None)),
+ });
+ t.observe(&provenance(None, "sess-1"));
+ t.observe(&StreamEvent::Step { index: 1, max: 0 });
+ t.observe(&usage(9, 4, 0, 0));
+ t.send(Signal::RunEnd {
+ session: Some("sess-1".into()),
+ run_id: None,
+ elapsed: Duration::from_millis(250),
+ });
+}
+
+#[tokio::test]
+async fn a_run_exports_metrics_and_logs_to_the_collector() {
+ let (url, seen) = collector(false).await;
+ let t = Telemetry::start(cfg_for(&url, "http/json"), None, "0.0.0-test");
+ scripted_run(&t);
+ t.shutdown(Duration::from_secs(5)).await;
+ let seen = seen.lock().unwrap().clone();
+ let body = |path: &str| -> Value {
+ let (_, body) = seen.iter().find(|(p, _)| p == path).unwrap_or_else(|| panic!("no POST {path} in {seen:?}"));
+ serde_json::from_slice(body).unwrap()
+ };
+ let metrics = body("/v1/metrics");
+ let names: Vec<&str> = metrics["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|m| m["name"].as_str().unwrap())
+ .collect();
+ for want in ["jan_agent.session.count", "jan_agent.token.usage", "jan_agent.turn.count", "jan_agent.active_time.total"] {
+ assert!(names.contains(&want), "{want} in {names:?}");
+ }
+ let resource = metrics["resourceMetrics"][0]["resource"]["attributes"].to_string();
+ assert!(resource.contains("jan-agent") && resource.contains("0.0.0-test"), "{resource}");
+ let logs = body("/v1/logs");
+ let events: Vec<&str> = logs["resourceLogs"][0]["scopeLogs"][0]["logRecords"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|r| r["eventName"].as_str().unwrap())
+ .collect();
+ assert_eq!(events, vec!["jan_agent.user_prompt", "jan_agent.api_request"]);
+}
+
+#[tokio::test]
+async fn protobuf_is_the_default_encoding() {
+ let (url, seen) = collector(false).await;
+ let t = Telemetry::start(cfg_for(&url, "http/protobuf"), None, "0.0.0-test");
+ scripted_run(&t);
+ t.shutdown(Duration::from_secs(5)).await;
+ let seen = seen.lock().unwrap().clone();
+ let (_, metrics) = seen.iter().find(|(p, _)| p == "/v1/metrics").expect("metrics POST");
+ // Binary, and carrying the metric names as length-delimited strings.
+ assert!(serde_json::from_slice::<Value>(metrics).is_err());
+ assert!(metrics.windows(21).any(|w| w == b"jan_agent.token.usage"));
+}
+
+#[tokio::test]
+async fn a_full_queue_drops_and_counts_without_waiting() {
+ // Nothing listens on port 9 (discard) in a test sandbox, and the worker is
+ // pinned on the stalled collector anyway: the point is the caller's side.
+ let (url, _seen) = collector(true).await;
+ let t = Telemetry::with_capacity(cfg_for(&url, "http/json"), None, "0", 4);
+ let started = Instant::now();
+ for _ in 0..10_000 {
+ t.observe(&StreamEvent::Step { index: 1, max: 0 });
+ }
+ assert!(started.elapsed() < Duration::from_secs(1), "{:?}", started.elapsed());
+ assert!(t.dropped() > 0);
+ // A stalled collector bounds shutdown too.
+ let started = Instant::now();
+ t.shutdown(Duration::from_millis(300)).await;
+ assert!(started.elapsed() < Duration::from_secs(2));
+}
+
+#[tokio::test]
+async fn a_dead_collector_is_not_the_runs_problem() {
+ // Bound, then closed: connecting is refused.
+ let port = {
+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ l.local_addr().unwrap().port()
+ };
+ let t = Telemetry::start(cfg_for(&format!("http://127.0.0.1:{port}"), "http/json"), None, "0");
+ scripted_run(&t);
+ t.shutdown(Duration::from_secs(2)).await;
+}
+
+#[test]
+fn refusals_are_read_off_the_loops_own_messages() {
+ assert_eq!(refusal_of("ERROR: tool 'bash' denied by user"), Some(Refusal::User));
+ assert_eq!(refusal_of("ERROR: user-scope subagent creation denied by user"), Some(Refusal::User));
+ assert_eq!(
+ refusal_of("ERROR: tool 'x' unavailable in plan_mode_read_only (plan mode is read-only)"),
+ Some(Refusal::Config)
+ );
+ assert_eq!(refusal_of("ERROR: tool 'x' denied: because"), Some(Refusal::Hook));
+ assert_eq!(refusal_of("ERROR: No such file"), None);
+ assert_eq!(refusal_of("denied by user"), None, "only a loop-produced ERROR result");
+}
+
+#[test]
+fn every_exported_metric_is_described() {
+ let state = fold(
+ cfg_with(false, false),
+ Some(Box::new(|_, _| Some(TokenRates { prompt_usd: 1.0, completion_usd: 1.0, cache_read_usd: None, cache_write_usd: None }))),
+ &[provenance(None, "s"), StreamEvent::Step { index: 1, max: 0 }, usage(1, 1, 0, 0)],
+ );
+ for metric in state.metrics(3, 5) {
+ assert!(!metric.description.is_empty() && !metric.unit.is_empty(), "{}", metric.name);
+ }
+ let dropped = state.metrics(3, 5).into_iter().find(|m| m.name == "jan_agent.telemetry.dropped");
+ assert_eq!(dropped.unwrap().points[0].value, PointValue::Int(5));
+ assert!(state.metrics(3, 0).iter().all(|m| m.name != "jan_agent.telemetry.dropped"));
+}
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index 3ea571687..a65a520a7 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -30,6 +30,11 @@ pub(crate) struct AgentToml {
pub skills: SkillsSection,
#[serde(default)]
pub plugins: PluginsSection,
+ /// `[telemetry]`: opt-in OTLP export. Wins over the global setting.
+ /// CLI-only: the desktop doesn't export telemetry yet.
+ #[cfg(feature = "cli")]
+ #[serde(default)]
+ pub telemetry: crate::core::agent::global_config::TelemetrySection,
/// `[[hooks]]` -- lifecycle commands this project runs around tool calls,
/// prompts, sessions and compactions. An array of tables rather than a
/// `[hooks]` map because several hooks may share one event.
@@ -744,6 +749,17 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ #[cfg(feature = "cli")]
+ #[test]
+ fn telemetry_section_is_optional_and_parsed() {
+ let root = unique_root("telemetry");
+ ensure_project(&root).expect("scaffold");
+ assert_eq!(load_agent_config(&root).unwrap().telemetry.enabled, None);
+ std::fs::write(agent_toml_path(&root), "[telemetry]\nenabled = false\n").unwrap();
+ assert_eq!(load_agent_config(&root).unwrap().telemetry.enabled, Some(false));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn load_roundtrips_template() {
let root = unique_root("roundtrip");
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 83f09652d..ea6995c96 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1571,6 +1571,20 @@ fn prepare_agent_session(
}
let cfg = load_agent_config(&project_root)?;
let permissions = permissions_from(&cfg);
+ // Opt-in OTLP export, decided once per process by the first session: every
+ // surface (TUI, `agent run`, RPC) starts here. agent.toml outranks the
+ // global setting and the env var outranks both (`otel::config`).
+ crate::core::agent::otel::init(
+ cfg.telemetry.enabled,
+ crate::core::agent::global_config::telemetry_setting(),
+ || {
+ let catalog = crate::core::cli::model_catalog::load();
+ Some(Box::new(move |provider: Option<&str>, model: &str| {
+ catalog.get(provider, model).and_then(|info| info.rates())
+ }))
+ },
+ crate::core::cli::updater::build_version(),
+ );
// Resolution order: --model flag, then agent.toml [agent].model, then the
// standalone global config (~/.jan/config.toml default_model / first provider
@@ -2107,6 +2121,7 @@ async fn run_agent_loop(
let mut updated_history = None;
while let Some(ev) = rx.recv().await {
report.observe(&ev);
+ crate::core::agent::otel::observe(&ev);
if format.is_stream_json() {
print_json_line(&ev);
}
diff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rs
index f99308a51..6cc094642 100644
--- a/src-tauri/src/core/cli/rpc.rs
+++ b/src-tauri/src/core/cli/rpc.rs
@@ -840,6 +840,7 @@ pub async fn serve() -> Result<(), String> {
let turn = active.as_mut().expect("active");
match message {
TurnMessage::Event(event) => {
+ crate::core::agent::otel::observe(&event);
if let StreamEvent::MessagesUpdated { messages } = &event { turn.updated_history = Some(messages.clone()); }
let wire = serde_json::to_value(&event).map_err(|e| e.to_string())?;
let method = format!("item/{}", wire["type"].as_str().ok_or("event has no tag")?);
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index ba66a2ee6..a0f979e72 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -9613,6 +9613,9 @@ async fn apply_stream_event(
current: &mut Option<CurrentRun>,
) {
note_claude_alias_if_engaged(app);
+ if let Some(ev) = &ev {
+ crate::core::agent::otel::observe(ev);
+ }
match ev {
Some(StreamEvent::Done { stop_reason, usage }) => {
app.on_done(stop_reason, usage);