| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::fmt::Write; |
| 3 | use std::sync::OnceLock; |
| 4 | |
| 5 | use codewhale_models::{ContentBlock, Message}; |
| 6 | use regex::Regex; |
| 7 | use serde_json::Value; |
| 8 | |
| 9 | const AGENT_TOOL: &str = "agent"; |
| 10 | const HEADING: &str = "Sub-agent handles from condensed turns (host-recorded with the last status \ |
| 11 | seen there; check live status with the agent tool before relying on one):"; |
| 12 | const MAX_HANDLES: usize = 32; |
| 13 | const MAX_ID_CHARS: usize = 96; |
| 14 | const MAX_STATUS_CHARS: usize = 48; |
| 15 | |
| 16 | #[derive(Default)] |
| 17 | struct Handles { |
| 18 | order: Vec<String>, |
| 19 | status: HashMap<String, Option<String>>, |
| 20 | } |
| 21 | |
| 22 | impl Handles { |
| 23 | fn note(&mut self, id: &str, status: Option<String>) { |
| 24 | let id = id.trim(); |
| 25 | if id.is_empty() |
| 26 | || id.chars().count() > MAX_ID_CHARS |
| 27 | || id.chars().any(|ch| ch.is_whitespace() || ch.is_control()) |
| 28 | { |
| 29 | return; |
| 30 | } |
| 31 | match self.status.get_mut(id) { |
| 32 | Some(known) => { |
| 33 | if status.is_some() { |
| 34 | *known = status; |
| 35 | } |
| 36 | } |
| 37 | None => { |
| 38 | self.order.push(id.to_string()); |
| 39 | self.status.insert(id.to_string(), status); |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | pub(super) fn section(condensed: &[Message]) -> String { |
| 46 | let handles = collect(condensed); |
| 47 | if handles.order.is_empty() { |
| 48 | return String::new(); |
| 49 | } |
| 50 | let mut text = format!("\n\n{HEADING}"); |
| 51 | for id in handles.order.iter().take(MAX_HANDLES) { |
| 52 | match handles.status.get(id).cloned().flatten() { |
| 53 | Some(status) => { |
| 54 | let _ = write!(text, "\n- {id} status={status}"); |
| 55 | } |
| 56 | None => { |
| 57 | let _ = write!(text, "\n- {id}"); |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | if handles.order.len() > MAX_HANDLES { |
| 62 | let _ = write!( |
| 63 | text, |
| 64 | "\n- ... {} more; list them with the agent tool", |
| 65 | handles.order.len() - MAX_HANDLES |
| 66 | ); |
| 67 | } |
| 68 | text |
| 69 | } |
| 70 | |
| 71 | fn collect(messages: &[Message]) -> Handles { |
| 72 | let agent_calls: HashSet<&str> = messages |
| 73 | .iter() |
| 74 | .flat_map(|message| &message.content) |
| 75 | .filter_map(|block| match block { |
| 76 | ContentBlock::ToolUse { id, name, .. } if name == AGENT_TOOL => Some(id.as_str()), |
| 77 | _ => None, |
| 78 | }) |
| 79 | .collect(); |
| 80 | let mut handles = Handles::default(); |
| 81 | for block in messages.iter().flat_map(|message| &message.content) { |
| 82 | match block { |
| 83 | ContentBlock::Text { text, .. } => carried_forward(text, &mut handles), |
| 84 | ContentBlock::ToolUse { name, input, .. } if name == AGENT_TOOL => { |
| 85 | visit_json(input, &mut handles, false); |
| 86 | } |
| 87 | ContentBlock::ToolResult { |
| 88 | tool_use_id, |
| 89 | content, |
| 90 | .. |
| 91 | } if agent_calls.contains(tool_use_id.as_str()) => { |
| 92 | match serde_json::from_str::<Value>(content) { |
| 93 | Ok(value) => visit_json(&value, &mut handles, true), |
| 94 | Err(_) => visit_text(content, &mut handles), |
| 95 | } |
| 96 | } |
| 97 | _ => {} |
| 98 | } |
| 99 | } |
| 100 | handles |
| 101 | } |
| 102 | |
| 103 | fn carried_forward(text: &str, handles: &mut Handles) { |
| 104 | let Some((_, rest)) = text.split_once(HEADING) else { |
| 105 | return; |
| 106 | }; |
| 107 | for line in rest.lines().skip(1) { |
| 108 | let Some(entry) = line.strip_prefix("- ") else { |
| 109 | break; |
| 110 | }; |
| 111 | let (id, status) = match entry.split_once(" status=") { |
| 112 | Some((id, status)) => (id, Some(status)), |
| 113 | None => (entry, None), |
| 114 | }; |
| 115 | if id.starts_with("...") { |
| 116 | break; |
| 117 | } |
| 118 | handles.note(id, status.and_then(clean_status)); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | fn visit_json(value: &Value, handles: &mut Handles, with_status: bool) { |
| 123 | match value { |
| 124 | Value::Object(map) => { |
| 125 | if let Some(id) = map.get("agent_id").and_then(Value::as_str) { |
| 126 | let status = with_status |
| 127 | .then(|| { |
| 128 | map.get("status") |
| 129 | .or_else(|| map.get("snapshot").and_then(|s| s.get("status"))) |
| 130 | .and_then(status_text) |
| 131 | }) |
| 132 | .flatten(); |
| 133 | handles.note(id, status); |
| 134 | } |
| 135 | if let Some(ids) = map.get("agent_ids").and_then(Value::as_array) { |
| 136 | for id in ids.iter().filter_map(Value::as_str) { |
| 137 | handles.note(id, None); |
| 138 | } |
| 139 | } |
| 140 | for nested in map.values() { |
| 141 | visit_json(nested, handles, with_status); |
| 142 | } |
| 143 | } |
| 144 | Value::Array(items) => { |
| 145 | for item in items { |
| 146 | visit_json(item, handles, with_status); |
| 147 | } |
| 148 | } |
| 149 | _ => {} |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | fn visit_text(text: &str, handles: &mut Handles) { |
| 154 | static PATTERNS: OnceLock<[Regex; 2]> = OnceLock::new(); |
| 155 | let [summarized, keyed] = PATTERNS.get_or_init(|| { |
| 156 | [ |
| 157 | Regex::new(r"(?m)^- (agent_[A-Za-z0-9_-]+) \([^)\n]*\) status=(\S+)").unwrap(), |
| 158 | Regex::new(r#"agent_id\\?["']?\s*[:=]\s*\\?["']?([A-Za-z0-9_-]+)"#).unwrap(), |
| 159 | ] |
| 160 | }); |
| 161 | for captures in summarized.captures_iter(text) { |
| 162 | handles.note(&captures[1], clean_status(&captures[2])); |
| 163 | } |
| 164 | for captures in keyed.captures_iter(text) { |
| 165 | handles.note(&captures[1], None); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | fn status_text(status: &Value) -> Option<String> { |
| 170 | match status { |
| 171 | Value::String(text) => clean_status(text), |
| 172 | Value::Object(map) => map.keys().next().and_then(|kind| clean_status(kind)), |
| 173 | _ => None, |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn clean_status(raw: &str) -> Option<String> { |
| 178 | let cleaned: String = raw |
| 179 | .trim() |
| 180 | .chars() |
| 181 | .filter(|ch| !ch.is_control()) |
| 182 | .take(MAX_STATUS_CHARS) |
| 183 | .collect(); |
| 184 | (!cleaned.is_empty()).then_some(cleaned) |
| 185 | } |
| 186 | |
| 187 | #[cfg(test)] |
| 188 | mod tests { |
| 189 | use super::*; |
| 190 | use codewhale_models::Role; |
| 191 | |
| 192 | fn call(id: &str, input: Value) -> Message { |
| 193 | Message { |
| 194 | role: Role::Assistant, |
| 195 | content: vec![ContentBlock::ToolUse { |
| 196 | id: id.to_string(), |
| 197 | name: AGENT_TOOL.to_string(), |
| 198 | input, |
| 199 | execution_id: None, |
| 200 | caller: None, |
| 201 | thought_signature: None, |
| 202 | }], |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | fn result(id: &str, content: &str) -> Message { |
| 207 | Message { |
| 208 | role: Role::User, |
| 209 | content: vec![ContentBlock::ToolResult { |
| 210 | tool_use_id: id.to_string(), |
| 211 | content: content.to_string(), |
| 212 | execution_id: None, |
| 213 | is_error: None, |
| 214 | content_blocks: None, |
| 215 | }], |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | fn text(role: Role, text: &str) -> Message { |
| 220 | Message { |
| 221 | role, |
| 222 | content: vec![ContentBlock::Text { |
| 223 | text: text.to_string(), |
| 224 | cache_control: None, |
| 225 | }], |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn spawned_subagent_ids_survive_two_compactions() { |
| 231 | let condensed = vec![ |
| 232 | text(Role::User, "fan out the audit"), |
| 233 | call( |
| 234 | "call_1", |
| 235 | serde_json::json!({"action": "start", "objective": "audit"}), |
| 236 | ), |
| 237 | result( |
| 238 | "call_1", |
| 239 | r#"{"agent_id":"agent_1a2b3c4d","agent_type":"worker","status":"running"}"#, |
| 240 | ), |
| 241 | call( |
| 242 | "call_2", |
| 243 | serde_json::json!({"action": "start", "objective": "docs"}), |
| 244 | ), |
| 245 | result( |
| 246 | "call_2", |
| 247 | "[sub-agent result summarized for parent context]\n- agent_docs (writer) status=completed\n result: done", |
| 248 | ), |
| 249 | call( |
| 250 | "call_3", |
| 251 | serde_json::json!({"action": "wait", "agent_ids": ["agent_1a2b3c4d"]}), |
| 252 | ), |
| 253 | result( |
| 254 | "call_3", |
| 255 | r#"{"settled":[{"agent_id":"agent_1a2b3c4d","status":{"failed":"boom"}}]}"#, |
| 256 | ), |
| 257 | result("unrelated", r#"{"agent_id":"agent_from_other_tool"}"#), |
| 258 | text(Role::Assistant, "agent_id=agent_prose_only is not a handle"), |
| 259 | ]; |
| 260 | let first = section(&condensed); |
| 261 | assert!(first.contains("- agent_1a2b3c4d status=failed"), "{first}"); |
| 262 | assert!(first.contains("- agent_docs status=completed"), "{first}"); |
| 263 | assert!(!first.contains("agent_from_other_tool"), "{first}"); |
| 264 | assert!(!first.contains("agent_prose_only"), "{first}"); |
| 265 | assert!( |
| 266 | first.find("agent_1a2b3c4d").unwrap() < first.find("agent_docs").unwrap(), |
| 267 | "first-seen order: {first}" |
| 268 | ); |
| 269 | |
| 270 | let checkpoint = crate::compaction::build_compaction_summary_block_text( |
| 271 | "model prose that forgot every id", |
| 272 | &first, |
| 273 | ); |
| 274 | let second = section(&[text(Role::User, &checkpoint)]); |
| 275 | assert_eq!(first, second); |
| 276 | } |
| 277 | |
| 278 | #[test] |
| 279 | fn no_agent_activity_adds_nothing_and_large_rosters_are_bounded() { |
| 280 | assert!(section(&[text(Role::User, "hello")]).is_empty()); |
| 281 | let mut messages = Vec::new(); |
| 282 | for index in 0..(MAX_HANDLES + 3) { |
| 283 | let id = format!("call_{index}"); |
| 284 | messages.push(call(&id, serde_json::json!({"action": "start"}))); |
| 285 | messages.push(result( |
| 286 | &id, |
| 287 | &format!(r#"{{"agent_id":"agent_{index:04}"}}"#), |
| 288 | )); |
| 289 | } |
| 290 | let text = section(&messages); |
| 291 | assert_eq!(text.matches("\n- agent_").count(), MAX_HANDLES); |
| 292 | assert!(text.contains("... 3 more"), "{text}"); |
| 293 | } |
| 294 | } |
| 295 |