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.

fix(agent): per-session otel prompt.id, console exporter disables signal, shared refusal phrases

thinhlpg0f33120dc30b
diff --git a/docs/src/pages/docs/agent/telemetry.mdx b/docs/src/pages/docs/agent/telemetry.mdx
index a5c525b44..ae785f0d2 100644
--- a/docs/src/pages/docs/agent/telemetry.mdx
+++ b/docs/src/pages/docs/agent/telemetry.mdx
@@ -88,7 +88,7 @@ setup you already use for another agent works unchanged.
| `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_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER` | `otlp` | `none` turns that signal off. `console` isn't supported, because stdout carries the RPC and stream-json protocol: Jan logs a warning and doesn't export that signal. Any other value is treated the same way. |
| `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. |
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 66b8d3be1..06bca51d8 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -1329,7 +1329,7 @@ impl CompositeToolInvoker {
match self.prompt_subagent_create(&def.name).await {
PermissionDecision::AllowOnce | PermissionDecision::AllowAlways => {}
PermissionDecision::Deny => {
- return "ERROR: user-scope subagent creation denied by user".to_string()
+ return format!("ERROR: user-scope subagent creation {DENIED_BY_USER}")
}
}
}
@@ -1413,7 +1413,7 @@ impl CompositeToolInvoker {
match self.prompt_monitor_start(&spec).await {
PermissionDecision::AllowOnce | PermissionDecision::AllowAlways => {}
PermissionDecision::Deny => {
- return "ERROR: monitor start denied by user".to_string()
+ return format!("ERROR: monitor start {DENIED_BY_USER}")
}
}
}
@@ -1607,11 +1607,20 @@ impl CompositeToolInvoker {
}
}
+/// Refusal phrases the loop puts in a tool result it produced without running
+/// the tool. Shared with `otel::refusal_of`, so telemetry classifies refusals
+/// from the same constants the messages are built from.
+pub(crate) const DENIED_BY_USER: &str = "denied by user";
+pub(crate) const DENIED_BY_POLICY: &str = "denied by project policy";
+pub(crate) const HIDDEN_PATH_REFUSED: &str = "refused: the Jan home";
+pub(crate) const PLAN_MODE_UNAVAILABLE: &str = "unavailable in plan_mode_read_only";
+pub(crate) const HOOK_DENIED: &str = "denied: ";
+
/// Message for a tool blocked by the project's own deny list, naming the
/// exact config file so the block is actionable, not mysterious.
fn denied_by_policy_msg(name: &str, project_root: &std::path::Path) -> String {
format!(
- "ERROR: tool '{name}' denied by project policy (see [tools] deny in {})",
+ "ERROR: tool '{name}' {DENIED_BY_POLICY} (see [tools] deny in {})",
crate::core::agent::project::agent_toml_path(project_root).display()
)
}
@@ -1620,7 +1629,7 @@ fn denied_by_policy_msg(name: &str, project_root: &std::path::Path) -> String {
/// policy the user edits, so it points at the dedicated tools instead.
fn hidden_path_msg(name: &str) -> String {
format!(
- "ERROR: tool '{name}' refused: the Jan home (~/.jan) holds the agent's own \
+ "ERROR: tool '{name}' {HIDDEN_PATH_REFUSED} (~/.jan) holds the agent's own \
configuration and state and is hidden from every tool -- do not try to reach it \
another way. Skills and memory are available through the skill_*/memory_* tools."
)
@@ -1644,11 +1653,11 @@ fn hard_deny_msg(name: &str, reason: DenyReason, project_root: &std::path::Path)
/// to teach either of them. The hook's reason is what distinguishes it, which
/// is the part the user wrote to be read.
fn hook_denied_msg(name: &str, reason: &str) -> String {
- format!("ERROR: tool '{name}' denied: {reason}")
+ format!("ERROR: tool '{name}' {HOOK_DENIED}{reason}")
}
fn plan_mode_read_only_msg(name: &str) -> String {
- format!("ERROR: tool '{name}' unavailable in plan_mode_read_only (plan mode is read-only)")
+ format!("ERROR: tool '{name}' {PLAN_MODE_UNAVAILABLE} (plan mode is read-only)")
}
#[async_trait]
@@ -1917,7 +1926,7 @@ impl ToolInvoker for CompositeToolInvoker {
if !approved {
out.push(ToolOutcome::plain(
id,
- format!("ERROR: tool '{name}' denied by user"),
+ format!("ERROR: tool '{name}' {DENIED_BY_USER}"),
));
continue;
}
@@ -1979,7 +1988,7 @@ impl ToolInvoker for CompositeToolInvoker {
if !approved {
out.push(ToolOutcome::plain(
id,
- format!("ERROR: tool '{name}' denied by user"),
+ format!("ERROR: tool '{name}' {DENIED_BY_USER}"),
));
continue;
}
@@ -2084,7 +2093,7 @@ impl ToolInvoker for CompositeToolInvoker {
if !approved {
out.push(ToolOutcome::plain(
id,
- format!("ERROR: tool '{name}' denied by user"),
+ format!("ERROR: tool '{name}' {DENIED_BY_USER}"),
));
continue;
}
@@ -2266,7 +2275,7 @@ impl ToolInvoker for CompositeToolInvoker {
.await
}
PermissionDecision::Deny => {
- (format!("ERROR: tool '{name}' denied by user"), None, None)
+ (format!("ERROR: tool '{name}' {DENIED_BY_USER}"), None, None)
}
}
}
diff --git a/src-tauri/src/core/agent/otel/config.rs b/src-tauri/src/core/agent/otel/config.rs
index 37e96fa8b..46ea1fc24 100644
--- a/src-tauri/src/core/agent/otel/config.rs
+++ b/src-tauri/src/core/agent/otel/config.rs
@@ -20,6 +20,14 @@ pub enum Protocol {
}
impl Protocol {
+ /// Pick the encoder for this protocol.
+ pub fn encode(self, json: impl FnOnce() -> Vec<u8>, proto: impl FnOnce() -> Vec<u8>) -> Vec<u8> {
+ match self {
+ Protocol::HttpJson => json(),
+ Protocol::HttpProtobuf => proto(),
+ }
+ }
+
pub fn content_type(self) -> &'static str {
match self {
Protocol::HttpProtobuf => "application/x-protobuf",
@@ -110,19 +118,22 @@ pub fn resolve(
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.
+ // console exporter would corrupt it. Refused everywhere (the
+ // signal is not exported), so the same environment behaves the
+ // same on every surface and nothing is sent that was not asked for.
Some("console") => {
warnings.push(format!(
"OTEL_{upper}_EXPORTER=console is not supported (stdout carries the \
- agent protocol); {signal} are exported over OTLP instead"
+ agent protocol); {signal} are not exported"
));
+ return None;
}
Some(other) => {
warnings.push(format!(
- "OTEL_{upper}_EXPORTER={other} is not supported; {signal} are exported \
- over OTLP instead"
+ "OTEL_{upper}_EXPORTER={other} is not supported (only otlp and none); \
+ {signal} are not exported"
));
+ return None;
}
}
let url = get(&format!("OTEL_EXPORTER_OTLP_{upper}_ENDPOINT"))
@@ -319,7 +330,7 @@ mod tests {
}
#[test]
- fn grpc_and_console_fall_back_with_a_warning() {
+ fn grpc_falls_back_and_console_disables_the_signal() {
let c = resolve(
&env(&[
(ENABLE_ENV, "1"),
@@ -331,8 +342,21 @@ mod tests {
)
.unwrap();
assert_eq!(c.metrics.unwrap().protocol, Protocol::HttpProtobuf);
+ assert!(c.logs.is_none(), "console must not fall back to OTLP");
+ assert_eq!(c.warnings.len(), 2, "{:?}", c.warnings);
+ }
+
+ #[test]
+ fn an_unknown_exporter_disables_the_signal() {
+ let c = resolve(
+ &env(&[(ENABLE_ENV, "1"), ("OTEL_METRICS_EXPORTER", "prometheus")]),
+ None,
+ None,
+ )
+ .unwrap();
+ assert!(c.metrics.is_none());
assert!(c.logs.is_some());
- assert_eq!(c.warnings.len(), 3, "{:?}", c.warnings);
+ assert_eq!(c.warnings.len(), 1, "{:?}", c.warnings);
}
#[test]
diff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rs
index d2ccefa69..7acc2d678 100644
--- a/src-tauri/src/core/agent/otel/mod.rs
+++ b/src-tauri/src/core/agent/otel/mod.rs
@@ -172,27 +172,54 @@ impl Refusal {
}
/// 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.
+/// phrases are the loop's own constants (`r#loop::DENIED_BY_USER` and
+/// friends), the same ones its refusal messages are built from, so the two
+/// cannot drift apart. Only the head of an `ERROR:` result is read.
pub fn refusal_of(content: &str) -> Option<Refusal> {
+ use crate::core::agent::r#loop::{
+ DENIED_BY_POLICY, DENIED_BY_USER, HIDDEN_PATH_REFUSED, HOOK_DENIED, PLAN_MODE_UNAVAILABLE,
+ };
if !content.starts_with("ERROR:") {
return None;
}
let head: String = content.chars().take(300).collect();
- if head.contains("denied by user") {
+ 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")
+ } else if head.contains(DENIED_BY_POLICY)
+ || head.contains(PLAN_MODE_UNAVAILABLE)
+ || head.contains(HIDDEN_PATH_REFUSED)
{
Some(Refusal::Config)
- } else if head.starts_with("ERROR: tool '") && head.contains("' denied: ") {
+ } else if head.starts_with("ERROR: tool '") && head.contains(&format!("' {HOOK_DENIED}")) {
Some(Refusal::Hook)
} else {
None
}
}
+/// Strip credentials a provider error may echo back (bearer tokens, API keys,
+/// `key=` query parameters) before the message leaves the process.
+pub fn redact_secrets(message: &str) -> String {
+ static PATTERNS: OnceLock<Vec<(regex::Regex, &'static str)>> = OnceLock::new();
+ let patterns = PATTERNS.get_or_init(|| {
+ [
+ (r"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]{8,}", "${1}[REDACTED]"),
+ (r"(?i)((?:api[_-]?key|access[_-]?token|token|key|secret|password)[\x22']?\s*[=:]\s*[\x22']?)[^\s&\x22',}]{6,}", "${1}[REDACTED]"),
+ (r"\b(?:sk|pk|rk)-[A-Za-z0-9_-]{12,}", "[REDACTED]"),
+ (r"\bAIza[0-9A-Za-z_-]{20,}", "[REDACTED]"),
+ (r"\bgh[pousr]_[A-Za-z0-9]{20,}", "[REDACTED]"),
+ ]
+ .into_iter()
+ .map(|(p, r)| (regex::Regex::new(p).expect("valid redaction pattern"), r))
+ .collect()
+ });
+ let mut out = message.to_string();
+ for (re, replacement) in patterns {
+ out = re.replace_all(&out, *replacement).into_owned();
+ }
+ out
+}
+
fn truncate(s: &str, cap: usize) -> String {
if s.len() <= cap {
return s.to_string();
@@ -246,7 +273,7 @@ pub fn classify(cfg: &Config, event: &StreamEvent, child: Option<Child>) -> Opti
},
StreamEvent::Error { code, message } => EventSignal::Error {
code: code.clone(),
- message: truncate(message, ERROR_CAP),
+ message: truncate(&redact_secrets(message), ERROR_CAP),
},
StreamEvent::SubagentEnd { run_id, name, error } => {
return Some(Signal::Event {
@@ -494,7 +521,9 @@ pub struct State {
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>,
+ /// The prompt currently in flight, per session (`""` = no session id),
+ /// so overlapping RPC sessions never tag each other's records.
+ prompt_ids: HashMap<String, String>,
main_session: Option<String>,
}
@@ -515,7 +544,7 @@ impl State {
requests: HashMap::new(),
tools: HashMap::new(),
prompted: HashMap::new(),
- prompt_id: None,
+ prompt_ids: HashMap::new(),
main_session: None,
}
}
@@ -557,7 +586,7 @@ impl State {
if let Some(s) = session {
all.push(("session.id".into(), AnyValue::Str(s.to_string())));
}
- if let Some(p) = &self.prompt_id {
+ if let Some(p) = self.prompt_ids.get(session.unwrap_or("")) {
all.push(("prompt.id".into(), AnyValue::Str(p.clone())));
}
if let Some(c) = child {
@@ -588,7 +617,10 @@ impl State {
}
}
if let Some((length, text)) = prompt {
- self.prompt_id = Some(uuid::Uuid::new_v4().to_string());
+ self.prompt_ids.insert(
+ session.clone().unwrap_or_default(),
+ 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 =
@@ -951,10 +983,10 @@ impl Worker {
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),
- };
+ let body = target.protocol.encode(
+ || encode::metrics_json(&self.origin, &metrics),
+ || encode::metrics_proto(&self.origin, &metrics),
+ );
self.post(&target, body, "metrics").await;
}
@@ -967,10 +999,10 @@ impl Worker {
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),
- };
+ let body = target.protocol.encode(
+ || encode::logs_json(&self.origin, &logs),
+ || encode::logs_proto(&self.origin, &logs),
+ );
self.post(&target, body, "logs").await;
}
diff --git a/src-tauri/src/core/agent/otel/tests.rs b/src-tauri/src/core/agent/otel/tests.rs
index e3b4e692f..f14ca1a5a 100644
--- a/src-tauri/src/core/agent/otel/tests.rs
+++ b/src-tauri/src/core/agent/otel/tests.rs
@@ -508,3 +508,80 @@ fn every_exported_metric_is_described() {
assert_eq!(dropped.unwrap().points[0].value, PointValue::Int(5));
assert!(state.metrics(3, 0).iter().all(|m| m.name != "jan_agent.telemetry.dropped"));
}
+
+#[test]
+fn refusals_classify_the_messages_the_loop_builds() {
+ use crate::core::agent::r#loop::{
+ DENIED_BY_POLICY, DENIED_BY_USER, HIDDEN_PATH_REFUSED, HOOK_DENIED, PLAN_MODE_UNAVAILABLE,
+ };
+ // Built the way loop.rs builds them, from the same constants.
+ assert_eq!(refusal_of(&format!("ERROR: tool 'bash' {DENIED_BY_USER}")), Some(Refusal::User));
+ assert_eq!(
+ refusal_of(&format!("ERROR: tool 'bash' {DENIED_BY_POLICY} (see [tools] deny in x)")),
+ Some(Refusal::Config)
+ );
+ assert_eq!(
+ refusal_of(&format!("ERROR: tool 'read' {HIDDEN_PATH_REFUSED} (~/.jan) holds")),
+ Some(Refusal::Config)
+ );
+ assert_eq!(
+ refusal_of(&format!("ERROR: tool 'edit' {PLAN_MODE_UNAVAILABLE} (plan mode is read-only)")),
+ Some(Refusal::Config)
+ );
+ assert_eq!(refusal_of(&format!("ERROR: tool 'x' {HOOK_DENIED}nope")), Some(Refusal::Hook));
+}
+
+#[test]
+fn overlapping_sessions_keep_their_own_prompt_id() {
+ let cfg = Arc::new(cfg_with(false, false));
+ let mut state = State::new(Arc::clone(&cfg), None);
+ let start = |state: &mut State, s: &str| {
+ state.apply(
+ Instant::now(),
+ 1,
+ Signal::RunStart { session: Some(s.into()), run_id: None, prompt: Some((1, None)) },
+ )
+ };
+ start(&mut state, "sess-a");
+ start(&mut state, "sess-b");
+ // A request from session A arrives after B started its prompt.
+ for event in [provenance(None, "sess-a"), usage(10, 1, 0, 0)] {
+ if let Some(signal) = classify(&cfg, &event, None) {
+ state.apply(Instant::now(), 2, signal);
+ }
+ }
+ let logs = state.logs.clone();
+ let prompt = |s: &str| {
+ logs.iter()
+ .find(|l| {
+ l.event_name == "jan_agent.user_prompt"
+ && attr(l, "session.id") == Some(&AnyValue::Str(s.into()))
+ })
+ .and_then(|l| attr(l, "prompt.id"))
+ .cloned()
+ };
+ let request = logs.iter().find(|l| l.event_name == "jan_agent.api_request").unwrap();
+ assert_ne!(prompt("sess-a"), prompt("sess-b"));
+ assert_eq!(attr(request, "session.id"), Some(&AnyValue::Str("sess-a".into())));
+ assert_eq!(attr(request, "prompt.id").cloned(), prompt("sess-a"));
+}
+
+#[test]
+fn api_error_messages_are_redacted() {
+ let cfg = cfg_with(false, false);
+ let event = StreamEvent::Error {
+ code: "upstream".into(),
+ message: "401: invalid key sk-abcdefghijklmnop1234 (Authorization: Bearer abc.def.ghi12345) \
+ url https://x/v1?api_key=supersecret99&x=1"
+ .into(),
+ };
+ let Some(Signal::Event { event: EventSignal::Error { message, .. }, .. }) =
+ classify(&cfg, &event, None)
+ else {
+ panic!("error should classify");
+ };
+ assert!(!message.contains("sk-abcdefghijklmnop1234"), "{message}");
+ assert!(!message.contains("abc.def.ghi12345"), "{message}");
+ assert!(!message.contains("supersecret99"), "{message}");
+ assert!(message.contains("401: invalid key"), "{message}");
+}