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.

Live activity: mask secrets split across thinking chunks and credential objects (#288)

Oleksandr Ivanchenkof921ca098458
diff --git a/docs/live-activity.md b/docs/live-activity.md
index d26f7d25..f5c3495a 100644
--- a/docs/live-activity.md
+++ b/docs/live-activity.md
@@ -86,10 +86,19 @@ shows. Thinking that streams after the load arrives as `ThinkingDelta` as usual.
Titles, details and thinking text pass through redaction before they leave the server. That
includes the live stream: each `ThinkingDelta` chunk, every string in a `ToolCallPending`'s `args`
and in a `ToolCallCompleted`'s `result` is masked before it is broadcast, and an `args`/`result`
-field named like a credential (`api_key`, `password`, `token`, …) loses its value whole. Reply text
-(`TextDelta`) is not touched. A secret split across two `ThinkingDelta` chunks can't be matched in
-either one; the thinking text saved on the reply is redacted again as a whole when the step ends.
-Masked:
+field named like a credential (`api_key`, `password`, `token`, …) loses its value whole, whatever
+its type: a string, a number, an object or a list becomes `"[redacted]"` (`true` and `null` stay).
+A plural name (`tokens`, `passwords`) loses its value when it holds any text, so counts such as
+`"max_tokens": 100` stay readable, as does `"key": "Enter"`. Reply text (`TextDelta`) is not
+touched.
+
+So that a secret split across two `ThinkingDelta` chunks is matched whole, each chunk goes out
+without its last two words (at most 256 characters); they are joined to the next chunk and
+redacted with it. Held text is per turn (and per delegated turn), and it is all sent, redacted,
+before the thinking step ends: on the next reply text or tool call, an approval or human step, and
+when the turn finishes, fails or is cancelled. Chunks therefore split at spaces, a word or two
+behind the model. The thinking text saved on the reply is redacted again as a whole when the step
+ends. Masked:
- the turn's MCP secret values are masked as `********`
- `key=value` / `"key": "value"` credentials (password, token, secret, api_key, …)
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
index e1192bde..39737f72 100644
--- a/src/drivers/activity.rs
+++ b/src/drivers/activity.rs
@@ -8,7 +8,7 @@
//! redacted: known secret values, `key=value` credentials, bearer tokens and provider-looking keys
//! never leave this module.
-use super::events::RuntimeEvent;
+use super::events::{RuntimeEvent, TurnTag};
use serde::Serialize;
use serde_json::{json, Value};
use std::collections::HashMap;
@@ -22,6 +22,9 @@ pub const MAX_THINKING_CHARS: usize = 16_000;
pub const MAX_TITLE: usize = 160;
/// Longest step detail (characters).
pub const MAX_DETAIL: usize = 500;
+/// Most thinking text held back from the live stream at once (characters): the last two words of
+/// what streamed so far, so a secret split across two chunks is masked once it is whole.
+pub const MAX_HELD_THINKING: usize = 256;
/// One thing the bot did, or is doing, in a turn.
#[derive(Debug, Clone, Serialize, PartialEq)]
@@ -75,6 +78,9 @@ pub struct ActivityLog {
thinking_chars: usize,
dropped: usize,
secrets: Vec<String>,
+ /// Thinking text not yet streamed, per scope (the `Scoped` tags around it; none for the turn
+ /// itself), sent with that scope's next chunk or when the thinking step ends.
+ held: Vec<(Vec<TurnTag>, String)>,
}
fn now() -> String {
@@ -276,7 +282,9 @@ impl ActivityLog {
}
/// Masks secrets in every string of a JSON value; a field named like a credential
- /// (`api_key`, `password`, `token`, …) loses its value whole, the way `api_key=…` does.
+ /// (`api_key`, `password`, `token`, …) loses its value whole, whatever its type, the way
+ /// `api_key=…` does (`true` and `null` stay). A plural one (`tokens`, `secrets`) loses it when
+ /// it holds any text, so counts like `max_tokens: 100` stay readable.
fn redact_value(&self, value: &Value) -> Value {
match value {
Value::String(s) => Value::String(self.redact(s)),
@@ -284,9 +292,11 @@ impl ActivityLog {
Value::Object(map) => Value::Object(
map.iter()
.map(|(k, v)| {
- let secret_key = crate::profiles::classify::is_credential_key(&k.to_ascii_lowercase());
- let v = match v {
- Value::String(_) | Value::Number(_) if secret_key => Value::String("[redacted]".into()),
+ let v = match credential_field(k) {
+ // `"token": {"value": …}`, `"password": ["…"]`: the whole value
+ Some(Field::Single) if !matches!(v, Value::Bool(_) | Value::Null) => Value::String("[redacted]".into()),
+ // `"tokens": ["…"]`, but `"max_tokens": 100` and `{"input_tokens": 3}` stay
+ Some(Field::Plural) if has_string(v) => Value::String("[redacted]".into()),
_ => self.redact_value(v),
};
(k.clone(), v)
@@ -297,6 +307,64 @@ impl ActivityLog {
}
}
+ /// Takes one driver event and returns, in the order to broadcast them: thinking text held
+ /// back for the live stream that is due now, the steps the event started or changed, and the
+ /// event itself as it may go out (redacted; a thinking chunk without its last two words, which
+ /// are held until the next chunk, so a secret split across chunks is masked whole).
+ pub fn relay(&mut self, event: &RuntimeEvent) -> (Vec<RuntimeEvent>, Vec<Step>, Vec<RuntimeEvent>) {
+ let thinking = matches!(event.unscoped(), RuntimeEvent::ThinkingDelta(_));
+ let flushed = if thinking { Vec::new() } else { self.flush_held() };
+ let steps = self.observe(event);
+ // With no thinking step open (all steps used), a chunk is a status line: sent whole
+ let out = if thinking && self.thinking.is_some() {
+ self.hold_thinking(Vec::new(), event).into_iter().collect()
+ } else {
+ vec![self.redact_event(event)]
+ };
+ (flushed, steps, out)
+ }
+
+ /// A thinking chunk joined to what its scope held back, minus the new tail it holds back,
+ /// redacted; `None` when all of it is held. `scope` is the chain of `Scoped` tags around it.
+ fn hold_thinking(&mut self, scope: Vec<TurnTag>, event: &RuntimeEvent) -> Option<RuntimeEvent> {
+ match event {
+ RuntimeEvent::Scoped { tag, event } => {
+ let mut inner_scope = scope;
+ inner_scope.push(tag.clone());
+ let inner = self.hold_thinking(inner_scope, event)?;
+ Some(RuntimeEvent::Scoped { tag: tag.clone(), event: Box::new(inner) })
+ }
+ RuntimeEvent::ThinkingDelta(text) => {
+ let at = match self.held.iter().position(|(s, _)| *s == scope) {
+ Some(at) => at,
+ None => {
+ self.held.push((scope, String::new()));
+ self.held.len() - 1
+ }
+ };
+ let buf = &mut self.held[at].1;
+ buf.push_str(text);
+ let cut = hold_from(buf);
+ let ready: String = buf.drain(..cut).collect();
+ (!ready.is_empty()).then(|| RuntimeEvent::ThinkingDelta(self.redact(&ready)))
+ }
+ other => Some(self.redact_event(other)),
+ }
+ }
+
+ /// Everything held back, redacted, as thinking chunks of their own scope; nothing stays held.
+ pub fn flush_held(&mut self) -> Vec<RuntimeEvent> {
+ std::mem::take(&mut self.held)
+ .into_iter()
+ .filter(|(_, text)| !text.is_empty())
+ .map(|(scope, text)| {
+ scope.into_iter().rev().fold(RuntimeEvent::ThinkingDelta(self.redact(&text)), |event, tag| {
+ RuntimeEvent::Scoped { tag, event: Box::new(event) }
+ })
+ })
+ .collect()
+ }
+
/// What is saved on the reply as `meta.activity`.
pub fn to_json(&self) -> Value {
let mut v = json!({ "steps": self.steps.iter().map(Step::to_json).collect::<Vec<_>>() });
@@ -307,6 +375,46 @@ impl ActivityLog {
}
}
+/// Byte index where the held-back tail of streamed thinking starts: the last two
+/// whitespace-separated words (so `Bearer <token>` and `password: <value>` stay together), at most
+/// [`MAX_HELD_THINKING`] characters.
+fn hold_from(text: &str) -> usize {
+ let mut at = text.len();
+ for _ in 0..2 {
+ at = text[..at].trim_end().len();
+ at = text[..at].rfind(char::is_whitespace).map_or(0, |i| i + text[i..].chars().next().map_or(1, char::len_utf8));
+ }
+ let longest = text.char_indices().rev().nth(MAX_HELD_THINKING.saturating_sub(1)).map_or(0, |(i, _)| i);
+ at.max(longest)
+}
+
+enum Field {
+ Single,
+ Plural,
+}
+
+/// Whether a JSON field is named like a credential: `api_key`, `password`, `token` (`Single`), or
+/// a plural of one, `tokens`, `passwords` (`Plural`). `key` and `max_tokens` are neither.
+fn credential_field(name: &str) -> Option<Field> {
+ let name = name.to_ascii_lowercase();
+ if crate::profiles::classify::is_credential_key(&name) {
+ return Some(Field::Single);
+ }
+ name.strip_suffix('s')
+ .filter(|stem| crate::profiles::classify::is_credential_key(stem))
+ .map(|_| Field::Plural)
+}
+
+/// Whether any string is inside a JSON value.
+fn has_string(value: &Value) -> bool {
+ match value {
+ Value::String(_) => true,
+ Value::Array(items) => items.iter().any(has_string),
+ Value::Object(map) => map.values().any(has_string),
+ _ => false,
+ }
+}
+
/// At most `max` characters, with `…` when cut.
fn cut(text: &str, max: usize) -> String {
match text.char_indices().nth(max.saturating_sub(1)) {
@@ -569,6 +677,42 @@ mod tests {
RuntimeEvent::ToolCallCompleted { id: id.into(), result: json!({ "status": status }) }
}
+ /// Rigel's N1 on #286: a credential-named field holding an object or a list goes out masked
+ /// whole, while `key`, `max_tokens` and flags stay readable.
+ #[test]
+ fn credential_fields_lose_objects_and_lists_whole() {
+ let log = ActivityLog::default();
+ let args = json!({
+ "token": {"value": "objsecret111"},
+ "tokens": ["arrsecret222"],
+ "password": ["pw-in-array-333"],
+ "auth": {"api_key": {"nested": ["deepsecret444"]}},
+ "key": "Enter",
+ "max_tokens": 100,
+ "usage": {"input_tokens": 3, "output_tokens": 4},
+ "secret": true,
+ "api_key": null,
+ });
+ let RuntimeEvent::ToolCallPending { args: out, .. } = log.redact_event(&pending("1", "mcp__x__y", args)) else {
+ panic!("not a tool call")
+ };
+ let wire = out.to_string();
+ for secret in ["objsecret111", "arrsecret222", "pw-in-array-333", "deepsecret444"] {
+ assert!(!wire.contains(secret), "{secret} in {wire}");
+ }
+ assert_eq!(out["token"], "[redacted]");
+ assert_eq!(out["tokens"], "[redacted]");
+ assert_eq!(out["password"], "[redacted]");
+ assert_eq!(out["auth"]["api_key"], "[redacted]");
+ assert_eq!(out["key"], "Enter");
+ assert_eq!(out["max_tokens"], 100);
+ assert_eq!(out["usage"], json!({"input_tokens": 3, "output_tokens": 4}));
+ assert_eq!(out["secret"], true);
+ assert_eq!(out["api_key"], Value::Null);
+ assert!(!crate::profiles::classify::is_credential_key("key"));
+ assert!(!crate::profiles::classify::is_credential_key("max_tokens"));
+ }
+
#[test]
fn steps_follow_thinking_and_tool_runs() {
let mut log = ActivityLog::default();
diff --git a/src/server/activity.rs b/src/server/activity.rs
index 1683f05b..a254f8e1 100644
--- a/src/server/activity.rs
+++ b/src/server/activity.rs
@@ -65,6 +65,22 @@ impl TurnActivity {
self.with_log(|log| log.redact_event(event))
}
+ fn send_events(&self, events: impl IntoIterator<Item = RuntimeEvent>) {
+ for event in events {
+ let _ = self.sender.send(RuntimeEvent::Scoped { tag: self.tag.clone(), event: Box::new(event) });
+ }
+ }
+
+ /// Feeds a driver event to the log and broadcasts it, masked, with the steps it changed: any
+ /// thinking text held back is sent before the step it belongs to ends, and a thinking chunk
+ /// goes out without its last two words until the next chunk (see [`ActivityLog::relay`]).
+ pub fn relay(&self, event: &RuntimeEvent) {
+ let (held, steps, out) = self.with_log(|log| log.relay(event));
+ self.send_events(held);
+ self.send(steps);
+ self.send_events(out);
+ }
+
pub fn observe(&self, event: &RuntimeEvent) {
let steps = self.with_log(|log| log.observe(event));
self.send(steps);
@@ -76,7 +92,8 @@ impl TurnActivity {
}
pub fn wait(&self, kind: &'static str, ref_id: &str, title: &str, tool: Option<&str>) {
- let steps = self.with_log(|log| log.wait(kind, ref_id, title, tool));
+ let (held, steps) = self.with_log(|log| (log.flush_held(), log.wait(kind, ref_id, title, tool)));
+ self.send_events(held);
self.send(steps);
}
@@ -85,13 +102,15 @@ impl TurnActivity {
self.send(step);
}
- /// Ends the turn's open steps and returns what to save on the reply as `meta.activity`
+ /// Sends any thinking text still held back, ends the turn's open steps and returns what to save on the reply as `meta.activity`
/// (`None` when nothing happened).
pub fn finish(&self) -> Option<Value> {
- let (steps, saved) = self.with_log(|log| {
+ let (held, steps, saved) = self.with_log(|log| {
+ let held = log.flush_held();
let steps = log.finish();
- (steps, (!log.is_empty()).then(|| log.to_json()))
+ (held, steps, (!log.is_empty()).then(|| log.to_json()))
});
+ self.send_events(held);
self.send(steps);
saved
}
@@ -237,4 +256,67 @@ mod tests {
while rx.try_recv().is_ok() {}
drop(turn);
}
+
+ /// Rigel's N2 on #286: a secret split across two thinking chunks never streams raw, not even
+ /// its tail, and the text held back is all sent when the step ends, for the turn and for a
+ /// delegated turn alike, and when the turn ends while thinking.
+ #[test]
+ fn split_thinking_secrets_never_stream_raw() {
+ let (tx, mut rx) = broadcast::channel(64);
+ let tag = TurnTag { turn_id: "turn-split-redact".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };
+ let turn = TurnActivity::start(tx, tag);
+ turn.add_secrets(vec!["hunter2-QA-mcp-value".into()]);
+ let sub = TurnTag { turn_id: "turn-split-sub".into(), ..Default::default() };
+ let scoped = |e: RuntimeEvent| RuntimeEvent::Scoped { tag: sub.clone(), event: Box::new(e) };
+ let chunks = [
+ "key one: ghp_FAKEFAKEFAKE",
+ "FAKEFAKE0123456789abcd and the MCP one is hunter2-",
+ "QA-mcp-value, done.",
+ ];
+ for c in chunks {
+ turn.relay(&RuntimeEvent::ThinkingDelta(c.into()));
+ }
+ for c in chunks {
+ turn.relay(&scoped(RuntimeEvent::ThinkingDelta(c.into())));
+ }
+ turn.relay(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({"command": "ls"}) });
+ // a second thinking step the turn ends in the middle of
+ turn.relay(&RuntimeEvent::ThinkingDelta("then hunter2-QA".into()));
+ turn.relay(&RuntimeEvent::ThinkingDelta("-mcp-value end".into()));
+ let saved = turn.finish().unwrap();
+
+ let events: Vec<RuntimeEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
+ let wire: Vec<Value> = events.iter().map(RuntimeEvent::to_wire).collect();
+ // what streamed as thinking for the turn itself (`None`) or for a delegated turn
+ let streamed = |inner: Option<&str>| -> String {
+ events
+ .iter()
+ .filter_map(|e| match e {
+ RuntimeEvent::Scoped { event, .. } => match (event.as_ref(), inner) {
+ (RuntimeEvent::ThinkingDelta(t), None) => Some(t.clone()),
+ (RuntimeEvent::Scoped { tag, event }, Some(id)) if tag.turn_id == id => match event.as_ref() {
+ RuntimeEvent::ThinkingDelta(t) => Some(t.clone()),
+ _ => None,
+ },
+ _ => None,
+ },
+ _ => None,
+ })
+ .collect()
+ };
+ let all = serde_json::to_string(&wire).unwrap();
+ for raw in ["FAKEFAKE0123456789abcd", "ghp_FAKE", "hunter2-", "QA-mcp-value", "hunter2-QA"] {
+ assert!(!all.contains(raw), "{raw} streamed live: {all}");
+ }
+ // nothing is lost: the turn's and the delegated turn's text each arrive whole, masked
+ let whole = "key one: [redacted] and the MCP one is ********, done.";
+ assert_eq!(streamed(Some("turn-split-sub")), whole);
+ assert_eq!(streamed(None), format!("{whole}then ******** end"));
+ // the held text goes out before the thinking step's end, not after it
+ let first_end = wire.iter().position(|w| w["type"] == "activity" && w["data"]["step"]["kind"] == "thinking" && w["data"]["step"]["status"] == "ok").unwrap();
+ let last_chunk = wire.iter().rposition(|w| w["type"] == "ThinkingDelta" && w["data"].as_str().is_some_and(|d| d.contains("done."))).unwrap();
+ assert!(last_chunk < first_end, "held text sent after the step ended: {all}");
+ assert!(!saved.to_string().contains("hunter2"));
+ drop(turn);
+ }
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index fba115f0..ad2557dd 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2752,8 +2752,7 @@ async fn run_kwant_turn_inner(
_ => false,
};
side_effects |= visible;
- event_broadcast.activity.observe(&event);
- event_broadcast.send(event_broadcast.activity.redact_event(&event));
+ event_broadcast.activity.relay(&event);
}
None => break,
}