返回 CodeWhale
lifecycle.rs
根目录 / crates / engine / src / tools / subagent / lifecycle.rs
1 //! Bounded supervision over the existing manager and persisted continuation map.
2 use super::*;
3
4 pub(super) const COMPACT_STATUS_BYTES: usize = 8192;
5 pub(super) const COMPACT_SPAWN_BYTES: usize = 4096;
6 pub(super) const COMPACT_CANCEL_BYTES: usize = 4096;
7 const DETAIL_STATUS_BYTES: usize = 8 * 1024 - r#","action":"status""#.len();
8 const PEEK_RECENT_EVENTS_LIMIT: usize = 8;
9 pub(super) const PEEK_RECENT_ACTIVITY_LIMIT: usize = 12;
10 const PEEK_INPUT_PREVIEW_BYTES: usize = 240;
11 const PEEK_RESULT_PREVIEW_BYTES: usize = 200;
12 const PEEK_ASSISTANT_TEXT_BYTES: usize = 400;
13 const PEEK_MIN_RECENT_EVENTS: usize = 2;
14 const PEEK_TOOL_COUNT_KEYS: usize = 32;
15
16 fn is_edit_call(name: &str, input: &Value) -> bool {
17 const EDIT_NAMES: [&str; 6] = [
18 "write",
19 "edit",
20 "write_file",
21 "edit_file",
22 "apply_patch",
23 "fim_edit",
24 ];
25 let canonical = codewhale_execpolicy::canonical_action::canonical_action_alias(name, input);
26 EDIT_NAMES.contains(&name)
27 || EDIT_NAMES.contains(&canonical)
28 || (name == "pandoc_convert" && input.get("output_path").is_some())
29 }
30
31 fn activity_input_preview(input: &Value) -> String {
32 match input.get("command").and_then(Value::as_str) {
33 Some(command) => text_preview(command, PEEK_INPUT_PREVIEW_BYTES),
34 None => text_preview(
35 &serde_json::to_string(input).unwrap_or_default(),
36 PEEK_INPUT_PREVIEW_BYTES,
37 ),
38 }
39 }
40
41 fn activity_timestamp(ms: u64) -> Value {
42 i64::try_from(ms)
43 .ok()
44 .and_then(chrono::DateTime::from_timestamp_millis)
45 .map_or(Value::Null, |at| json!(at.to_rfc3339()))
46 }
47
48 pub(super) fn attach_peek_recent_activity(
49 row: &mut Value,
50 transcript: std::result::Result<Vec<Message>, String>,
51 last_activity_ms: Option<u64>,
52 ) {
53 let Some(obj) = row.as_object_mut() else {
54 return;
55 };
56 let messages = match transcript {
57 Ok(messages) => messages,
58 Err(reason) => {
59 obj.insert("recent_activity".into(), Value::Array(Vec::new()));
60 obj.insert(
61 "recent_activity_unavailable".into(),
62 json!(text_preview(&reason, 200)),
63 );
64 return;
65 }
66 };
67 let mut results: HashMap<&str, (&str, bool)> = HashMap::new();
68 for message in &messages {
69 for block in &message.content {
70 if let ContentBlock::ToolResult {
71 tool_use_id,
72 content,
73 is_error,
74 ..
75 } = block
76 {
77 results.insert(
78 tool_use_id.as_str(),
79 (content.as_str(), is_error.unwrap_or(false)),
80 );
81 }
82 }
83 }
84 let mut calls = Vec::new();
85 let mut by_tool: std::collections::BTreeMap<String, u64> = std::collections::BTreeMap::new();
86 let mut edit_calls = 0u64;
87 let mut last_assistant_text = None;
88 for message in &messages {
89 for block in &message.content {
90 match block {
91 ContentBlock::ToolUse {
92 id, name, input, ..
93 } => {
94 *by_tool.entry(text_preview(name, 64)).or_default() += 1;
95 if is_edit_call(name, input) {
96 edit_calls += 1;
97 }
98 calls.push((id.as_str(), name.as_str(), input));
99 }
100 ContentBlock::Text { text, .. }
101 if message.role == Role::Assistant && !text.trim().is_empty() =>
102 {
103 last_assistant_text = Some(text.trim());
104 }
105 _ => {}
106 }
107 }
108 }
109 let total = calls.len();
110 let recent: Vec<Value> = calls
111 .iter()
112 .skip(total.saturating_sub(PEEK_RECENT_ACTIVITY_LIMIT))
113 .map(|(id, name, input)| {
114 let mut entry = json!({
115 "tool": text_preview(name, 64),
116 "input_preview": activity_input_preview(input),
117 });
118 match results.get(id) {
119 Some((content, is_error)) => {
120 entry["result_preview"] =
121 json!(text_preview(content.trim(), PEEK_RESULT_PREVIEW_BYTES));
122 entry["is_error"] = json!(is_error);
123 }
124 None => {
125 entry["result_preview"] = Value::Null;
126 entry["is_error"] = json!(false);
127 entry["pending"] = json!(true);
128 }
129 }
130 entry
131 })
132 .collect();
133 let mut ranked: Vec<(String, u64)> = by_tool.into_iter().collect();
134 ranked.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
135 let other_tools: u64 = ranked
136 .iter()
137 .skip(PEEK_TOOL_COUNT_KEYS)
138 .map(|(_, count)| count)
139 .sum();
140 ranked.truncate(PEEK_TOOL_COUNT_KEYS);
141 let mut counts: serde_json::Map<String, Value> = ranked
142 .into_iter()
143 .map(|(name, count)| (name, json!(count)))
144 .collect();
145 if other_tools > 0 {
146 counts.insert("other".into(), json!(other_tools));
147 }
148 obj.insert("recent_activity".into(), Value::Array(recent));
149 obj.insert(
150 "last_assistant_text".into(),
151 last_assistant_text.map_or(Value::Null, |text| {
152 json!(text_preview(text, PEEK_ASSISTANT_TEXT_BYTES))
153 }),
154 );
155 obj.insert(
156 "work_summary".into(),
157 json!({
158 "tool_calls_total": total,
159 "tool_counts": counts,
160 "edit_calls": edit_calls,
161 "last_activity_at": last_activity_ms.map_or(Value::Null, activity_timestamp),
162 }),
163 );
164 }
165
166 fn peek_fits(payload: &Value) -> bool {
167 serde_json::to_vec(payload).is_ok_and(|bytes| bytes.len() <= COMPACT_STATUS_BYTES)
168 }
169
170 fn fit_peek_budget(payload: &mut Value) {
171 if peek_fits(payload) {
172 return;
173 }
174 while !peek_fits(payload) {
175 let Some(events) = payload
176 .get_mut("recent_events")
177 .and_then(Value::as_array_mut)
178 .filter(|events| events.len() > PEEK_MIN_RECENT_EVENTS)
179 else {
180 break;
181 };
182 events.remove(0);
183 payload["recent_events_truncated"] = json!(true);
184 }
185 let mut omitted = 0usize;
186 while !peek_fits(payload) {
187 let Some(activity) = payload
188 .get_mut("recent_activity")
189 .and_then(Value::as_array_mut)
190 .filter(|activity| !activity.is_empty())
191 else {
192 break;
193 };
194 activity.remove(0);
195 omitted += 1;
196 payload["recent_activity_omitted"] = json!(omitted);
197 payload["recent_activity_truncated"] =
198 json!("Oldest tool calls were dropped to fit the peek byte budget.");
199 }
200 if !peek_fits(payload)
201 && let Some(text) = payload.get("last_assistant_text").and_then(Value::as_str)
202 {
203 payload["last_assistant_text"] = json!(text_preview(text, 120));
204 }
205 }
206
207 pub(super) fn compact_transcript_handle(mut handle: Value) -> Value {
208 if let Some(preview) = handle.get("repr_preview").and_then(Value::as_str) {
209 handle["repr_preview"] = json!(text_preview(preview, 160));
210 }
211 handle
212 }
213
214 fn compact_event_entry(event: &AgentWorkerEvent) -> Value {
215 let mut entry = json!({
216 "seq": event.seq,
217 "status": agent_worker_status_name(event.status),
218 "timestamp_ms": event.timestamp_ms,
219 });
220 let obj = entry.as_object_mut().expect("event object");
221 if let Some(step) = event.step {
222 obj.insert("step".into(), json!(step));
223 }
224 if let Some(tool_name) = event.tool_name.as_deref() {
225 obj.insert("tool_name".into(), json!(text_preview(tool_name, 64)));
226 }
227 if let Some(message) = event.message.as_deref() {
228 obj.insert("message".into(), json!(text_preview(message, 160)));
229 }
230 entry
231 }
232
233 fn compact_event_json(event: &Value) -> Value {
234 let Some(source) = event.as_object() else {
235 return json!(text_preview(&event.to_string(), 160));
236 };
237 let mut obj = serde_json::Map::new();
238 for key in ["seq", "status", "timestamp_ms", "step"] {
239 if let Some(val) = source.get(key) {
240 obj.insert(key.to_string(), val.clone());
241 }
242 }
243 if let Some(tool_name) = source.get("tool_name").and_then(Value::as_str) {
244 obj.insert("tool_name".into(), json!(text_preview(tool_name, 64)));
245 }
246 if let Some(message) = source.get("message").and_then(Value::as_str) {
247 obj.insert("message".into(), json!(text_preview(message, 160)));
248 }
249 Value::Object(obj)
250 }
251
252 pub(super) fn attach_peek_recent_events(row: &mut Value, record: Option<&AgentWorkerRecord>) {
253 let Some(obj) = row.as_object_mut() else {
254 return;
255 };
256 match record {
257 Some(record) => {
258 let total = record.events.len();
259 let start = total.saturating_sub(PEEK_RECENT_EVENTS_LIMIT);
260 let recent: Vec<Value> = record
261 .events
262 .iter()
263 .skip(start)
264 .map(compact_event_entry)
265 .collect();
266 obj.insert("recent_events".into(), Value::Array(recent));
267 obj.insert("events_total".into(), json!(total));
268 }
269 None => {
270 obj.insert("recent_events".into(), Value::Array(Vec::new()));
271 obj.insert("events_total".into(), json!(0));
272 }
273 }
274 }
275
276 pub(super) fn compact_cancel_receipt(
277 snapshot: &SubAgentResult,
278 projection: &SubAgentSessionProjection,
279 record: Option<&AgentWorkerRecord>,
280 ) -> Value {
281 let usage = record.map(|rec| &rec.usage).unwrap_or(&projection.usage);
282 let handle = compact_transcript_handle(
283 serde_json::to_value(&projection.transcript_handle).unwrap_or(Value::Null),
284 );
285 let mut receipt = json!({
286 "action": "cancel",
287 "agent_id": projection.agent_id,
288 "name": text_preview(&projection.name, 64),
289 "role": snapshot.agent_type.as_str(),
290 "status": projection.status,
291 "terminal": projection.terminal,
292 "steps": snapshot.steps_taken,
293 "steps_taken": snapshot.steps_taken,
294 "duration_ms": snapshot.duration_ms,
295 "usage": {
296 "input_tokens": usage.input_tokens,
297 "output_tokens": usage.output_tokens,
298 "total_tokens": usage.total_tokens,
299 },
300 "transcript_handle": handle,
301 "cancelled_by_parent": snapshot.status == SubAgentStatus::Cancelled,
302 });
303 if let Some(summary) = snapshot
304 .result
305 .as_deref()
306 .map(str::trim)
307 .filter(|text| !text.is_empty())
308 {
309 receipt["summary"] = json!(text_preview(summary, 512));
310 }
311 if serde_json::to_vec(&receipt).map_or(true, |bytes| bytes.len() > COMPACT_CANCEL_BYTES)
312 && let Some(summary) = receipt.get("summary").and_then(Value::as_str)
313 {
314 receipt["summary"] = json!(text_preview(summary, 160));
315 }
316 receipt
317 }
318
319 pub(super) fn text_preview(value: &str, bytes: usize) -> String {
320 if value.len() <= bytes {
321 return value.to_string();
322 }
323 let mut end = bytes.saturating_sub(3).min(value.len());
324 while !value.is_char_boundary(end) {
325 end -= 1;
326 }
327 format!("{}...", &value[..end])
328 }
329
330 pub(super) fn reasoning_override_note(route: &ChildRouteReceipt) -> Option<String> {
331 let requested = route.requested_reasoning.trim();
332 if matches!(requested, "" | "inherit" | "auto") {
333 return None;
334 }
335 let effective = route
336 .effective_reasoning
337 .as_deref()
338 .map(str::trim)
339 .filter(|effort| !effort.is_empty());
340 if effective.is_some_and(|effort| effort.eq_ignore_ascii_case(requested)) {
341 return None;
342 }
343 let route_context = match route.resolved_profile_id.as_deref() {
344 Some(profile) => format!(" (route ceiling; profile '{profile}')"),
345 None => " (route ceiling)".to_string(),
346 };
347 let no_tier_context = match route.resolved_profile_id.as_deref() {
348 Some(profile) => format!(" (profile '{profile}')"),
349 None => String::new(),
350 };
351 Some(text_preview(
352 &match effective {
353 Some(effort) => {
354 format!(
355 "requested thinking '{requested}' runs as '{effort}' on {}/{}{route_context}",
356 route.provider_id, route.model_id
357 )
358 }
359 None => {
360 format!(
361 "requested thinking '{requested}' is not sent; {}/{}{no_tier_context} has no reasoning tier",
362 route.provider_id, route.model_id
363 )
364 }
365 },
366 240,
367 ))
368 }
369
370 pub(super) fn page(input: &Value) -> Result<(usize, usize), ToolError> {
371 let number = |key: &str, default| -> Result<usize, ToolError> {
372 match input.get(key) {
373 None => Ok(default),
374 Some(value) => value
375 .as_u64()
376 .and_then(|value| usize::try_from(value).ok())
377 .ok_or_else(|| {
378 ToolError::invalid_input(format!("{key} must be a nonnegative integer"))
379 }),
380 }
381 };
382 let offset = number("offset", 0)?;
383 let limit = number("limit", 20)?;
384 if !(1..=20).contains(&limit) {
385 return Err(ToolError::invalid_input("limit must be 1..20"));
386 }
387 Ok((offset, limit))
388 }
389
390 // Keep the same typed route receipt on every surface. Exceptionally long
391 // profile/model labels are previews; detail inspection retains their source.
392 pub(super) fn compact_child_route(mut route: Value) -> Value {
393 if serde_json::to_vec(&route).is_ok_and(|bytes| bytes.len() <= 1024) {
394 return route;
395 }
396 let Some(object) = route.as_object_mut() else {
397 return route;
398 };
399 for cap in [128, 64, 32, 16, 8] {
400 let mut truncated = false;
401 for value in object.values_mut() {
402 if let Value::String(text) = value
403 && text.len() > cap
404 {
405 *text = text_preview(text, cap);
406 truncated = true;
407 }
408 }
409 if truncated {
410 object.insert("truncated".into(), json!(true));
411 }
412 if serde_json::to_vec(&object).is_ok_and(|bytes| bytes.len() <= 1024) {
413 break;
414 }
415 }
416 route
417 }
418
419 pub(super) fn status_result(mut payload: Value, peek: bool) -> Result<ToolResult, ToolError> {
420 let action = if peek { "peek" } else { "status" };
421 payload["action"] = json!(action);
422 if peek {
423 fit_peek_budget(&mut payload);
424 }
425 let mut metadata = if payload.get("agent_id").is_some() {
426 json!({
427 "action": action, "agent_id": payload["agent_id"],
428 "status": payload["status"], "terminal": payload["terminal"],
429 "child_route": payload["child_route"],
430 })
431 } else {
432 json!({"action": action, "count": payload["count"]})
433 };
434 if let Some(unchanged) = payload.get("unchanged") {
435 metadata["unchanged"] = unchanged.clone();
436 }
437 let mut result = ToolResult::json(&payload)
438 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
439 result.metadata = Some(metadata);
440 Ok(result)
441 }
442
443 pub(super) fn compact_row(manager: &SubAgentManager, agent: &SubAgent) -> Value {
444 let record = manager.worker_records.get(&agent.id);
445 let current = manager.continuation_target(&agent.id);
446 let continuable = matches!(agent.status, SubAgentStatus::Interrupted(_))
447 && agent
448 .checkpoint
449 .as_ref()
450 .is_some_and(super::checkpoint_has_continuable_history);
451 let status = record
452 .map(|record| agent_worker_status_name(record.status))
453 .unwrap_or_else(|| {
454 if continuable {
455 "waiting_for_user"
456 } else {
457 subagent_status_name(&agent.status)
458 }
459 });
460 let mut row = json!({
461 "agent_id": agent.id, "name": text_preview(&agent.session_name, 64),
462 "role": agent.agent_type.as_str(),
463 "status": status, "terminal": agent.status != SubAgentStatus::Running,
464 "compact": true, "steps": agent.steps_taken, "steps_taken": agent.steps_taken,
465 "duration_ms": u64::try_from(agent.started_at.elapsed().as_millis()).unwrap_or(u64::MAX),
466 "needs_continuation": continuable, "usage": {},
467 });
468 let object = row.as_object_mut().expect("row is an object");
469 if let Some(record) = record {
470 if let Some(parent) = record
471 .parent_run_id
472 .as_ref()
473 .or(record.spec.parent_run_id.as_ref())
474 {
475 object.insert("parent_agent_id".into(), json!(parent));
476 }
477 object.insert("spawn_depth".into(), json!(record.spec.spawn_depth));
478 object.insert("max_spawn_depth".into(), json!(record.spec.max_spawn_depth));
479 if let Ok(profile) = serde_json::to_value(&record.spec.runtime_profile) {
480 let mut limits = serde_json::Map::new();
481 for key in ["max_steps", "wall_time_secs", "wall_deadline_ms"] {
482 if let Some(value) = profile.get(key) {
483 limits.insert(key.to_string(), value.clone());
484 }
485 }
486 object.insert("effective_limits".into(), Value::Object(limits));
487 }
488 let usage = &record.usage;
489 // These are this worker's receipts. Shared scope expenditure must not
490 // be added once per descendant when presenting a subtree total.
491 object.insert(
492 "usage".into(),
493 json!({
494 "input_tokens": usage.input_tokens, "output_tokens": usage.output_tokens,
495 "total_tokens": usage.total_tokens,
496 }),
497 );
498 object.insert("last_activity_ms".into(), json!(record.updated_at_ms));
499 if let Some(message) = &record.latest_message {
500 object.insert("activity".into(), json!(text_preview(message, 96)));
501 }
502 let mut verification = serde_json::to_value(&record.verification).unwrap_or(Value::Null);
503 if let Some(verdicts) = verification
504 .get_mut("deliverables")
505 .and_then(Value::as_array_mut)
506 {
507 let mut counts = std::collections::BTreeMap::<String, usize>::new();
508 for verdict in verdicts.iter() {
509 *counts
510 .entry(
511 verdict
512 .get("status")
513 .and_then(Value::as_str)
514 .unwrap_or("unknown")
515 .to_string(),
516 )
517 .or_default() += 1;
518 }
519 verdicts.sort_by_key(|verdict| {
520 matches!(
521 verdict.get("status").and_then(Value::as_str),
522 Some("present" | "pending")
523 )
524 });
525 let total = verdicts.len();
526 verification["deliverables_total"] = json!(total);
527 verification["deliverables_omitted"] = json!(total.saturating_sub(4));
528 verification["deliverable_counts"] = json!(counts);
529 }
530 bound_detail_value(&mut verification, 0, 4, &mut 1200);
531 object.insert("verification".into(), verification);
532 if let Some(route) = &record.spec.child_route {
533 object.insert(
534 "child_route".into(),
535 compact_child_route(serde_json::to_value(route).unwrap_or(Value::Null)),
536 );
537 }
538 // #6194 item 5: live declared-vs-observed write surfacing. The child
539 // declares deliverables at spawn and the registry records every
540 // successful scoped write; the parent sees the diff while the child
541 // is still alive instead of only in the post-mortem receipt.
542 if record.spec.runtime_profile.permissions.write {
543 const MAX_LISTED_WRITES: usize = 4;
544 let declared: Vec<String> = record
545 .spec
546 .launch_manifest
547 .as_ref()
548 .map(|manifest| {
549 manifest
550 .deliverables
551 .iter()
552 .take(MAX_LISTED_WRITES)
553 .cloned()
554 .collect()
555 })
556 .unwrap_or_default();
557 let declared_total = record
558 .spec
559 .launch_manifest
560 .as_ref()
561 .map(|manifest| manifest.deliverables.len())
562 .unwrap_or(0);
563 let observed: Vec<String> = record
564 .delivery_evidence
565 .observed_writes
566 .iter()
567 .take(MAX_LISTED_WRITES)
568 .cloned()
569 .collect();
570 let observed_total = record.delivery_evidence.observed_writes.len();
571 if declared_total > 0 || observed_total > 0 {
572 object.insert(
573 "write_progress".into(),
574 json!({
575 "declared": declared,
576 "declared_total": declared_total,
577 "observed": observed,
578 "observed_total": observed_total,
579 }),
580 );
581 }
582 }
583 }
584 if let Some(source) = manager.continuation_source(&agent.id) {
585 object.insert("resumed_from".into(), json!(source));
586 }
587 match current {
588 Ok(target) if target != agent.id => {
589 object.insert("resumed_as".into(), json!(target));
590 }
591 Err(error) => {
592 object.insert(
593 "lineage_error".into(),
594 json!(text_preview(&error.to_string(), 120)),
595 );
596 }
597 _ => {}
598 }
599 if let Some(input) = &agent.needs_input {
600 object.insert(
601 "needs_input".into(),
602 json!(text_preview(&input.question, 160)),
603 );
604 }
605 let stop_reason = match &agent.status {
606 SubAgentStatus::Failed(reason) | SubAgentStatus::Interrupted(reason) => Some(reason),
607 _ => agent
608 .result
609 .as_ref()
610 .filter(|_| agent.status != SubAgentStatus::Running),
611 };
612 if let Some(reason) = stop_reason {
613 object.insert("summary".into(), json!(text_preview(reason, 160)));
614 }
615 if serde_json::to_vec(&row).is_ok_and(|bytes| bytes.len() > 3072) {
616 // A verdict containing highly escaped prose can exceed its raw-byte
617 // allowance. Keep the authoritative verdict status and name the
618 // omitted detail, rather than returning a page that cannot advance.
619 let status = row
620 .pointer("/verification/status")
621 .cloned()
622 .unwrap_or(Value::Null);
623 let counts = row.pointer("/verification/deliverable_counts").cloned();
624 let total = row.pointer("/verification/deliverables_total").cloned();
625 row["verification"] = json!({"status": status, "deliverable_counts": counts, "deliverables_total": total, "detail_required": true});
626 }
627 row
628 }
629
630 pub(super) fn compact_roster(
631 manager: &SubAgentManager,
632 input: &Value,
633 session: &str,
634 archived: bool,
635 peek: bool,
636 ) -> Result<Value, ToolError> {
637 let (offset, limit) = page(input)?;
638 let mut agents = manager
639 .agents
640 .values()
641 .filter(|agent| manager.agent_is_owned_by_session(agent, session))
642 .filter(|agent| archived || !manager.is_from_prior_session(agent))
643 .collect::<Vec<_>>();
644 // Live and waiting work comes first; tie-break with immutable ids, so a
645 // page is reproducible for unchanged state even across process restarts.
646 agents.sort_by(|a, b| {
647 (a.status != SubAgentStatus::Running, &a.id)
648 .cmp(&(b.status != SubAgentStatus::Running, &b.id))
649 });
650 let mut counts = std::collections::BTreeMap::<&str, usize>::new();
651 let mut total_tokens = 0_u64;
652 let mut reported_workers = 0_usize;
653 let mut unreported_usage_workers = 0_usize;
654 let mut partially_reported_workers = 0_usize;
655 let mut active_workers = 0_usize;
656 for agent in &agents {
657 *counts
658 .entry(subagent_status_name(&agent.status))
659 .or_default() += 1;
660 let record = manager.worker_records.get(&agent.id);
661 active_workers += usize::from(
662 agent.status == SubAgentStatus::Running
663 || record.is_some_and(|record| !record.status.is_terminal()),
664 );
665 if let Some(record) = record {
666 if let Some(tokens) = record.usage.total_tokens {
667 total_tokens = total_tokens.saturating_add(tokens);
668 reported_workers += 1;
669 if record.has_unreported_usage {
670 partially_reported_workers += 1;
671 }
672 }
673 if record.has_unreported_usage {
674 unreported_usage_workers += 1;
675 }
676 }
677 }
678 let total = agents.len();
679 // A stable header carries field names once. Null cells mean absent or
680 // unreported values; a reported zero remains a numeric zero.
681 let columns = [
682 "agent_id",
683 "parent_agent_id",
684 "resumed_from",
685 "resumed_as",
686 "spawn_depth",
687 "status",
688 "duration_ms",
689 "total_tokens",
690 "last_activity_ms",
691 "activity",
692 "needs_input",
693 "needs_continuation",
694 "verification",
695 "summary",
696 "lineage_error",
697 ];
698 let mut rows = agents
699 .into_iter()
700 .skip(offset)
701 .take(limit)
702 .map(|agent| {
703 let mut row = compact_row(manager, agent);
704 let total_tokens = row
705 .pointer("/usage/total_tokens")
706 .cloned()
707 .unwrap_or(Value::Null);
708 row["total_tokens"] = total_tokens;
709 if let Some(record) = manager.worker_records.get(&agent.id) {
710 let mut verification =
711 json!({"status": text_preview(&record.verification.status, 64)});
712 if !matches!(
713 record.verification.status.as_str(),
714 "self_report_only" | "deliverables_present"
715 ) && !record.verification.summary.is_empty()
716 {
717 verification["summary"] =
718 json!(text_preview(&record.verification.summary, 160));
719 }
720 if let Some(counts) = row
721 .pointer("/verification/deliverable_counts")
722 .filter(|value| value.as_object().is_some_and(|counts| !counts.is_empty()))
723 {
724 verification["deliverable_counts"] = counts.clone();
725 }
726 row["verification"] = verification;
727 }
728 Value::Array(
729 columns
730 .iter()
731 .map(|column| row.get(*column).cloned().unwrap_or(Value::Null))
732 .collect(),
733 )
734 })
735 .collect::<Vec<_>>();
736 loop {
737 let shown = rows.len();
738 let next = offset.saturating_add(shown);
739 let payload = json!({
740 "action": if peek { "peek" } else { "status" }, "compact": true,
741 "count": shown, "total_count": total, "status_counts": counts,
742 "usage": {
743 "total_tokens": total_tokens,
744 "reported_workers": reported_workers,
745 "unreported_usage_workers": unreported_usage_workers,
746 "partially_reported_workers": partially_reported_workers,
747 "complete": active_workers == 0
748 && unreported_usage_workers == 0
749 && reported_workers == total,
750 "workers": total,
751 },
752 "columns": columns, "agents": rows, "offset": offset,
753 "next_offset": (next < total).then_some(next),
754 "omitted": total.saturating_sub(shown),
755 "detail_hint": "Rows follow columns. Inspect with agent_id and detail=true.",
756 });
757 if serde_json::to_vec(&payload)
758 .map_err(|error| ToolError::execution_failed(error.to_string()))?
759 .len()
760 <= COMPACT_STATUS_BYTES
761 {
762 return Ok(payload);
763 }
764 if rows.pop().is_none() {
765 return Err(ToolError::execution_failed(
766 "Status envelope exceeds its byte limit",
767 ));
768 }
769 }
770 }
771
772 // Bound arbitrary message/tool-input JSON as it is copied into a diagnostic
773 // page. The transcript handle remains the authoritative unabridged source.
774 fn bound_detail_value(value: &mut Value, offset: usize, limit: usize, budget: &mut usize) {
775 if *budget == 0 {
776 *value = json!("[omitted]");
777 return;
778 }
779 match value {
780 Value::String(text) => {
781 *text = text_preview(text, (*budget).min(1024));
782 *budget = budget.saturating_sub(text.len());
783 }
784 Value::Array(items) => {
785 *items = std::mem::take(items)
786 .into_iter()
787 .skip(offset)
788 .take(limit)
789 .collect();
790 for item in items {
791 bound_detail_value(item, 0, limit, budget);
792 }
793 }
794 Value::Object(object) => {
795 object.retain(|key, _| key.len() <= 128);
796 for child in object.values_mut() {
797 bound_detail_value(child, 0, limit, budget);
798 }
799 }
800 _ => {
801 *budget = budget.saturating_sub(16);
802 }
803 }
804 }
805
806 fn detail_fits(page: &Value) -> bool {
807 serde_json::to_vec(page).is_ok_and(|bytes| bytes.len() <= DETAIL_STATUS_BYTES)
808 }
809
810 fn truncate_event_page(detail: &mut Value, offset: usize, retained: usize) {
811 if let Some(events) = detail
812 .get_mut("recent_events")
813 .and_then(Value::as_array_mut)
814 && events.len() > retained
815 {
816 events.truncate(retained);
817 detail["events_next_offset"] = json!(offset.saturating_add(retained));
818 detail["events_omitted"] = json!(true);
819 }
820 }
821
822 pub(super) fn bounded_detail(value: Value, compact: Value, offset: usize, limit: usize) -> Value {
823 // The typed handle is the retrieval authority, not diagnostic prose.
824 // Large earlier fields must never consume its lookup coordinates.
825 let transcript_handle = value
826 .get("transcript_handle")
827 .filter(|handle| !handle.is_null())
828 .cloned()
829 .map(compact_transcript_handle);
830 let mut verification = value.get("verification").cloned().unwrap_or(Value::Null);
831 if let Some(verdicts) = verification
832 .get_mut("deliverables")
833 .and_then(Value::as_array_mut)
834 {
835 let total = verdicts.len();
836 *verdicts = std::mem::take(verdicts)
837 .into_iter()
838 .skip(offset)
839 .take(limit)
840 .collect();
841 verification["deliverables_total"] = json!(total);
842 verification["deliverables_next_offset"] = (offset.saturating_add(limit) < total)
843 .then_some(offset.saturating_add(limit))
844 .map_or(Value::Null, |next| json!(next));
845 }
846 bound_detail_value(&mut verification, 0, limit, &mut 2048);
847
848 let mut detail = serde_json::Map::new();
849 if let Some(compact_obj) = compact.as_object() {
850 for (key, val) in compact_obj {
851 detail.insert(key.clone(), val.clone());
852 }
853 }
854 if !detail.contains_key("role")
855 && let Some(role) = value
856 .pointer("/snapshot/agent_type")
857 .and_then(Value::as_str)
858 .or_else(|| {
859 value
860 .pointer("/child_route/canonical_role")
861 .and_then(Value::as_str)
862 })
863 .or_else(|| {
864 value
865 .pointer("/worker_record/spec/agent_type")
866 .and_then(Value::as_str)
867 })
868 {
869 detail.insert("role".into(), json!(role));
870 }
871 if let Some(steps) = detail
872 .get("steps")
873 .or_else(|| detail.get("steps_taken"))
874 .or_else(|| value.pointer("/snapshot/steps_taken"))
875 .cloned()
876 {
877 detail.insert("steps".into(), steps.clone());
878 detail.insert("steps_taken".into(), steps);
879 }
880 if let Some(objective) = value
881 .pointer("/snapshot/assignment/objective")
882 .and_then(Value::as_str)
883 .or_else(|| {
884 value
885 .pointer("/worker_record/spec/objective")
886 .and_then(Value::as_str)
887 })
888 .map(str::trim)
889 .filter(|text| !text.is_empty())
890 {
891 detail.insert("objective".into(), json!(text_preview(objective, 320)));
892 }
893 if let Some(result_text) = value
894 .pointer("/snapshot/result")
895 .and_then(Value::as_str)
896 .map(str::trim)
897 .filter(|text| !text.is_empty())
898 {
899 let bounded = text_preview(result_text, 2048);
900 let truncated = bounded.len() < result_text.len();
901 detail.insert("result".into(), json!(bounded));
902 if truncated {
903 detail.insert("result_truncated".into(), json!(true));
904 }
905 }
906 if let Some(checkpoint) = value
907 .get("checkpoint")
908 .filter(|cp| cp.is_object())
909 .or_else(|| {
910 value
911 .pointer("/snapshot/checkpoint")
912 .filter(|cp| cp.is_object())
913 })
914 {
915 let mut summary = serde_json::Map::new();
916 if let Some(reason) = checkpoint.get("reason").and_then(Value::as_str) {
917 summary.insert("reason".into(), json!(text_preview(reason, 160)));
918 }
919 if let Some(step) = checkpoint.get("step") {
920 summary.insert("step".into(), step.clone());
921 }
922 if let Some(messages) = checkpoint.get("messages").and_then(Value::as_array) {
923 summary.insert("message_count".into(), json!(messages.len()));
924 }
925 if let Some(continuable) = checkpoint.get("continuable") {
926 summary.insert("continuable".into(), continuable.clone());
927 }
928 if !summary.is_empty() {
929 detail.insert("checkpoint_summary".into(), Value::Object(summary));
930 }
931 }
932 if let Some(events) = value
933 .pointer("/worker_record/events")
934 .and_then(Value::as_array)
935 {
936 let total = events.len();
937 let page_events: Vec<Value> = events
938 .iter()
939 .skip(offset)
940 .take(limit)
941 .map(compact_event_json)
942 .collect();
943 let next = offset.saturating_add(page_events.len());
944 detail.insert("recent_events".into(), Value::Array(page_events));
945 detail.insert("events_total".into(), json!(total));
946 if next < total {
947 detail.insert("events_next_offset".into(), json!(next));
948 }
949 }
950 if let Some(continuable) = value.get("continuable") {
951 detail.insert("continuable".into(), continuable.clone());
952 }
953 detail.insert("verification".into(), verification);
954 let has_handle = transcript_handle.is_some();
955 if let Some(handle) = transcript_handle {
956 detail.insert("transcript_handle".into(), handle);
957 }
958 detail.insert("compact".into(), json!(false));
959 detail.insert("detail_bounded".into(), json!(true));
960 detail.insert("detail_offset".into(), json!(offset));
961 detail.insert("detail_limit".into(), json!(limit));
962 detail.insert(
963 "detail_hint".into(),
964 json!(if has_handle {
965 "Fields are bounded; use offset/limit for recent_events and deliverables, or transcript_handle with handle_read for the complete retained transcript."
966 } else {
967 "Fields are bounded; use offset/limit for recent_events and deliverables."
968 }),
969 );
970
971 let mut out = Value::Object(detail);
972 if !detail_fits(&out) {
973 if let Some(result_text) = out
974 .get("result")
975 .and_then(Value::as_str)
976 .map(|text| text_preview(text, 512))
977 {
978 out["result"] = json!(result_text);
979 out["result_truncated"] = json!(true);
980 }
981 truncate_event_page(&mut out, offset, 4);
982 }
983 if !detail_fits(&out) {
984 truncate_event_page(&mut out, offset, 1);
985 let status = out
986 .pointer("/verification/status")
987 .cloned()
988 .unwrap_or(Value::Null);
989 let counts = out.pointer("/verification/deliverable_counts").cloned();
990 let total = out.pointer("/verification/deliverables_total").cloned();
991 let next = out
992 .pointer("/verification/deliverables_next_offset")
993 .cloned();
994 out["verification"] = json!({
995 "status": status,
996 "deliverable_counts": counts,
997 "deliverables_total": total,
998 "deliverables_next_offset": next,
999 "detail_required": true,
1000 });
1001 }
1002 if !detail_fits(&out) {
1003 let handle = out.get("transcript_handle").cloned();
1004 let mut minimal = json!({
1005 "agent_id": out["agent_id"],
1006 "role": out["role"],
1007 "status": out["status"],
1008 "steps": out["steps"],
1009 "steps_taken": out["steps_taken"],
1010 "duration_ms": out["duration_ms"],
1011 "activity": out["activity"],
1012 "needs_input": out["needs_input"],
1013 "summary": out["summary"],
1014 "usage": out["usage"],
1015 "verification": out["verification"],
1016 "detail_bounded": true,
1017 "omitted_detail": if handle.is_some() {
1018 "Diagnostic page exceeded 8 KiB; use transcript_handle with handle_read for retained detail."
1019 } else {
1020 "Diagnostic page exceeded 8 KiB."
1021 },
1022 });
1023 if let Some(handle) = handle {
1024 minimal["transcript_handle"] = handle;
1025 }
1026 for key in [
1027 "recent_events",
1028 "events_total",
1029 "events_next_offset",
1030 "events_omitted",
1031 ] {
1032 if let Some(value) = out.get_mut(key) {
1033 minimal[key] = value.take();
1034 }
1035 }
1036 if !detail_fits(&minimal) {
1037 let identity = minimal.get_mut("agent_id").map(Value::take);
1038 minimal.as_object_mut().unwrap().retain(|key, _| {
1039 matches!(
1040 key.as_str(),
1041 "recent_events"
1042 | "events_total"
1043 | "events_next_offset"
1044 | "events_omitted"
1045 | "transcript_handle"
1046 | "detail_bounded"
1047 )
1048 });
1049 if !detail_fits(&minimal)
1050 && let Some(row) = minimal
1051 .get_mut("recent_events")
1052 .and_then(Value::as_array_mut)
1053 .and_then(|events| events.first_mut())
1054 {
1055 *row = json!({"seq": row["seq"].as_u64(), "detail_omitted": true});
1056 }
1057 if !detail_fits(&minimal) {
1058 minimal.as_object_mut().unwrap().remove("transcript_handle");
1059 minimal["transcript_handle_omitted"] = json!(true);
1060 }
1061 if let Some(identity) = identity {
1062 minimal["agent_id"] = identity;
1063 if !detail_fits(&minimal) {
1064 minimal.as_object_mut().unwrap().remove("agent_id");
1065 }
1066 }
1067 }
1068 out = minimal;
1069 }
1070 out
1071 }
1072
1072 lines RUST