Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

29n mask-then-cut-2: mask the API driver's live content before cutting it; judge failures on the first 600 chars (#838)

Oleksandr Ivanchenkoa9359c4af2cf
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
index da43469e..990215b6 100644
--- a/src/drivers/activity.rs
+++ b/src/drivers/activity.rs
@@ -365,7 +365,8 @@ impl ActivityLog {
/// Masks secrets in a driver event before it is broadcast: thinking text, a tool call's
/// arguments and a finished tool's result (every string in them). Reply text passes as is.
- /// A failed tool's `error` is then cut to [`LIVE_ERROR_MAX`]: drivers send it whole.
+ /// A failed tool's `error` is then cut to [`LIVE_ERROR_MAX`], and a tool's `content` (the API
+ /// driver's) to [`crate::mcp::RECORD_RESULT_MAX_CHARS`]: drivers send both whole.
pub fn redact_event(&self, event: &RuntimeEvent) -> RuntimeEvent {
match event {
RuntimeEvent::ThinkingDelta(text) => RuntimeEvent::ThinkingDelta(self.redact(text)),
@@ -378,6 +379,10 @@ impl ActivityLog {
if let Some(Value::String(why)) = result.get_mut("error") {
*why = crate::mcp::truncate_text(why, LIVE_ERROR_MAX);
}
+ // 29n: the API driver's `content` too, at the length it was cut to before
+ if let Some(Value::String(text)) = result.get_mut("content") {
+ *text = crate::mcp::truncate_text(text, crate::mcp::RECORD_RESULT_MAX_CHARS);
+ }
RuntimeEvent::ToolCallCompleted { id: id.clone(), result }
}
RuntimeEvent::Scoped { tag, event } => {
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 85d1e509..180d6cdd 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -1391,23 +1391,8 @@ impl ApiDriver {
.send(RuntimeEvent::ToolCallPending { id: id.to_string(), name: name.to_string(), args: shown_args })
.await;
let outcome = session.call(caller, id, name, raw_args).await;
- let mut completed = json!({
- "status": outcome.status,
- "content": crate::mcp::truncate_text(&outcome.text, crate::mcp::RECORD_RESULT_MAX_CHARS),
- });
- // 15c: a call kwnt didn't send says so, so the failure line doesn't count it
- if let Some(n) = outcome.record.get("repeat_stopped") {
- completed["repeat_stopped"] = n.clone();
- }
let _ = event_tx
- .send(RuntimeEvent::ToolCallCompleted {
- id: id.to_string(),
- result: super::activity::with_page_title(
- completed,
- name,
- &outcome.text,
- ),
- })
+ .send(RuntimeEvent::ToolCallCompleted { id: id.to_string(), result: live_result(&outcome, name) })
.await;
results.push(&mut messages, id, name, outcome.model_text(), outcome.status == "ok");
}
@@ -1673,6 +1658,18 @@ impl Driver for ApiDriver {
}
}
+/// A finished call's `ToolCallCompleted`: its status and its whole text as `content`. kwnt masks
+/// it, then cuts it to [`crate::mcp::RECORD_RESULT_MAX_CHARS`] (`ActivityLog::redact_event`, 29n),
+/// so a secret across the cut is masked whole. A call kwnt didn't send says so (15c), so the
+/// failure line doesn't count it; an opened page carries its title.
+fn live_result(outcome: &crate::mcp::session::CallOutcome, name: &str) -> Value {
+ let mut completed = json!({ "status": outcome.status, "content": outcome.text });
+ if let Some(n) = outcome.record.get("repeat_stopped") {
+ completed["repeat_stopped"] = n.clone();
+ }
+ super::activity::with_page_title(completed, name, &outcome.text)
+}
+
#[cfg(test)]
mod attribution_tests {
use super::*;
@@ -1765,6 +1762,51 @@ mod tests {
use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
use std::sync::{Arc, Mutex};
+ /// 29n: a tool's whole text goes out as `content`, and kwnt masks it before it cuts it to 4000,
+ /// so a known secret across char 4000 is masked whole live (no part of it shows), ok or failed.
+ /// A text of 4000 chars is relayed as it is; 4001 is cut to 4000 plus the marker, as before.
+ #[test]
+ fn a_secret_across_4000_is_masked_whole_live() {
+ use crate::drivers::activity::ActivityLog;
+ use crate::mcp::session::CallOutcome;
+ let secret = "Qv7Lamp0Vole2Quiet8Fern4Moss6Rx";
+ let tool = "mcp__github__get_file_contents";
+ let outcome = |status: &'static str, text: &str, record: Value| CallOutcome {
+ text: text.to_string(),
+ status,
+ record,
+ remind: false,
+ hint: None,
+ };
+ // What the live stream gets for one call through the API driver, and its saved step
+ let relayed = |o: &CallOutcome| {
+ let mut log = ActivityLog::with_secrets(vec![secret.into()]);
+ log.relay(&RuntimeEvent::ToolCallPending { id: "c".into(), name: tool.into(), args: json!({}) });
+ let (_, steps, out) = log.relay(&RuntimeEvent::ToolCallCompleted { id: "c".into(), result: live_result(o, tool) });
+ let [RuntimeEvent::ToolCallCompleted { result, .. }] = &out[..] else { panic!("{out:?}") };
+ (result.clone(), steps[0].detail.clone())
+ };
+ let text = format!("{}{secret} tail", "é".repeat(3990));
+ for status in ["ok", "error"] {
+ let o = outcome(status, &text, json!({}));
+ assert_eq!(live_result(&o, tool), json!({"status": status, "content": text}), "the driver sends it whole");
+ let (live, saved) = relayed(&o);
+ assert_eq!(live, json!({"status": status, "content": format!("{}******** t… [truncated]", "é".repeat(3990))}));
+ for shown in [Some(live["content"].as_str().unwrap().to_string()), saved].into_iter().flatten() {
+ assert!(!shown.contains(&secret[..4]), "{}", shown.trim_start_matches('é'));
+ }
+ }
+ // The same bounds as before: 4000 stays, 4001 is cut
+ let whole = "é".repeat(crate::mcp::RECORD_RESULT_MAX_CHARS);
+ assert_eq!(relayed(&outcome("ok", &whole, json!({}))).0["content"], whole);
+ let over = format!("{whole}x");
+ assert_eq!(relayed(&outcome("ok", &over, json!({}))).0["content"], format!("{whole}… [truncated]"));
+ assert_eq!(crate::mcp::RECORD_RESULT_MAX_CHARS, 4000);
+ // 15c: a stopped repeat still says so
+ let (stopped, _) = relayed(&outcome("error", "stopped", json!({"repeat_stopped": 3})));
+ assert_eq!(stopped, json!({"status": "error", "content": "stopped", "repeat_stopped": 3}));
+ }
+
type Seen = Arc<Mutex<Vec<(HeaderMap, Value)>>>;
async fn mock(status: u16, reply: Value) -> (String, Seen) {
diff --git a/src/server/tool_failures.rs b/src/server/tool_failures.rs
index 5db095f9..a771d595 100644
--- a/src/server/tool_failures.rs
+++ b/src/server/tool_failures.rs
@@ -281,6 +281,9 @@ pub fn about_the_connection(result: &Value) -> bool {
/// A failed call → the connection failure it is, if any.
pub fn classify(name: &str, args: &Value, why: &str, servers: &[Server]) -> Option<Failure> {
+ // 29n: every driver's reason is judged on the same first 600 chars the live step shows, so a
+ // "401" or "unauthorized" deep in a long tool error isn't called a connection problem
+ let why = &crate::mcp::truncate_text(why, crate::drivers::activity::LIVE_ERROR_MAX);
let conn = connection_of(name, args, servers)?;
let cause = cause_of(&conn, why)?;
Some(Failure {
diff --git a/src/server/tool_failures/tests.rs b/src/server/tool_failures/tests.rs
index bfcbed9c..e43818fe 100644
--- a/src/server/tool_failures/tests.rs
+++ b/src/server/tool_failures/tests.rs
@@ -269,3 +269,26 @@ fn reasons_are_cut() {
let f = classify("mcp__github__x", &json!({}), &long, &servers()).unwrap();
assert!(f.detail.unwrap().chars().count() <= MAX_DETAIL + 1);
}
+
+/// 29n: a failed reason is judged on its first 600 chars, the part the live step shows, for every
+/// driver. "unauthorized" or a bare 503 deep in a long tool error is the tool's own text, not a
+/// connection problem; the same words inside the first 600 still are, and the line keeps them.
+#[test]
+fn only_the_first_600_chars_say_its_the_connection() {
+ let at = |n: usize, word: &str| format!("{}{word} rest of the tool's own error", "é".repeat(n));
+ let judged = |why: &str| classify("mcp__github__list_issues", &json!({}), why, &servers());
+ // After char 600 (whole, or straddling it): the tool's own error, no line
+ for why in [at(600, "unauthorized"), at(601, " 503 "), at(1500, "HTTP 401 Unauthorized"), at(598, "503")] {
+ assert!(judged(&why).is_none(), "{}", why.trim_start_matches('é'));
+ }
+ // Inside the first 600: still the connection's, as before
+ let signin = judged(&at(588, "unauthorized")).expect("unauthorized ending at char 600");
+ assert_eq!(signin.cause, Cause::SignIn);
+ let detail = signin.detail.unwrap();
+ assert_eq!(detail.chars().count(), MAX_DETAIL);
+ assert!(detail.starts_with("éé") && detail.ends_with("é…"), "{detail}");
+ let down = judged(&at(597, "503")).expect("503 ending at char 600");
+ assert_eq!(down.cause, Cause::Down);
+ assert_eq!(judged(&at(0, " 503 ")).unwrap().cause, Cause::Down);
+ assert_eq!(crate::drivers::activity::LIVE_ERROR_MAX, 600);
+}