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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Keep thinking text and secrets out of the activity list and live stream (#286)
Oleksandr Ivanchenkoe02e4b2b1d70
diff --git a/docs/live-activity.md b/docs/live-activity.mdindex 184dfd53..d26f7d25 100644--- a/docs/live-activity.md+++ b/docs/live-activity.md@@ -76,12 +76,20 @@ and details at 500. Steps still open when the turn ended are saved as `stopped`.A turn that is still running has no saved reply yet. `GET /api/turns` lists each running turn withits steps so far under `activity`, in the same shape (`{ "steps": [ <step>, … ] }`). Queued turnsand turns with no steps yet have no `activity`. Clients seed their live steps from it on load and-on every reconnect, so the working line shows the open step instead of "getting started". Thinking-text that streamed before the load is not included; the thinking step's title still shows.+on every reconnect, so the working line shows the open step instead of "getting started". Steps+here never carry `text`: thinking text that streamed before the load is not included (a running+thinking step's text isn't redacted until the step ends), and the thinking step's title still+shows. Thinking that streams after the load arrives as `ThinkingDelta` as usual.### Redaction-Titles, details and thinking text pass through redaction before they leave the server:+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:- the turn's MCP secret values are masked as `********`- `key=value` / `"key": "value"` credentials (password, token, secret, api_key, …)diff --git a/frontend/src/activity.ts b/frontend/src/activity.tsindex 17867581..1229e624 100644--- a/frontend/src/activity.ts+++ b/frontend/src/activity.ts@@ -84,12 +84,21 @@ export function applyActivity(prev: LiveActivity | undefined, turnId: string, st/*** After a load or reconnect: a running turn's steps so far, from `GET /api/turns` (its `activity`,* shaped like `meta.activity`). Each goes through `applyActivity`, so steps that already came live- * keep their place and a settled step never goes back to running. Null when there is nothing to add.+ * keep their place and a settled step never goes back to running. Steps there carry no thinking+ * `text`, so a step that already has its text keeps it. Null when there is nothing to add.*/export function seedActivity(prev: LiveActivity | undefined, turnId: string, raw: unknown): LiveActivity | null {const saved = parseActivityMeta({ activity: raw });if (!saved?.steps.length) return null;- return saved.steps.reduce<LiveActivity>((acc, step) => applyActivity(acc, turnId, step), prev?.turnId === turnId ? prev : { turnId, steps: [], thinking: {} });+ // `/api/turns` sends no thinking text, so a thinking step that already ended live keeps its own.+ const keepText = (acc: LiveActivity, step: ActivityStep) => {+ const text = step.text ?? acc.steps.find((s) => s.id === step.id)?.text;+ return text === undefined ? step : { ...step, text };+ };+ return saved.steps.reduce<LiveActivity>(+ (acc, step) => applyActivity(acc, turnId, keepText(acc, step)),+ prev?.turnId === turnId ? prev : { turnId, steps: [], thinking: {} },+ );}/** The thinking step text is streaming into right now, if any. */diff --git a/frontend/tests/activity.test.mjs b/frontend/tests/activity.test.mjsindex 6788a7b1..ddb07515 100644--- a/frontend/tests/activity.test.mjs+++ b/frontend/tests/activity.test.mjs@@ -111,6 +111,10 @@ test('a page opened mid-turn seeds the open step from /api/turns (ticket 4)', asconst merged = a.seedActivity(live, 't1', fromServer);assert.deepEqual(merged.steps.map((s) => [s.id, s.status]), [['b', 'ok'], ['a', 'ok']]);assert.equal(merged.thinking.x, 'hm');+ // `/api/turns` sends no thinking text: a thinking step that ended live keeps the text it had.+ const ended = { turnId: 't1', thinking: {}, steps: [step({ id: 'th', kind: 'thinking', status: 'ok', title: 'Thinking', text: 'saw it' })] };+ const reseeded = a.seedActivity(ended, 't1', { steps: [step({ id: 'th', kind: 'thinking', status: 'ok', title: 'Thinking' })] });+ assert.equal(reseeded.steps[0].text, 'saw it');// Nothing to add: no activity, junk, or no steps.assert.equal(a.seedActivity(undefined, 't1', undefined), null);assert.equal(a.seedActivity(undefined, 't1', { steps: [] }), null);diff --git a/src/drivers/activity.rs b/src/drivers/activity.rsindex 5cff16a3..e1192bde 100644--- a/src/drivers/activity.rs+++ b/src/drivers/activity.rs@@ -244,6 +244,59 @@ impl ActivityLog {changed}+ /// The steps so far as `GET /api/turns` lists them for a running turn: the same shape as+ /// `meta.activity`, but with no thinking `text`. A running thinking step's text isn't redacted+ /// until the step ends, and the text that streamed before a load isn't shown anyway.+ pub fn to_view_json(&self) -> Value {+ let mut v = self.to_json();+ if let Some(steps) = v["steps"].as_array_mut() {+ for step in steps.iter_mut().filter_map(Value::as_object_mut) {+ step.remove("text");+ }+ }+ v+ }++ /// 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.+ pub fn redact_event(&self, event: &RuntimeEvent) -> RuntimeEvent {+ match event {+ RuntimeEvent::ThinkingDelta(text) => RuntimeEvent::ThinkingDelta(self.redact(text)),+ RuntimeEvent::ToolCallPending { id, name, args } => {+ RuntimeEvent::ToolCallPending { id: id.clone(), name: name.clone(), args: self.redact_value(args) }+ }+ RuntimeEvent::ToolCallCompleted { id, result } => {+ RuntimeEvent::ToolCallCompleted { id: id.clone(), result: self.redact_value(result) }+ }+ RuntimeEvent::Scoped { tag, event } => {+ RuntimeEvent::Scoped { tag: tag.clone(), event: Box::new(self.redact_event(event)) }+ }+ other => other.clone(),+ }+ }++ /// 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.+ fn redact_value(&self, value: &Value) -> Value {+ match value {+ Value::String(s) => Value::String(self.redact(s)),+ Value::Array(items) => Value::Array(items.iter().map(|v| self.redact_value(v)).collect()),+ 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()),+ _ => self.redact_value(v),+ };+ (k.clone(), v)+ })+ .collect(),+ ),+ other => other.clone(),+ }+ }+/// 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<_>>() });diff --git a/src/profiles/classify.rs b/src/profiles/classify.rsindex 0b523235..c0f865ea 100644--- a/src/profiles/classify.rs+++ b/src/profiles/classify.rs@@ -397,7 +397,7 @@ fn is_aws_access_key_id(word: &str) -> bool {.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())}-fn is_credential_key(name: &str) -> bool {+pub(crate) fn is_credential_key(name: &str) -> bool {let after_separator = |k: &&str, whole: bool| {name.strip_suffix(*k).is_some_and(|rest| (whole && rest.is_empty()) || rest.ends_with(['_', '-']))diff --git a/src/server/activity.rs b/src/server/activity.rsindex d76a9131..1683f05b 100644--- a/src/server/activity.rs+++ b/src/server/activity.rs@@ -59,6 +59,12 @@ impl TurnActivity {crate::drivers::activity::hide_home_paths(&self.with_log(|log| log.redact(text)))}+ /// `event` as it may be broadcast: thinking text, tool arguments and tool results with the+ /// turn's secrets and credentials masked (see [`ActivityLog::redact_event`]).+ pub fn redact_event(&self, event: &RuntimeEvent) -> RuntimeEvent {+ self.with_log(|log| log.redact_event(event))+ }+pub fn observe(&self, event: &RuntimeEvent) {let steps = self.with_log(|log| log.observe(event));self.send(steps);@@ -108,10 +114,11 @@ pub fn approval_settled(turn_id: &str, ticket: &str, status: &'static str) {/// A running turn as `GET /api/turns` lists it, with its steps so far under `activity` (as/// `meta.activity`), so a page that loads or reconnects mid-turn shows what the bot is doing now-/// instead of starting from no steps. Queued turns and turns with no steps yet have none.+/// instead of starting from no steps. Queued turns and turns with no steps yet have none. Thinking+/// text is left out: a running thinking step's text isn't redacted until it ends.pub fn turn_view(turn: &super::turns::ActiveTurn) -> Value {let mut v = serde_json::to_value(turn).unwrap_or(Value::Null);- let steps = TurnActivity::find(&turn.turn_id).and_then(|t| t.with_log(|log| (!log.is_empty()).then(|| log.to_json())));+ let steps = TurnActivity::find(&turn.turn_id).and_then(|t| t.with_log(|log| (!log.is_empty()).then(|| log.to_view_json())));if let (Some(steps), Some(obj)) = (steps, v.as_object_mut()) {obj.insert("activity".into(), steps);}@@ -180,4 +187,54 @@ mod tests {assert!(turn_view(&active("some-other-turn")).get("activity").is_none());drop(turn);}++ /// Rigel's N1 on #284: a running turn's `GET /api/turns` view carries no thinking text and no+ /// secret from a tool call's arguments, and the live stream masks them too.+ #[test]+ fn listed_turn_has_no_thinking_text_or_raw_secrets() {+ let active = super::super::turns::ActiveTurn {+ turn_id: "turn-view-redact".into(),+ kwant_id: "k".into(),+ context_id: "c".into(),+ thread_id: None,+ state: "running".into(),+ since: chrono::Utc::now(),+ purpose: None,+ };+ let token = "ghp_abcdefghijklmnopqrstuvwxyz0123456789";+ let (tx, mut rx) = broadcast::channel(16);+ let tag = TurnTag { turn_id: "turn-view-redact".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };+ let turn = TurnActivity::start(tx, tag);+ turn.add_secrets(vec!["hunter2-mcp-value".into()]);+ let thinking = RuntimeEvent::ThinkingDelta(format!("I'll use {token} and hunter2-mcp-value"));+ turn.observe(&thinking);+ let v = turn_view(&active);+ let step = &v["activity"]["steps"][0];+ assert_eq!((step["kind"].as_str(), step["status"].as_str(), step["title"].as_str()), (Some("thinking"), Some("running"), Some("Thinking")));+ assert!(step.get("text").is_none(), "no thinking text on /api/turns: {step}");++ let call = RuntimeEvent::ToolCallPending {+ id: "1".into(),+ name: "Bash".into(),+ args: json!({"command": format!("curl -H 'Authorization: Bearer {token}' https://x.dev"), "api_key": "plainvalue123", "env": ["PASSWORD=hunter2-mcp-value"]}),+ };+ turn.observe(&call);+ let v = turn_view(&active).to_string();+ for secret in [token, "hunter2-mcp-value", "plainvalue123"] {+ assert!(!v.contains(secret), "{secret} in {v}");+ }+ assert!(v.contains("\"title\":\"Running `curl"), "the tool step still reads right: {v}");+ assert!(!v.contains("I'll use"), "thinking that ended on the tool call stays out too: {v}");++ // The live stream: thinking, tool args and tool results go out masked+ for event in [&thinking, &call, &RuntimeEvent::ToolCallCompleted { id: "1".into(), result: json!({"status": "ok", "content": format!("token={token}")}) }] {+ let wire = turn.redact_event(event).to_wire().to_string();+ for secret in [token, "hunter2-mcp-value", "plainvalue123"] {+ assert!(!wire.contains(secret), "{secret} streamed live: {wire}");+ }+ }+ assert_eq!(turn.redact_event(&RuntimeEvent::TextDelta("reply".into())), RuntimeEvent::TextDelta("reply".into()));+ while rx.try_recv().is_ok() {}+ drop(turn);+ }}diff --git a/src/server/routes.rs b/src/server/routes.rsindex cac4bf21..fba115f0 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2753,7 +2753,7 @@ async fn run_kwant_turn_inner(};side_effects |= visible;event_broadcast.activity.observe(&event);- event_broadcast.send(event);+ event_broadcast.send(event_broadcast.activity.redact_event(&event));}None => break,}