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
Live activity: hold credential keys until their value arrives (N3) (#294)
Oleksandr Ivanchenko8b6338c4bda7
diff --git a/docs/live-activity.md b/docs/live-activity.mdindex f5c3495a..5c6cec31 100644--- a/docs/live-activity.md+++ b/docs/live-activity.md@@ -94,7 +94,15 @@ touched.So that a secret split across two `ThinkingDelta` chunks is matched whole, each chunk goes outwithout 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,+redacted with it. A credential whose value has not fully arrived is held with it: `password:` or+`password =` until the next word, `Authorization: Basic` / `Bearer` until the credential after+it, a bare `Bearer` before a word that is not all lowercase, and a quoted value+(`password = "two words"`) until its closing quote, all within the same 256-character cap. A+credential word in prose ("the password field is empty", "Bearer tokens expire") is held no+longer than any other word. By design, a bare `Bearer` before an all-lowercase word+(`Bearer abcdefghij`) is not held, so that word shows live. The saved text treats it as prose+too and leaves it unmasked, so the two match; `Authorization: Bearer` masks any word. This+keeps prose such as "Bearer tokens expire" or "bearer of bad news" from stalling the stream. 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, andwhen the turn finishes, fails or is cancelled. Chunks therefore split at spaces, a word or twobehind the model. The thinking text saved on the reply is redacted again as a whole when the stepdiff --git a/src/drivers/activity.rs b/src/drivers/activity.rsindex 39737f72..e1688229 100644--- a/src/drivers/activity.rs+++ b/src/drivers/activity.rs@@ -376,18 +376,90 @@ 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.+/// whitespace-separated words, moved back while the text before it ends in a credential whose+/// value is not all there yet (see [`value_pending`]), so `password: <value>` and+/// `Authorization: Bearer <token>` go out whole; 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));}+ while let Some(key) = value_pending(&text[..at], &text[at..]).filter(|&k| k < at) {+ at = key;+ }let longest = text.char_indices().rev().nth(MAX_HELD_THINKING.saturating_sub(1)).map_or(0, |(i, _)| i);at.max(longest)}+/// Where the credential starts when `head`, the text about to stream, ends before its value is+/// whole, so the key is held with it. The same pairs [`crate::profiles::classify::mask_credentials`]+/// masks: `password:` or `password =` with the value still to come (`next`, the held text, starts+/// it), `Authorization: Basic` (a scheme), a bare `Bearer` before a word that is not all lowercase+/// (so "Bearer tokens expire" is prose), and `password = "` with the closing quote still to come.+/// A credential word on its own ("the password field") is not held.+fn value_pending(head: &str, next: &str) -> Option<usize> {+ use crate::profiles::classify::is_credential_key;+ let is_key = |word: &str| -> bool {+ // `"password"` and `X-Api-Key` count; the name is the trailing run of name characters+ let word = word.strip_suffix(['"', '\'']).unwrap_or(word);+ let start = word+ .char_indices()+ .rev()+ .find(|&(_, c)| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))+ .map_or(0, |(i, c)| i + c.len_utf8());+ start < word.len() && is_credential_key(&word[start..].to_ascii_lowercase())+ };+ // the last words of `head` with their byte offsets; a held key is held from its word start+ let trimmed = head.trim_end();+ let mut words = trimmed.split_whitespace().rev().map(|w| (w.as_ptr() as usize - head.as_ptr() as usize, w));+ let next_word = next.split_whitespace().next().unwrap_or("");+ if let Some((at, last)) = words.next() {+ let bare = last.trim_end_matches(['"', '\'']);+ // `password:` / `password="`, or `password` before `= …` / `:…`+ if let Some(sep_free) = bare.strip_suffix([':', '=']) {+ if sep_free.is_empty() {+ if let Some((prev_at, prev)) = words.clone().next() {+ if is_key(prev) {+ return Some(prev_at);+ }+ }+ } else if is_key(sep_free) {+ return Some(at);+ }+ } else if next_word.starts_with([':', '=']) && is_key(last) {+ return Some(at);+ }+ let scheme = last.to_ascii_lowercase();+ if ["bearer", "basic", "digest"].contains(&scheme.as_str()) {+ // `Authorization: Basic` with the credential still to come+ if let Some((prev_at, prev)) = words.clone().next() {+ let key = prev.strip_suffix([':', '=']).unwrap_or("");+ if is_key(key) && key.to_ascii_lowercase().trim_end_matches(['"', '\'']).ends_with("authorization") {+ return Some(prev_at);+ }+ }+ if scheme == "bearer" && !next_word.is_empty() && !next_word.bytes().all(|b| b.is_ascii_lowercase()) {+ return Some(at);+ }+ }+ }+ // `password = "two words` with its closing quote still to come+ for (q, c) in trimmed.char_indices().rev().filter(|(_, c)| *c == '"' || *c == '\'') {+ if trimmed[q + 1..].contains(c) {+ continue;+ }+ let before = trimmed[..q].trim_end();+ let Some(key) = before.strip_suffix([':', '=']) else { continue };+ let key = key.trim_end();+ let word_at = key.char_indices().rev().find(|&(_, c)| c.is_whitespace()).map_or(0, |(i, c)| i + c.len_utf8());+ if is_key(&key[word_at..]) {+ return Some(word_at);+ }+ }+ None+}+enum Field {Single,Plural,@@ -669,6 +741,38 @@ pub fn thinking_note(engine: &str) -> Option<&'static str> {mod tests {use super::*;+ /// Rigel's B1 on #294: the hold is cut on char boundaries for any script. Every prefix of+ /// mixed CJK, accented Latin, emoji, NBSP and U+3000 text around `key:`, `password = "a b"`+ /// and `Authorization: Bearer X` gets a hold index without a panic, on a char boundary.+ #[test]+ fn hold_from_cuts_multibyte_text_on_char_boundaries() {+ let samples = [+ "Plan: 例: see résumé: then password: FAKEMB1value and 日本語: done",+ "例:\u{a0}password:\u{3000}FAKEMB3 résumé\u{a0}token=😀x 日本語\u{3000}secret: 値",+ "résumé\u{a0}password = \"a b 😀\" then 例\u{3000}password = \"日本 語\" ok",+ "😀 Authorization: Bearer X 例\u{3000}Authorization:\u{a0}Bearer\u{a0}Ünïcode 日本語",+ "\u{3000}é:\u{a0}例= 😀: \u{a0}Bearer 日本 \"例 api_key:é\u{3000}",+ ];+ for text in samples {+ for (k, _) in text.char_indices().chain([(text.len(), ' ')]) {+ let head = &text[..k];+ let at = hold_from(head);+ assert!(at <= head.len() && head.is_char_boundary(at), "{at} in {head:?}");+ }+ }+ }++ /// The documented trade-off: a bare `Bearer` before an all-lowercase word is prose to the+ /// masker ("Bearer tokens expire"), so it is neither held live nor masked when saved, and the+ /// live text still equals the saved text. `Authorization: Bearer` masks any word.+ #[test]+ fn bare_lowercase_bearer_is_prose_live_and_saved() {+ assert_eq!(value_pending("I send Bearer", "abcdefghij now"), None);+ assert_eq!(redact("I send Bearer abcdefghij now", &[]), "I send Bearer abcdefghij now");+ assert!(value_pending("send Authorization: Bearer", "abcdefghij now").is_some());+ assert!(!redact("send Authorization: Bearer abcdefghij now", &[]).contains("abcdefghij"));+ }+fn pending(id: &str, name: &str, args: Value) -> RuntimeEvent {RuntimeEvent::ToolCallPending { id: id.into(), name: name.into(), args }}diff --git a/src/server/activity.rs b/src/server/activity.rsindex a254f8e1..4cb0adc7 100644--- a/src/server/activity.rs+++ b/src/server/activity.rs@@ -319,4 +319,93 @@ mod tests {assert!(!saved.to_string().contains("hunter2"));drop(turn);}++ /// Every thinking chunk the turn streamed live (its own, not delegated), in order.+ fn live_thinking(events: &[RuntimeEvent]) -> Vec<String> {+ events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::Scoped { event, .. } => match event.as_ref() {+ RuntimeEvent::ThinkingDelta(t) => Some(t.clone()),+ _ => None,+ },+ _ => None,+ })+ .collect()+ }++ /// Streams `chunks` as one thinking step that a tool call ends; returns the live thinking+ /// chunks and, after each input chunk, how much of the text had streamed.+ fn stream_thinking(chunks: &[&str]) -> (Vec<String>, Vec<String>) {+ let (tx, mut rx) = broadcast::channel(8192);+ let tag = TurnTag { turn_id: "turn-n3".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };+ let turn = TurnActivity::start(tx, tag);+ let mut events = Vec::new();+ let mut so_far = Vec::new();+ for c in chunks {+ turn.relay(&RuntimeEvent::ThinkingDelta((*c).into()));+ events.extend(std::iter::from_fn(|| rx.try_recv().ok()));+ so_far.push(live_thinking(&events).concat());+ }+ turn.relay(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({"command": "ls"}) });+ let _ = turn.finish();+ events.extend(std::iter::from_fn(|| rx.try_recv().ok()));+ drop(turn);+ (live_thinking(&events), so_far)+ }++ /// Rigel's N3 on #288: `key: value` credentials with a space between the key and the value+ /// never stream raw, wherever the thinking text is cut: the key is held until its value is+ /// whole (a quoted one until its closing quote), then both go out masked.+ #[test]+ fn spaced_credentials_never_stream_raw() {+ let lines = [+ ("password: FAKEPW1secretvalue", ["FAKEPW1", "secretvalue"]),+ ("Authorization: Basic dXNlcjpwYXNzFAKEBASIC1", ["dXNl", "FAKEBASIC1"]),+ ("Authorization: Bearer FAKEBEARER1234567890abcdef", ["FAKEBEARER", "567890abcdef"]),+ ("password = \"FAKEPW2 with spaces inside\"", ["FAKEPW2", "spaces inside"]),+ // B1 on #294: multibyte names and words before the key+ ("例: résumé: password: FAKEMB2value 日本語", ["FAKEMB2", "MB2value"]),+ ];+ for (line, raws) in lines {+ let text = format!("First I check the setup. Then I send {line} to the server and wait for it.");+ let masked = crate::drivers::activity::redact(&text, &[]);+ assert!(raws.iter().all(|r| !masked.contains(r)), "not masked as a whole: {masked}");+ // cuts at every space and right after it, so at every word boundary and after+ // `:`, `=`, `Bearer` and `Basic`+ let mut cuts: Vec<usize> = text.match_indices(' ').flat_map(|(i, _)| [i, i + 1]).collect();+ cuts.dedup();+ let mut ways: Vec<Vec<String>> = cuts.iter().map(|&k| vec![text[..k].to_string(), text[k..].to_string()]).collect();+ // and all at once: one word, one character and three characters per chunk+ ways.push(text.split_inclusive(' ').map(String::from).collect());+ ways.push(text.chars().map(String::from).collect());+ ways.push(text.chars().collect::<Vec<_>>().chunks(3).map(|c| c.iter().collect()).collect());+ for chunks in ways {+ let chunks: Vec<&str> = chunks.iter().map(String::as_str).collect();+ let (live, _) = stream_thinking(&chunks);+ for delta in &live {+ for raw in raws {+ assert!(!delta.contains(raw), "{raw} streamed live in {delta:?}, chunks {chunks:?}");+ }+ }+ // nothing lost, nothing twice: the live text is the masked text+ assert_eq!(live.concat(), masked, "chunks {chunks:?}");+ }+ }+ }++ /// Prose that only names a credential ("the password field", "Bearer tokens") is held back+ /// no more than the usual last two words.+ #[test]+ fn credential_words_in_prose_are_not_held_longer() {+ let text = "the password field is empty, Bearer tokens expire and my token was old so the secret key rotates now ";+ let words: Vec<&str> = text.split_inclusive(' ').collect();+ let (live, so_far) = stream_thinking(&words);+ for (i, streamed) in so_far.iter().enumerate() {+ let expected: String = words[..(i + 1).saturating_sub(2)].concat();+ assert_eq!(streamed, &expected, "after word {i} ({:?})", words[i]);+ }+ assert_eq!(live.concat(), text);+ }+}