返回 CodeWhale
coord.rs
根目录 / crates / engine / src / tools / subagent / coord.rs
1 //! Agent coordination handlers behind the `agent` tool's actions.
2 //!
3 //! These wrap existing SubAgentManager / mailbox / checkpoint machinery
4 //! without restoring the retired lifecycle theater (`agent_open` /
5 //! `agent_eval` / …). None of them is registered as a tool of its own.
6
7 use std::sync::Arc;
8 use std::time::{Duration, Instant};
9
10 use async_trait::async_trait;
11 use serde_json::{Value, json};
12
13 use super::{
14 COMPLETED_AGENT_RETENTION, NEEDS_PERSON_WAIT_NOTE, ParentMailReceipt, SharedSubAgentManager,
15 SubAgentRuntime, SubAgentStatus, parse_agent_ref, subagent_result_display_name,
16 subagent_session_projection, subagent_status_name, take_new_needs_person,
17 wait_for_subagents_from_input,
18 };
19 use crate::tools::spec::{
20 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
21 };
22
23 /// Bounds for `agents/wait`. Short on purpose: a blocked wait makes the
24 /// session deaf to typed input, and settled children already report back as
25 /// `<codewhale:subagent.done>` sentinels that start a fresh turn (#4097).
26 /// `pub` so the description-pinning test can tie the advertised
27 /// numbers to the runtime constants.
28 pub const COORD_WAIT_DEFAULT_TIMEOUT_SECS: u64 = 30;
29 const COORD_WAIT_MIN_TIMEOUT_SECS: u64 = 1;
30 pub const COORD_WAIT_MAX_TIMEOUT_SECS: u64 = 120;
31 const COORD_WAIT_CHECK_INTERVAL: Duration = Duration::from_millis(250);
32 const RECENT_PROGRESS_LIMIT: usize = 8;
33 pub(super) const COORDINATION_RECORD_LIMIT: usize = 128;
34 const COORDINATION_INSPECT_LIMIT: usize = 24;
35 pub(super) const COORDINATION_PROJECTION_DECISION_LIMIT: usize = 8;
36 pub(super) const COORDINATION_PROJECTION_BYTE_LIMIT: usize = 4096;
37
38 mod ledger;
39
40 // The ledger types moved to `ledger` unchanged and are re-published here, so
41 // `crate::tools::subagent::coord::{DecisionRecord, …}` still resolves for every
42 // consumer that never had reason to know where the definitions sit — the point
43 // of the split was to shorten two files, not to make four other files import
44 // differently.
45 //
46 // A glob, not a list: several of these types are named only from `cfg(test)`
47 // code in other modules, and an explicit `pub use` of those reads as an unused
48 // import in a release build. The glob also keeps each item's own visibility, so
49 // `MAX_RECONCILIATION_RETRIES` stays reachable here without becoming part of
50 // the module's public surface.
51 pub use ledger::*;
52
53 // ── agents/list ──────────────────────────────────────────────────────────
54
55 pub struct AgentsListTool {
56 manager: SharedSubAgentManager,
57 }
58
59 impl AgentsListTool {
60 #[must_use]
61 pub fn new(manager: SharedSubAgentManager) -> Self {
62 Self { manager }
63 }
64 }
65
66 #[async_trait]
67 impl ToolSpec for AgentsListTool {
68 fn name(&self) -> &'static str {
69 "agents/list"
70 }
71
72 fn description(&self) -> &'static str {
73 "List child agents: ids, parent hierarchy, state, and bounded recent progress. Read-only coordination view — does not spawn or wake workers."
74 }
75
76 fn input_schema(&self) -> Value {
77 json!({
78 "type": "object",
79 "properties": {
80 "include_archived": {
81 "type": "boolean",
82 "description": "Include prior-session / archived agents. Default false."
83 },
84 "agent_id": {
85 "type": "string",
86 "description": "Optional single agent id or session name to inspect."
87 }
88 },
89 "required": []
90 })
91 }
92
93 fn capabilities(&self) -> Vec<ToolCapability> {
94 vec![ToolCapability::ReadOnly]
95 }
96
97 fn approval_requirement(&self) -> ApprovalRequirement {
98 ApprovalRequirement::Auto
99 }
100
101 fn is_read_only_for(&self, _input: &Value) -> bool {
102 true
103 }
104
105 fn supports_parallel_for(&self, _input: &Value) -> bool {
106 true
107 }
108
109 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
110 let include_archived = input
111 .get("include_archived")
112 .and_then(Value::as_bool)
113 .unwrap_or(false);
114 let agent_ref = parse_agent_ref(&input)?;
115
116 let manager = self.manager.clone();
117 let session = context.state_namespace.clone();
118 let summaries = codewhale_runtime::runtime_control::owner_work(move || {
119 let mut manager = manager.blocking_write();
120 manager.cleanup_for_session(&session, COMPLETED_AGENT_RETENTION)?;
121 let summaries = if let Some(agent_ref) = agent_ref {
122 manager
123 .coordination_summary_for_session(&session, &agent_ref, RECENT_PROGRESS_LIMIT)
124 .map(|summary| vec![summary])
125 .map_err(|err| ToolError::invalid_input(err.to_string()))
126 } else {
127 Ok(manager.list_coordination_summaries_for_session(
128 &session,
129 include_archived,
130 RECENT_PROGRESS_LIMIT,
131 ))
132 };
133 Ok(summaries)
134 })
135 .await
136 .map_err(|error| ToolError::execution_failed(error.to_string()))??;
137
138 let payload = json!({
139 "action": "list",
140 "count": summaries.len(),
141 "agents": summaries,
142 });
143 let mut tool_result = ToolResult::json(&payload)
144 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
145 tool_result.metadata = Some(json!({
146 "action": "list",
147 "count": summaries.len(),
148 }));
149 Ok(tool_result)
150 }
151 }
152
153 // ── agents/message ───────────────────────────────────────────────────────
154
155 pub struct AgentsMessageTool {
156 manager: SharedSubAgentManager,
157 caller_agent_id: Option<String>,
158 }
159
160 impl AgentsMessageTool {
161 #[must_use]
162 pub fn new(manager: SharedSubAgentManager) -> Self {
163 Self {
164 manager,
165 caller_agent_id: None,
166 }
167 }
168
169 #[must_use]
170 pub fn with_optional_caller(mut self, caller_agent_id: Option<String>) -> Self {
171 self.caller_agent_id = caller_agent_id;
172 self
173 }
174 }
175
176 #[async_trait]
177 impl ToolSpec for AgentsMessageTool {
178 fn name(&self) -> &'static str {
179 "agents/message"
180 }
181
182 fn description(&self) -> &'static str {
183 "Send a parent note to a running child. A child with a live input channel receives it at its next step boundary without being interrupted (delivered: \"next_step\"). If the channel is closed the note stays queued (queued: true) until a later agents/followup delivers it. Non-running children do not accept messages; use agents/followup to resume an interrupted child."
184 }
185
186 fn input_schema(&self) -> Value {
187 json!({
188 "type": "object",
189 "properties": {
190 "agent_id": {
191 "type": "string",
192 "description": "Target child agent id or session name."
193 },
194 "message": {
195 "type": "string",
196 "minLength": 1,
197 "maxLength": super::MAX_PARENT_MESSAGE_BYTES,
198 "description": "Message text to deliver."
199 }
200 },
201 "required": ["agent_id", "message"]
202 })
203 }
204
205 fn capabilities(&self) -> Vec<ToolCapability> {
206 vec![ToolCapability::RequiresApproval]
207 }
208
209 fn approval_requirement(&self) -> ApprovalRequirement {
210 ApprovalRequirement::Required
211 }
212
213 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
214 let agent_ref =
215 parse_agent_ref(&input)?.ok_or_else(|| ToolError::missing_field("agent_id"))?;
216 let message = input
217 .get("message")
218 .or_else(|| input.get("text"))
219 .and_then(Value::as_str)
220 .map(str::trim)
221 .filter(|s| !s.is_empty())
222 .ok_or_else(|| ToolError::missing_field("message"))?
223 .to_string();
224 if message.len() > super::MAX_PARENT_MESSAGE_BYTES {
225 return Err(ToolError::invalid_input(format!(
226 "message is {} bytes; maximum allowed is {} bytes",
227 message.len(),
228 super::MAX_PARENT_MESSAGE_BYTES
229 )));
230 }
231
232 let receipt = {
233 let mut manager = self.manager.write().await;
234 manager
235 .ensure_caller_controls_descendant_for_session(
236 &context.state_namespace,
237 &agent_ref,
238 self.caller_agent_id.as_deref(),
239 "agent action=message",
240 )
241 .map_err(|err| ToolError::invalid_input(err.to_string()))?;
242 manager
243 .queue_running_parent_message_for_session(
244 &context.state_namespace,
245 &agent_ref,
246 message,
247 )
248 .map_err(|err| ToolError::invalid_input(err.to_string()))?
249 };
250
251 let mut payload = json!({
252 "action": "message",
253 "agent_id": receipt.agent_id,
254 "queued": !receipt.woke,
255 "woke": false,
256 "queue_depth": receipt.queue_depth,
257 "status": receipt.status,
258 "note": if receipt.woke {
259 "Delivered to the running child at its next step boundary without interrupting it."
260 } else {
261 "Message queued; the child's live input channel is closed. A later agents/followup delivers it."
262 },
263 });
264 if receipt.woke {
265 payload["delivered"] = json!("next_step");
266 }
267 let mut tool_result = ToolResult::json(&payload)
268 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
269 tool_result.metadata = Some(json!({
270 "action": "message",
271 "agent_id": receipt.agent_id,
272 "woke": false,
273 "delivered": receipt.woke.then_some("next_step"),
274 "queue_depth": receipt.queue_depth,
275 }));
276 Ok(tool_result)
277 }
278 }
279
280 // ── agents/followup ──────────────────────────────────────────────────────
281
282 pub struct AgentsFollowupTool {
283 manager: SharedSubAgentManager,
284 caller_agent_id: Option<String>,
285 /// Runtime for checkpoint resume. `None` (legacy/test construction)
286 /// keeps the queue-only followup behavior.
287 runtime: Option<SubAgentRuntime>,
288 }
289
290 impl AgentsFollowupTool {
291 #[must_use]
292 pub fn new(manager: SharedSubAgentManager) -> Self {
293 Self {
294 manager,
295 caller_agent_id: None,
296 runtime: None,
297 }
298 }
299
300 #[must_use]
301 pub fn with_runtime(mut self, runtime: SubAgentRuntime) -> Self {
302 self.runtime = Some(runtime);
303 self
304 }
305
306 #[must_use]
307 pub fn with_optional_caller(mut self, caller_agent_id: Option<String>) -> Self {
308 self.caller_agent_id = caller_agent_id;
309 self
310 }
311 }
312
313 impl AgentsFollowupTool {
314 async fn followup_one(
315 &self,
316 agent_ref: &str,
317 message: &str,
318 context: &ToolContext,
319 ) -> Result<Value, ToolError> {
320 let manager_handle = self.manager.clone();
321 let manager = manager_handle.clone();
322 let session = context.state_namespace.clone();
323 let caller = self.caller_agent_id.clone();
324 let runtime = self.runtime.clone();
325 let agent_ref = agent_ref.to_owned();
326 let message = message.to_owned();
327 codewhale_runtime::runtime_control::owner_work(move || {
328 let mut manager = manager.blocking_write();
329 let result = (|| {
330 let (source, target) = manager
331 .continuation_target_for_caller(
332 &session,
333 &agent_ref,
334 caller.as_deref(),
335 "agent action=followup",
336 )
337 .map_err(|error| ToolError::invalid_input(error.to_string()))?;
338 let snapshot = manager
339 .get_result(&target)
340 .map_err(|error| ToolError::invalid_input(error.to_string()))?;
341 let resumed_already = source != target;
342 let receipt = if super::subagent_checkpoint_is_continuable(&snapshot)
343 && let Some(runtime) = runtime
344 {
345 let snapshot = manager
346 .resume_from_checkpoint_for_session(
347 &session,
348 Arc::clone(&manager_handle),
349 runtime,
350 &target,
351 &message,
352 )
353 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
354 ParentMailReceipt {
355 agent_id: snapshot.agent_id.clone(),
356 status: subagent_status_name(&snapshot.status).to_string(),
357 queue_depth: 0,
358 woke: true,
359 continued_from_checkpoint: true,
360 continuation_handle: None,
361 note: format!(
362 "resumed from checkpoint {source} as {}; original receipt retained",
363 snapshot.agent_id
364 ),
365 }
366 } else if resumed_already && snapshot.status != SubAgentStatus::Running {
367 ParentMailReceipt {
368 agent_id: target, status: subagent_status_name(&snapshot.status).to_string(),
369 queue_depth: 0, woke: false, continued_from_checkpoint: true,
370 continuation_handle: None,
371 note: "Existing continuation has settled; no duplicate worker was started and no message was delivered.".to_string(),
372 }
373 } else {
374 manager
375 .followup_child_for_session(&session, &target, message)
376 .map_err(|error| ToolError::invalid_input(error.to_string()))?
377 };
378 let child_route = manager
379 .get_worker_record_for_session(&session, &receipt.agent_id)
380 .and_then(|record| record.spec.child_route);
381 Ok(json!({
382 "action": "followup", "from": source, "to": receipt.agent_id,
383 "agent_id": receipt.agent_id, "queued": receipt.woke || receipt.queue_depth > 0,
384 "woke": receipt.woke, "queue_depth": receipt.queue_depth, "status": receipt.status,
385 "continued_from_checkpoint": receipt.continued_from_checkpoint || resumed_already,
386 "continuation_handle": receipt.continuation_handle, "note": receipt.note,
387 "child_route": child_route,
388 }))
389 })();
390 Ok(result)
391 })
392 .await
393 .map_err(|error| ToolError::execution_failed(error.to_string()))?
394 }
395 }
396
397 #[async_trait]
398 impl ToolSpec for AgentsFollowupTool {
399 fn name(&self) -> &'static str {
400 "agents/followup"
401 }
402
403 fn description(&self) -> &'static str {
404 "Queue a message and attempt to resume an idle or interrupted child. Running children receive the message at their next step boundary, like agents/message; interrupted_continuable children are resumed from their checkpoint into a fresh agent loop (new agent id, original prompt plus prior conversation tail) when a runtime is attached, and otherwise keep queue-only semantics with the continuation_handle returned."
405 }
406
407 fn input_schema(&self) -> Value {
408 json!({
409 "type": "object",
410 "properties": {
411 "agent_id": {"type": "string"},
412 "agent_ids": {"type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1, "maxItems": 32},
413 "all_parked": {"type": "boolean", "description": "Continue every owned parked child, up to 32."},
414 "message": {"type": "string", "minLength": 1, "maxLength": super::MAX_PARENT_MESSAGE_BYTES}
415 },
416 "required": ["message"],
417 "oneOf": [{"required": ["agent_id"]}, {"required": ["agent_ids"]}, {"required": ["all_parked"]}]
418 })
419 }
420
421 fn capabilities(&self) -> Vec<ToolCapability> {
422 vec![ToolCapability::RequiresApproval]
423 }
424
425 fn approval_requirement(&self) -> ApprovalRequirement {
426 ApprovalRequirement::Required
427 }
428
429 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
430 let message = input
431 .get("message")
432 .or_else(|| input.get("text"))
433 .and_then(Value::as_str)
434 .map(str::trim)
435 .filter(|value| !value.is_empty())
436 .ok_or_else(|| ToolError::missing_field("message"))?;
437 if message.len() > super::MAX_PARENT_MESSAGE_BYTES {
438 return Err(ToolError::invalid_input(format!(
439 "followup message is {} bytes; maximum allowed is {} bytes",
440 message.len(),
441 super::MAX_PARENT_MESSAGE_BYTES
442 )));
443 }
444 let single = parse_agent_ref(&input)?;
445 let all_parked = super::parse_optional_bool(&input, &["all_parked"])?.unwrap_or(false);
446 let batch = input.get("agent_ids");
447 if usize::from(single.is_some()) + usize::from(batch.is_some()) + usize::from(all_parked)
448 != 1
449 {
450 return Err(ToolError::invalid_input(
451 "followup requires exactly one of agent_id, agent_ids, or all_parked=true",
452 ));
453 }
454 let mut targets = if let Some(ids) = batch {
455 let ids = ids
456 .as_array()
457 .filter(|ids| !ids.is_empty() && ids.len() <= 32)
458 .ok_or_else(|| {
459 ToolError::invalid_input("agent_ids must contain 1..32 nonempty strings")
460 })?;
461 ids.iter()
462 .map(|id| {
463 id.as_str()
464 .map(str::trim)
465 .filter(|id| !id.is_empty())
466 .map(str::to_string)
467 .ok_or_else(|| {
468 ToolError::invalid_input("agent_ids must contain nonempty strings")
469 })
470 })
471 .collect::<Result<Vec<_>, _>>()?
472 } else if let Some(id) = single.as_ref() {
473 vec![id.clone()]
474 } else {
475 let manager = self.manager.read().await;
476 let mut ids = manager
477 .agents
478 .values()
479 .filter(|agent| {
480 manager.agent_is_owned_by_session(agent, &context.state_namespace)
481 && agent
482 .checkpoint
483 .as_ref()
484 .is_some_and(|checkpoint| checkpoint.parked_at_turn_end)
485 && matches!(agent.status, SubAgentStatus::Interrupted(_))
486 && manager
487 .ensure_caller_controls_descendant(
488 &agent.id,
489 self.caller_agent_id.as_deref(),
490 "agent action=followup",
491 )
492 .is_ok()
493 && manager
494 .continuation_target(&agent.id)
495 .is_ok_and(|target| target == agent.id)
496 })
497 .map(|agent| agent.id.clone())
498 .collect::<Vec<_>>();
499 ids.sort();
500 if ids.len() > 32 {
501 return Err(ToolError::invalid_input(
502 "More than 32 parked children; use explicit agent_ids batches",
503 ));
504 }
505 ids
506 };
507 let mut seen = std::collections::HashSet::new();
508 targets.retain(|target| seen.insert(target.clone()));
509 let mut results = Vec::new();
510 let mut errors = Vec::new();
511 // Each mutation and both hierarchy checks share the manager write lock.
512 // A target failure cannot erase successful results from another target.
513 for target in targets {
514 match self.followup_one(&target, message, context).await {
515 Ok(payload) => results.push(payload),
516 Err(error) if single.is_some() => return Err(error),
517 Err(error) => errors.push(json!({"from": target, "error": error.to_string()})),
518 }
519 }
520 let payload = if single.is_some() {
521 results.pop().expect("single target returned a result")
522 } else {
523 json!({"action": "followup", "results": results, "errors": errors})
524 };
525 let mut result = ToolResult::json(&payload)
526 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
527 result.metadata = Some(payload.clone());
528 Ok(result)
529 }
530 }
531
532 // ── agents/interrupt ─────────────────────────────────────────────────────
533
534 pub struct AgentsInterruptTool {
535 manager: SharedSubAgentManager,
536 /// Optional caller identity for fail-closed self-interrupt checks.
537 caller_agent_id: Option<String>,
538 }
539
540 impl AgentsInterruptTool {
541 #[must_use]
542 pub fn new(manager: SharedSubAgentManager) -> Self {
543 Self {
544 manager,
545 caller_agent_id: None,
546 }
547 }
548
549 #[must_use]
550 pub fn with_caller(mut self, caller_agent_id: impl Into<String>) -> Self {
551 self.caller_agent_id = Some(caller_agent_id.into());
552 self
553 }
554
555 #[must_use]
556 pub fn with_optional_caller(mut self, caller_agent_id: Option<String>) -> Self {
557 self.caller_agent_id = caller_agent_id;
558 self
559 }
560 }
561
562 #[async_trait]
563 impl ToolSpec for AgentsInterruptTool {
564 fn name(&self) -> &'static str {
565 "agents/interrupt"
566 }
567
568 fn description(&self) -> &'static str {
569 "Interrupt a running child agent, preserve its checkpoint, and return the prior state. Fails closed on root or self targets. Prefer this over cancel when you may resume later."
570 }
571
572 fn input_schema(&self) -> Value {
573 json!({
574 "type": "object",
575 "properties": {
576 "agent_id": {
577 "type": "string",
578 "description": "Child agent id or session name to interrupt."
579 },
580 "reason": {
581 "type": "string",
582 "description": "Optional interrupt reason recorded on the checkpoint."
583 }
584 },
585 "required": ["agent_id"]
586 })
587 }
588
589 fn capabilities(&self) -> Vec<ToolCapability> {
590 vec![ToolCapability::RequiresApproval]
591 }
592
593 fn approval_requirement(&self) -> ApprovalRequirement {
594 ApprovalRequirement::Required
595 }
596
597 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
598 let agent_ref =
599 parse_agent_ref(&input)?.ok_or_else(|| ToolError::missing_field("agent_id"))?;
600 let reason = input
601 .get("reason")
602 .and_then(Value::as_str)
603 .map(str::trim)
604 .filter(|s| !s.is_empty())
605 .unwrap_or("interrupted by parent via agent action=interrupt")
606 .to_string();
607
608 let manager = self.manager.clone();
609 let session = context.state_namespace.clone();
610 let caller = self.caller_agent_id.clone();
611 let (prior, snapshot) = codewhale_runtime::runtime_control::owner_work(move || {
612 manager.blocking_write().interrupt_child_for_session(
613 &session,
614 &agent_ref,
615 caller.as_deref(),
616 reason,
617 )
618 })
619 .await
620 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
621
622 let snapshot = super::settle_requested_child(&self.manager, snapshot).await;
623 let worker_record = {
624 let manager = self.manager.read().await;
625 manager.get_worker_record_for_session(&context.state_namespace, &snapshot.agent_id)
626 };
627 let projection =
628 subagent_session_projection(&self.manager, snapshot, false, context, worker_record)
629 .await;
630 let payload = json!({
631 "action": "interrupt",
632 "agent_id": projection.agent_id,
633 "prior_status": subagent_status_name(&prior.status),
634 "prior_steps_taken": prior.steps_taken,
635 "status": projection.status,
636 "checkpoint_preserved": projection.checkpoint.is_some(),
637 "continuable": projection.continuable,
638 "projection": projection,
639 "child_route": projection.child_route,
640 });
641 let mut tool_result = ToolResult::json(&payload)
642 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
643 tool_result.metadata = Some(json!({
644 "action": "interrupt",
645 "agent_id": payload["agent_id"],
646 "checkpoint_preserved": payload["checkpoint_preserved"],
647 "child_route": payload["child_route"],
648 }));
649 Ok(tool_result)
650 }
651 }
652
653 // ── agents/wait ──────────────────────────────────────────────────────────
654
655 pub struct AgentsWaitTool {
656 manager: SharedSubAgentManager,
657 }
658
659 impl AgentsWaitTool {
660 #[must_use]
661 pub fn new(manager: SharedSubAgentManager) -> Self {
662 Self { manager }
663 }
664 }
665
666 #[async_trait]
667 impl ToolSpec for AgentsWaitTool {
668 fn name(&self) -> &'static str {
669 "agents/wait"
670 }
671
672 fn description(&self) -> &'static str {
673 "Block briefly until one child settles or timeout_secs (default 30, max 120) elapses; on timeout the receipt reports timed_out=true and any settled children. Keep waits short: on timeout, end your turn — settled children wake you automatically as completion sentinels; polling agents/list in a loop is not the right shape either. until=all is the fan-out join: it returns only when every child running at call time has left running, with each child's outcome. until=completion (default) returns as soon as any one child settles. until=activity also returns on progress."
674 }
675
676 fn input_schema(&self) -> Value {
677 json!({
678 "type": "object",
679 "properties": {
680 "agent_id": {
681 "type": "string",
682 "description": "Optional specific child. When omitted, watches every child running at call time."
683 },
684 "timeout_secs": {
685 "type": "integer",
686 "minimum": 1,
687 "maximum": 120,
688 "description": "Maximum seconds to block. Default 30. Keep it short — on timeout, end your turn; settled children report back as completion sentinels."
689 },
690 "until": {
691 "type": "string",
692 "enum": ["completion", "all", "activity"],
693 "description": "completion (default): return when any one child leaves running. all: return only when every watched child has left running — use this after a fan-out so one wait covers the whole batch. activity: also return when recent progress changes. Children spawned after the call are not watched; no children means an immediate return."
694 }
695 },
696 "required": []
697 })
698 }
699
700 fn capabilities(&self) -> Vec<ToolCapability> {
701 vec![ToolCapability::ReadOnly]
702 }
703
704 fn approval_requirement(&self) -> ApprovalRequirement {
705 ApprovalRequirement::Auto
706 }
707
708 fn is_read_only_for(&self, _input: &Value) -> bool {
709 true
710 }
711
712 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
713 dispatch_wait(&input, Arc::clone(&self.manager), context).await
714 }
715 }
716
717 /// Single entry point for every blocking wait, shared by `agents/wait` and
718 /// `agent(action="wait")` so the two surfaces cannot drift.
719 ///
720 /// `until` selects the join shape:
721 /// - `completion` (default) — return as soon as any one watched child settles.
722 /// - `all` — return only when every watched child has settled (the fan-out
723 /// join the parent should use after dispatching a batch).
724 /// - `activity` — also return when a running child makes visible progress.
725 pub(super) async fn dispatch_wait(
726 input: &Value,
727 manager: SharedSubAgentManager,
728 context: &ToolContext,
729 ) -> Result<ToolResult, ToolError> {
730 let until = input
731 .get("until")
732 .and_then(Value::as_str)
733 .unwrap_or("completion")
734 .trim()
735 .to_ascii_lowercase();
736
737 match until.as_str() {
738 "" | "completion" => {
739 let mut wait_input = input.clone();
740 if wait_input.get("action").is_none() {
741 wait_input["action"] = json!("wait");
742 }
743 wait_for_subagents_from_input(&wait_input, manager, context).await
744 }
745 "all" => wait_for_all_children(input, manager, context).await,
746 "activity" => wait_for_activity(input, manager, context).await,
747 other => Err(ToolError::invalid_input(format!(
748 "Invalid until '{other}'. Use completion, all, or activity."
749 ))),
750 }
751 }
752
753 /// `until=all`: block until every child that was running when the call was
754 /// made has left `Running`.
755 ///
756 /// The watch set is fixed at call time. A child spawned while this wait is
757 /// blocked is deliberately **not** joined — the parent asked to join the batch
758 /// it had just dispatched, and silently extending the set would make the call
759 /// unbounded in a way the caller never asked for. Callers that fan out again
760 /// simply issue another wait.
761 ///
762 /// Cancel-safe (no lock is held across an await), honours `timeout_secs`, and
763 /// returns immediately with `all_settled: true` when nothing is running.
764 async fn wait_for_all_children(
765 input: &Value,
766 manager: SharedSubAgentManager,
767 context: &ToolContext,
768 ) -> Result<ToolResult, ToolError> {
769 let timeout_secs = input
770 .get("timeout_secs")
771 .or_else(|| input.get("timeout"))
772 .and_then(Value::as_u64)
773 .unwrap_or(COORD_WAIT_DEFAULT_TIMEOUT_SECS)
774 .clamp(COORD_WAIT_MIN_TIMEOUT_SECS, COORD_WAIT_MAX_TIMEOUT_SECS);
775 let timeout = Duration::from_secs(timeout_secs);
776 let agent_ref = parse_agent_ref(input)?;
777
778 // Resolve the watch set up front so a bad reference fails immediately
779 // rather than blocking for the whole timeout.
780 let watched: Vec<String> = {
781 let manager = manager.read().await;
782 if let Some(agent_ref) = &agent_ref {
783 let snapshot = manager
784 .get_result_by_ref_for_session(&context.state_namespace, agent_ref)
785 .map_err(|err| ToolError::invalid_input(err.to_string()))?;
786 if snapshot.status != SubAgentStatus::Running {
787 // Already settled: hand back its outcome rather than an empty
788 // "nothing to join" that hides what the caller asked about.
789 let settled = json!({
790 "agent_id": snapshot.agent_id,
791 "name": subagent_result_display_name(&snapshot),
792 "status": subagent_status_name(&snapshot.status),
793 "steps_taken": snapshot.steps_taken,
794 });
795 drop(manager);
796 return wait_all_payload(&[settled], &[], &[], 0, false);
797 }
798 vec![snapshot.agent_id]
799 } else {
800 manager
801 .list_filtered_for_session(&context.state_namespace, false)
802 .into_iter()
803 .filter(|snapshot| snapshot.status == SubAgentStatus::Running)
804 .map(|snapshot| snapshot.agent_id)
805 .collect()
806 }
807 };
808
809 // Zero children is an immediate return, never a hang.
810 if watched.is_empty() {
811 return wait_all_payload(&[], &[], &[], 0, false);
812 }
813
814 let started = Instant::now();
815 let cancelled = async {
816 match &context.cancel_token {
817 Some(token) => token.cancelled().await,
818 None => std::future::pending().await,
819 }
820 };
821 tokio::pin!(cancelled);
822
823 loop {
824 let (settled, still_running) = {
825 let manager = manager.read().await;
826 let mut settled = Vec::new();
827 let mut still_running = Vec::new();
828 for agent_id in &watched {
829 match manager.get_result_by_ref_for_session(&context.state_namespace, agent_id) {
830 Ok(snapshot) if snapshot.status == SubAgentStatus::Running => {
831 still_running.push(json!({
832 "agent_id": snapshot.agent_id,
833 "name": subagent_result_display_name(&snapshot),
834 "status": "running",
835 }));
836 }
837 Ok(snapshot) => settled.push(json!({
838 "agent_id": snapshot.agent_id,
839 "name": subagent_result_display_name(&snapshot),
840 "status": subagent_status_name(&snapshot.status),
841 "steps_taken": snapshot.steps_taken,
842 })),
843 // A watched child that vanished from the ledger (retention
844 // cleanup) is no longer running; report it rather than
845 // blocking on a record that will never settle.
846 Err(_) => settled.push(json!({
847 "agent_id": agent_id,
848 "status": "gone",
849 })),
850 }
851 }
852 (settled, still_running)
853 };
854
855 if still_running.is_empty() {
856 return wait_all_payload(&settled, &[], &[], started.elapsed().as_millis(), false);
857 }
858 // A child blocked on a person ends the join early (approvals C2).
859 let needs_person = take_new_needs_person(&manager, &watched).await;
860 if !needs_person.is_empty() {
861 return wait_all_payload(
862 &settled,
863 &still_running,
864 &needs_person,
865 started.elapsed().as_millis(),
866 false,
867 );
868 }
869 if started.elapsed() >= timeout {
870 return wait_all_payload(
871 &settled,
872 &still_running,
873 &[],
874 started.elapsed().as_millis(),
875 true,
876 );
877 }
878
879 tokio::select! {
880 biased;
881 () = &mut cancelled => {
882 return Err(ToolError::cancelled(
883 "Wait interrupted by user cancellation before every child settled.".to_string(),
884 ));
885 }
886 () = tokio::time::sleep(COORD_WAIT_CHECK_INTERVAL) => {}
887 }
888 }
889 }
890
891 /// `until=all` result: every watched child with its own outcome, so the parent
892 /// can synthesize from one return instead of re-inspecting each child.
893 fn wait_all_payload(
894 settled: &[Value],
895 still_running: &[Value],
896 needs_person: &[Value],
897 waited_ms: u128,
898 timed_out: bool,
899 ) -> Result<ToolResult, ToolError> {
900 let note = if !needs_person.is_empty() {
901 NEEDS_PERSON_WAIT_NOTE
902 } else if timed_out {
903 "The wait interval ended; the children are still running. You may answer the user or continue other work. Ordinary turn completion keeps them running; results arrive as <codewhale:subagent.done> sentinels. Use followup only when a child actually needs continuation."
904 } else if settled.is_empty() {
905 "No sub-agents were running; nothing to join."
906 } else {
907 "Every watched child has settled. Full results arrive as <codewhale:subagent.done> sentinels — synthesize from those."
908 };
909 let mut payload = json!({
910 "action": "wait",
911 "until": "all",
912 "all_settled": still_running.is_empty(),
913 "settled": settled,
914 "still_running": still_running,
915 "waited_ms": u64::try_from(waited_ms).unwrap_or(u64::MAX),
916 "timed_out": timed_out,
917 "note": note,
918 });
919 if !needs_person.is_empty() {
920 payload["needs_person"] = json!(needs_person);
921 }
922 let mut tool_result =
923 ToolResult::json(&payload).map_err(|err| ToolError::execution_failed(err.to_string()))?;
924 tool_result.metadata = Some(json!({
925 "action": "wait",
926 "until": "all",
927 "all_settled": still_running.is_empty(),
928 "settled": settled.len(),
929 "running": still_running.len(),
930 "timed_out": timed_out,
931 }));
932 Ok(tool_result)
933 }
934
935 async fn wait_for_activity(
936 input: &Value,
937 manager: SharedSubAgentManager,
938 context: &ToolContext,
939 ) -> Result<ToolResult, ToolError> {
940 let timeout_secs = input
941 .get("timeout_secs")
942 .or_else(|| input.get("timeout"))
943 .and_then(Value::as_u64)
944 .unwrap_or(COORD_WAIT_DEFAULT_TIMEOUT_SECS)
945 .clamp(COORD_WAIT_MIN_TIMEOUT_SECS, COORD_WAIT_MAX_TIMEOUT_SECS);
946 let timeout = Duration::from_secs(timeout_secs);
947 let agent_ref = parse_agent_ref(input)?;
948
949 let (watched, baseline): (Vec<String>, Vec<(String, u64)>) = {
950 let manager = manager.read().await;
951 if let Some(agent_ref) = &agent_ref {
952 let snap = manager
953 .get_result_by_ref_for_session(&context.state_namespace, agent_ref)
954 .map_err(|err| ToolError::invalid_input(err.to_string()))?;
955 let fp = manager.activity_fingerprint(&snap.agent_id).unwrap_or(0);
956 if snap.status != SubAgentStatus::Running {
957 let payload = json!({
958 "action": "wait",
959 "until": "activity",
960 "reason": "already_settled",
961 "timed_out": false,
962 "agent_id": snap.agent_id,
963 "status": subagent_status_name(&snap.status),
964 });
965 let mut tool_result = ToolResult::json(&payload)
966 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
967 tool_result.metadata = Some(json!({ "action": "wait", "timed_out": false }));
968 return Ok(tool_result);
969 }
970 (vec![snap.agent_id.clone()], vec![(snap.agent_id, fp)])
971 } else {
972 let running = manager
973 .list_filtered_for_session(&context.state_namespace, false)
974 .into_iter()
975 .filter(|s| s.status == SubAgentStatus::Running)
976 .map(|s| s.agent_id)
977 .collect::<Vec<_>>();
978 let baseline = running
979 .iter()
980 .map(|id| {
981 let fp = manager.activity_fingerprint(id).unwrap_or(0);
982 (id.clone(), fp)
983 })
984 .collect();
985 (running, baseline)
986 }
987 };
988
989 if watched.is_empty() {
990 let payload = json!({
991 "action": "wait",
992 "until": "activity",
993 "note": "No running sub-agents; nothing to wait for.",
994 "timed_out": false,
995 });
996 let mut tool_result = ToolResult::json(&payload)
997 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
998 tool_result.metadata = Some(json!({ "action": "wait", "timed_out": false }));
999 return Ok(tool_result);
1000 }
1001
1002 let started = Instant::now();
1003 let cancelled = async {
1004 match &context.cancel_token {
1005 Some(token) => token.cancelled().await,
1006 None => std::future::pending().await,
1007 }
1008 };
1009 tokio::pin!(cancelled);
1010
1011 loop {
1012 let outcome = {
1013 let manager = manager.read().await;
1014 let mut settled = Vec::new();
1015 let mut activity = Vec::new();
1016 for (id, base_fp) in &baseline {
1017 if let Ok(snap) =
1018 manager.get_result_by_ref_for_session(&context.state_namespace, id)
1019 {
1020 if snap.status != SubAgentStatus::Running {
1021 settled.push(snap);
1022 continue;
1023 }
1024 let fp = manager.activity_fingerprint(id).unwrap_or(0);
1025 if fp != *base_fp {
1026 activity.push(json!({
1027 "agent_id": id,
1028 "status": "running",
1029 "activity_fingerprint": fp,
1030 }));
1031 }
1032 }
1033 }
1034 (
1035 settled,
1036 activity,
1037 manager.running_count_for_session(&context.state_namespace),
1038 )
1039 };
1040
1041 if !outcome.0.is_empty() || !outcome.1.is_empty() {
1042 let payload = json!({
1043 "action": "wait",
1044 "until": "activity",
1045 "settled": outcome.0.iter().map(|s| json!({
1046 "agent_id": s.agent_id,
1047 "status": subagent_status_name(&s.status),
1048 })).collect::<Vec<_>>(),
1049 "activity": outcome.1,
1050 "running": outcome.2,
1051 "elapsed_ms": started.elapsed().as_millis(),
1052 "timed_out": false,
1053 });
1054 let mut tool_result = ToolResult::json(&payload)
1055 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
1056 tool_result.metadata = Some(json!({
1057 "action": "wait",
1058 "timed_out": false,
1059 "settled": outcome.0.len(),
1060 "activity": outcome.1.len(),
1061 }));
1062 return Ok(tool_result);
1063 }
1064
1065 if started.elapsed() >= timeout {
1066 let payload = json!({
1067 "action": "wait",
1068 "until": "activity",
1069 "settled": [],
1070 "activity": [],
1071 "running": outcome.2,
1072 "elapsed_ms": started.elapsed().as_millis(),
1073 "timed_out": true,
1074 "note": "The wait interval ended without new child activity. Children keep running after ordinary turn completion and report through <codewhale:subagent.done> sentinels.",
1075 });
1076 let mut tool_result = ToolResult::json(&payload)
1077 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
1078 tool_result.metadata = Some(json!({ "action": "wait", "timed_out": true }));
1079 return Ok(tool_result);
1080 }
1081
1082 tokio::select! {
1083 biased;
1084 () = &mut cancelled => {
1085 return Err(ToolError::cancelled(
1086 "Wait interrupted by user cancellation before child activity.".to_string(),
1087 ));
1088 }
1089 () = tokio::time::sleep(COORD_WAIT_CHECK_INTERVAL) => {}
1090 }
1091 }
1092 }
1093
1094 pub struct AgentsCoordinateTool {
1095 manager: SharedSubAgentManager,
1096 caller: Option<String>,
1097 }
1098
1099 impl AgentsCoordinateTool {
1100 #[must_use]
1101 pub fn new(manager: SharedSubAgentManager, caller: Option<String>) -> Self {
1102 Self { manager, caller }
1103 }
1104 fn mutate_coordination(
1105 caller: Option<&str>,
1106 session: &str,
1107 workspace: &std::path::Path,
1108 manager: &mut super::SubAgentManager,
1109 input: Value,
1110 ) -> Result<ToolResult, ToolError> {
1111 let action = input
1112 .get("action")
1113 .and_then(Value::as_str)
1114 .unwrap_or("inspect");
1115 let owner = caller.map(str::to_string).unwrap_or_else(|| "root".into());
1116 let bounded_text = |key: &str| {
1117 input
1118 .get(key)
1119 .and_then(Value::as_str)
1120 .map(|value| value.chars().take(512).collect::<String>())
1121 };
1122 let strings = |key: &str| {
1123 input
1124 .get(key)
1125 .and_then(Value::as_array)
1126 .map(|items| {
1127 items
1128 .iter()
1129 .take(24)
1130 .filter_map(Value::as_str)
1131 .map(|value| value.chars().take(512).collect::<String>())
1132 .collect::<Vec<_>>()
1133 })
1134 .unwrap_or_default()
1135 };
1136 if let Some(caller) = caller {
1137 manager
1138 .get_result_by_ref_for_session(session, caller)
1139 .map_err(|_| {
1140 ToolError::invalid_input("Agent not found in the active session".to_string())
1141 })?;
1142 }
1143 if matches!(action, "accept" | "supersede") {
1144 let decision_id = bounded_text("decision_id").unwrap_or_default();
1145 if !manager.coordination_decision_is_owned_by_session(session, &decision_id) {
1146 return Err(ToolError::invalid_input(
1147 "Coordination decision not found in the active session".to_string(),
1148 ));
1149 }
1150 }
1151 if action == "reconcile"
1152 && strings("input_decisions").iter().any(|decision_id| {
1153 !manager.coordination_decision_is_owned_by_session(session, decision_id)
1154 })
1155 {
1156 return Err(ToolError::invalid_input(
1157 "One or more coordination decisions were not found in the active session"
1158 .to_string(),
1159 ));
1160 }
1161 let coordination_before = manager.coordination.clone();
1162 let mutation = match action {
1163 "propose" => manager
1164 .record_coordination_decision_in_workspace(
1165 DecisionRecord {
1166 decision_id: bounded_text("decision_id").unwrap_or_default(),
1167 subject: bounded_text("subject").unwrap_or_default(),
1168 status: DecisionStatus::Proposed,
1169 owner,
1170 scope: strings("scope"),
1171 constraints: strings("constraints"),
1172 evidence_handles: strings("evidence_handles"),
1173 version: 1,
1174 sequence: 0,
1175 },
1176 workspace,
1177 )
1178 .map_err(ToolError::invalid_input)
1179 .and_then(|record| {
1180 serde_json::to_value(record)
1181 .map_err(|e| ToolError::execution_failed(e.to_string()))
1182 }),
1183 "accept" | "supersede" => input
1184 .get("expected_version")
1185 .and_then(Value::as_u64)
1186 .and_then(|value| u32::try_from(value).ok())
1187 .ok_or_else(|| {
1188 ToolError::invalid_input(
1189 "accept/supersede requires expected_version".to_string(),
1190 )
1191 })
1192 .and_then(|expected_version| {
1193 manager
1194 .update_coordination_decision(
1195 &bounded_text("decision_id").unwrap_or_default(),
1196 if action == "accept" {
1197 DecisionStatus::Accepted
1198 } else {
1199 DecisionStatus::Superseded
1200 },
1201 &owner,
1202 expected_version,
1203 )
1204 .map_err(ToolError::invalid_input)
1205 })
1206 .and_then(|record| {
1207 serde_json::to_value(record)
1208 .map_err(|e| ToolError::execution_failed(e.to_string()))
1209 }),
1210 "claim" => manager
1211 .expand_write_claim(
1212 &owner,
1213 strings("roots"),
1214 strings("exact_files"),
1215 strings("contracts"),
1216 )
1217 .map_err(ToolError::invalid_input)
1218 .and_then(|claim| {
1219 serde_json::to_value(claim)
1220 .map_err(|e| ToolError::execution_failed(e.to_string()))
1221 }),
1222 "reconcile" => manager
1223 .reconcile_coordination(
1224 bounded_text("subject").unwrap_or_default(),
1225 owner,
1226 strings("input_decisions"),
1227 bounded_text("outcome").unwrap_or_default(),
1228 strings("evidence_handles"),
1229 strings("candidate_handles"),
1230 input
1231 .get("retry_count")
1232 .and_then(Value::as_u64)
1233 .and_then(|value| u32::try_from(value).ok())
1234 .unwrap_or_default(),
1235 input
1236 .get("retry_limit")
1237 .and_then(Value::as_u64)
1238 .and_then(|value| u32::try_from(value).ok())
1239 .unwrap_or(MAX_RECONCILIATION_RETRIES),
1240 strings("reviewer_evidence_handles"),
1241 strings("verifier_evidence_handles"),
1242 bounded_text("verification_outcome").unwrap_or_default(),
1243 )
1244 .map_err(ToolError::invalid_input)
1245 .and_then(|receipt| {
1246 serde_json::to_value(receipt)
1247 .map_err(|e| ToolError::execution_failed(e.to_string()))
1248 }),
1249 "release" => {
1250 let owner = input
1251 .get("owner")
1252 .and_then(Value::as_str)
1253 .map(|value| value.to_string());
1254 let released = manager
1255 .release_stale_write_claims(owner)
1256 .map_err(ToolError::invalid_input)?;
1257 let sequence = manager.coordination.sequence;
1258 serde_json::to_value(json!({
1259 "released": released.len(),
1260 "owners": released,
1261 "sequence": sequence
1262 }))
1263 .map_err(|e| ToolError::execution_failed(e.to_string()))
1264 }
1265 _ => unreachable!("coordination action validated above"),
1266 };
1267 let value = match mutation {
1268 Ok(value) => value,
1269 Err(error) => {
1270 // Contention failures deliberately append a durable receipt.
1271 // Stamp and persist every sequence allocated by the failed
1272 // action before returning its error; validation failures that
1273 // did not mutate the ledger allocate nothing.
1274 let first_new_sequence = coordination_before.sequence.saturating_add(1);
1275 let last_new_sequence = manager.coordination.sequence;
1276 for sequence in first_new_sequence..=last_new_sequence {
1277 if let Err(stamp_error) =
1278 manager.stamp_coordination_sequence_for_session(sequence, session)
1279 {
1280 manager.coordination = coordination_before;
1281 return Err(ToolError::execution_failed(format!(
1282 "{error}; additionally failed to stamp coordination receipt: {stamp_error}"
1283 )));
1284 }
1285 }
1286 if last_new_sequence >= first_new_sequence
1287 && let Err(persist_error) = manager.persist_state_synchronously()
1288 {
1289 manager.coordination = coordination_before;
1290 return Err(ToolError::execution_failed(format!(
1291 "{error}; additionally failed to persist coordination receipt: {persist_error}"
1292 )));
1293 }
1294 return Err(error);
1295 }
1296 };
1297 let Some(sequence) = value.get("sequence").and_then(Value::as_u64) else {
1298 manager.coordination = coordination_before;
1299 return Err(ToolError::execution_failed(format!(
1300 "coordination action '{action}' produced no durable sequence"
1301 )));
1302 };
1303 if let Err(error) = manager.stamp_coordination_sequence_for_session(sequence, session) {
1304 manager.coordination = coordination_before;
1305 return Err(ToolError::execution_failed(error));
1306 }
1307 if let Err(error) = manager.persist_state_synchronously() {
1308 manager.coordination = coordination_before;
1309 return Err(ToolError::execution_failed(format!(
1310 "failed to persist coordination action '{action}': {error}"
1311 )));
1312 }
1313 ToolResult::json(&value).map_err(|e| ToolError::execution_failed(e.to_string()))
1314 }
1315 }
1316
1317 #[async_trait]
1318 impl ToolSpec for AgentsCoordinateTool {
1319 fn name(&self) -> &'static str {
1320 "agents/coordinate"
1321 }
1322
1323 fn description(&self) -> &'static str {
1324 "Record or inspect bounded coordination state: propose/accept/supersede decisions, expand the caller's write claim before mutation, reconcile multiple decision records into one neutral fan-in receipt, or release stale write-claims whose owner is no longer running."
1325 }
1326
1327 fn input_schema(&self) -> Value {
1328 json!({
1329 "type": "object",
1330 "properties": {
1331 "action": { "type": "string", "enum": ["inspect", "propose", "accept", "supersede", "claim", "reconcile", "release"] },
1332 "decision_id": { "type": "string" },
1333 "subject": { "type": "string" },
1334 "expected_version": { "type": "integer", "minimum": 1 },
1335 "scope": { "type": "array", "items": { "type": "string" } },
1336 "constraints": { "type": "array", "items": { "type": "string" } },
1337 "evidence_handles": { "type": "array", "items": { "type": "string" } },
1338 "roots": { "type": "array", "items": { "type": "string" } },
1339 "exact_files": { "type": "array", "items": { "type": "string" } },
1340 "contracts": { "type": "array", "items": { "type": "string" } },
1341 "owner": { "type": "string" },
1342 "input_decisions": { "type": "array", "items": { "type": "string" } },
1343 "outcome": { "type": "string" },
1344 "candidate_handles": { "type": "array", "items": { "type": "string" } },
1345 "retry_count": { "type": "integer", "minimum": 0, "maximum": 3 },
1346 "retry_limit": { "type": "integer", "minimum": 1, "maximum": 3 },
1347 "reviewer_evidence_handles": { "type": "array", "items": { "type": "string" } },
1348 "verifier_evidence_handles": { "type": "array", "items": { "type": "string" } },
1349 "verification_outcome": { "type": "string" },
1350 "limit": { "type": "integer", "minimum": 1, "maximum": 24 }
1351 },
1352 "required": ["action"]
1353 })
1354 }
1355
1356 fn capabilities(&self) -> Vec<ToolCapability> {
1357 // #5123-class: this tool mutates the coordination ledger and expands
1358 // the caller's write claim (actions propose/accept/supersede/claim/
1359 // reconcile) — declaring ReadOnly was a lie that let policy layers
1360 // treat a mutating call as a safe read. Only `inspect` is read-only,
1361 // which is what is_read_only_for reports.
1362 vec![ToolCapability::WritesFiles]
1363 }
1364 fn approval_requirement(&self) -> ApprovalRequirement {
1365 // Stays Auto: coordination records are session-scoped in-memory
1366 // state, and gating them would deadlock autonomous sub-agent fan-in.
1367 ApprovalRequirement::Auto
1368 }
1369 fn is_read_only_for(&self, input: &Value) -> bool {
1370 input.get("action").and_then(Value::as_str) == Some("inspect")
1371 }
1372
1373 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
1374 let action = input
1375 .get("action")
1376 .and_then(Value::as_str)
1377 .unwrap_or("inspect");
1378 let bounded_text = |key: &str| {
1379 input
1380 .get(key)
1381 .and_then(Value::as_str)
1382 .map(|value| value.chars().take(512).collect::<String>())
1383 };
1384 if action == "inspect" {
1385 let manager = self.manager.read().await;
1386 let value = manager.inspect_coordination_for_session(
1387 &context.state_namespace,
1388 bounded_text("subject").as_deref(),
1389 input
1390 .get("limit")
1391 .and_then(Value::as_u64)
1392 .unwrap_or(COORDINATION_INSPECT_LIMIT as u64) as usize,
1393 );
1394 return ToolResult::json(&value)
1395 .map_err(|e| ToolError::execution_failed(e.to_string()));
1396 }
1397 if !matches!(
1398 action,
1399 "propose" | "accept" | "supersede" | "claim" | "reconcile" | "release"
1400 ) {
1401 return Err(ToolError::invalid_input(format!(
1402 "unknown coordination action '{action}'"
1403 )));
1404 }
1405
1406 let manager = self.manager.clone();
1407 let caller = self.caller.clone();
1408 let session = context.state_namespace.clone();
1409 let workspace = context.workspace.clone();
1410 codewhale_runtime::runtime_control::owner_work(move || {
1411 let mut manager = manager.blocking_write();
1412 manager.with_store_transaction(|manager| {
1413 Self::mutate_coordination(caller.as_deref(), &session, &workspace, manager, input)
1414 .map_err(anyhow::Error::new)
1415 })
1416 })
1417 .await
1418 .map_err(|error| match error.downcast::<ToolError>() {
1419 Ok(error) => error,
1420 Err(error) => ToolError::execution_failed(error.to_string()),
1421 })
1422 }
1423 }
1424
1425 #[cfg(test)]
1426 mod tests {
1427 use super::*;
1428 use crate::tools::spec::ToolContext;
1429 use codewhale_models::Role;
1430 use std::collections::BTreeSet;
1431 use tempfile::tempdir;
1432
1433 #[test]
1434 fn coordinate_tool_does_not_declare_read_only() {
1435 // #5123-class: the tool mutates the coordination ledger and expands
1436 // write claims; its declared capabilities must not say ReadOnly.
1437 let manager = Arc::new(tokio::sync::RwLock::new(
1438 super::super::SubAgentManager::new(std::path::PathBuf::from("."), 1),
1439 ));
1440 let tool = AgentsCoordinateTool::new(manager, None);
1441 let capabilities = ToolSpec::capabilities(&tool);
1442 assert!(
1443 !capabilities.contains(&ToolCapability::ReadOnly),
1444 "agents/coordinate mutates the ledger — ReadOnly is a lie: {capabilities:?}"
1445 );
1446 // …but the dynamic check still marks inspect as read-only.
1447 assert!(tool.is_read_only_for(&json!({"action": "inspect"})));
1448 assert!(!tool.is_read_only_for(&json!({"action": "propose"})));
1449 }
1450
1451 #[test]
1452 fn coordination_descriptions_match_implemented_resume_behavior() {
1453 // Checkpoint resume is implemented (#5242): the descriptions must
1454 // describe the real behavior, including the honest queue-only
1455 // fallback when no runtime is attached.
1456 let manager = Arc::new(tokio::sync::RwLock::new(
1457 super::super::SubAgentManager::new(std::env::temp_dir(), 1),
1458 ));
1459 let message = AgentsMessageTool::new(Arc::clone(&manager));
1460 let followup = AgentsFollowupTool::new(manager);
1461
1462 assert!(!message.description().contains("natural resume"));
1463 assert!(message.description().contains("next step boundary"));
1464 assert!(message.description().contains("stays queued"));
1465 assert!(followup.description().contains("attempt to resume"));
1466 assert!(
1467 followup
1468 .description()
1469 .contains("resumed from their checkpoint")
1470 );
1471 assert!(followup.description().contains("queue-only semantics"));
1472 }
1473
1474 async fn manager_with_running_child(
1475 workspace: &std::path::Path,
1476 ) -> (SharedSubAgentManager, String) {
1477 let manager = Arc::new(tokio::sync::RwLock::new(
1478 super::super::SubAgentManager::new(workspace.to_path_buf(), 4),
1479 ));
1480 let agent_id = {
1481 let mut guard = manager.write().await;
1482 guard.insert_test_running_agent("coord_child", workspace)
1483 };
1484 (manager, agent_id)
1485 }
1486
1487 async fn manager_with_agent_hierarchy(
1488 workspace: &std::path::Path,
1489 ) -> (SharedSubAgentManager, String, String, String) {
1490 let manager = Arc::new(tokio::sync::RwLock::new(
1491 super::super::SubAgentManager::new(workspace.to_path_buf(), 8),
1492 ));
1493 let (parent, child, sibling) = {
1494 let mut guard = manager.write().await;
1495 let parent = guard.insert_test_running_agent("hierarchy_parent", workspace);
1496 let child = guard.insert_test_running_agent("hierarchy_child", workspace);
1497 let sibling = guard.insert_test_running_agent("hierarchy_sibling", workspace);
1498 for (agent_id, parent_id) in [
1499 (&parent, "root"),
1500 (&child, parent.as_str()),
1501 (&sibling, "root"),
1502 ] {
1503 let record = guard
1504 .worker_records
1505 .get_mut(agent_id)
1506 .expect("hierarchy worker record");
1507 record.parent_run_id = Some(parent_id.to_string());
1508 record.spec.parent_run_id = Some(parent_id.to_string());
1509 }
1510 (parent, child, sibling)
1511 };
1512 (manager, parent, child, sibling)
1513 }
1514
1515 #[tokio::test]
1516 async fn message_queues_when_running_child_has_no_live_channel() {
1517 let tmp = tempdir().unwrap();
1518 let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
1519 let tool = AgentsMessageTool::new(Arc::clone(&manager));
1520 let result = tool
1521 .execute(
1522 json!({ "agent_id": agent_id, "message": "hold this" }),
1523 &ToolContext::new(tmp.path()),
1524 )
1525 .await
1526 .expect("message ok");
1527 let body: Value = serde_json::from_str(&result.content).unwrap();
1528 assert_eq!(body["woke"], json!(false));
1529 assert_eq!(body["queued"], json!(true));
1530 assert!(body.get("delivered").is_none(), "{body}");
1531 assert_eq!(body["queue_depth"], json!(1));
1532
1533 let guard = manager.read().await;
1534 let depth = guard.queued_mail_depth(&agent_id).unwrap();
1535 assert_eq!(depth, 1);
1536 assert!(!guard.child_was_woken(&agent_id));
1537 }
1538
1539 #[tokio::test]
1540 async fn followup_does_not_claim_wake_when_live_channel_is_closed() {
1541 let tmp = tempdir().unwrap();
1542 let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
1543 let result = AgentsFollowupTool::new(Arc::clone(&manager))
1544 .execute(
1545 json!({ "agent_id": agent_id, "message": "try to wake" }),
1546 &ToolContext::new(tmp.path()),
1547 )
1548 .await
1549 .expect("truthful closed-channel receipt");
1550 let body: Value = serde_json::from_str(&result.content).unwrap();
1551 assert_eq!(body["woke"], json!(false));
1552 assert_eq!(body["queue_depth"], json!(1));
1553 assert!(
1554 body["note"].as_str().unwrap_or_default().contains("closed"),
1555 "{body}"
1556 );
1557
1558 let guard = manager.read().await;
1559 assert_eq!(guard.queued_mail_depth(&agent_id), Some(1));
1560 assert!(!guard.child_was_woken(&agent_id));
1561 }
1562
1563 #[tokio::test]
1564 async fn hierarchy_mutations_allow_own_descendants_and_deny_siblings_or_ancestors() {
1565 let tmp = tempdir().unwrap();
1566 let (manager, parent, child, sibling) = manager_with_agent_hierarchy(tmp.path()).await;
1567 let context = ToolContext::new(tmp.path());
1568
1569 AgentsMessageTool::new(Arc::clone(&manager))
1570 .with_optional_caller(Some(parent.clone()))
1571 .execute(
1572 json!({ "agent_id": child, "message": "bounded parent note" }),
1573 &context,
1574 )
1575 .await
1576 .expect("parent may message its own child");
1577 AgentsFollowupTool::new(Arc::clone(&manager))
1578 .with_optional_caller(Some(parent.clone()))
1579 .execute(
1580 json!({ "agent_id": child, "message": "resume own child" }),
1581 &context,
1582 )
1583 .await
1584 .expect("parent may follow up its own child");
1585
1586 let sibling_message = AgentsMessageTool::new(Arc::clone(&manager))
1587 .with_optional_caller(Some(parent.clone()))
1588 .execute(
1589 json!({ "agent_id": sibling, "message": "cross branch" }),
1590 &context,
1591 )
1592 .await
1593 .expect_err("sibling message must fail closed")
1594 .to_string();
1595 assert!(
1596 sibling_message.contains("own descendants"),
1597 "{sibling_message}"
1598 );
1599
1600 let ancestor_followup = AgentsFollowupTool::new(Arc::clone(&manager))
1601 .with_optional_caller(Some(child.clone()))
1602 .execute(
1603 json!({ "agent_id": parent, "message": "wake ancestor" }),
1604 &context,
1605 )
1606 .await
1607 .expect_err("ancestor followup must fail closed")
1608 .to_string();
1609 assert!(
1610 ancestor_followup.contains("own descendants"),
1611 "{ancestor_followup}"
1612 );
1613
1614 let sibling_interrupt = AgentsInterruptTool::new(Arc::clone(&manager))
1615 .with_optional_caller(Some(parent.clone()))
1616 .execute(json!({ "agent_id": sibling }), &context)
1617 .await
1618 .expect_err("sibling interrupt must fail closed")
1619 .to_string();
1620 assert!(
1621 sibling_interrupt.contains("own descendants"),
1622 "{sibling_interrupt}"
1623 );
1624
1625 let interrupted = AgentsInterruptTool::new(Arc::clone(&manager))
1626 .with_optional_caller(Some(parent))
1627 .execute(json!({ "agent_id": child }), &context)
1628 .await
1629 .expect("parent may interrupt its own child");
1630 let body: Value = serde_json::from_str(&interrupted.content).unwrap();
1631 assert_eq!(body["status"], json!("interrupted"));
1632 }
1633
1634 #[tokio::test]
1635 async fn coordinate_inspect_is_side_effect_free_and_mutations_are_synchronously_durable() {
1636 let tmp = tempdir().unwrap();
1637 let blocked_state_path = tmp.path().join("blocked-state");
1638 std::fs::create_dir(&blocked_state_path).unwrap();
1639 let blocked_manager = Arc::new(tokio::sync::RwLock::new(
1640 super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
1641 .with_state_path(blocked_state_path),
1642 ));
1643 let blocked_tool = AgentsCoordinateTool::new(Arc::clone(&blocked_manager), None);
1644
1645 blocked_tool
1646 .execute(
1647 json!({ "action": "inspect" }),
1648 &ToolContext::new(tmp.path()),
1649 )
1650 .await
1651 .expect("read-only inspect must not attempt persistence");
1652 let error = blocked_tool
1653 .execute(
1654 json!({
1655 "action": "propose",
1656 "decision_id": "durable-decision",
1657 "subject": "durability",
1658 "constraints": ["persist before acknowledgement"]
1659 }),
1660 &ToolContext::new(tmp.path()),
1661 )
1662 .await
1663 .expect_err("mutation must fail when its receipt cannot persist")
1664 .to_string();
1665 assert!(
1666 error.contains("delegated durable store admission failed"),
1667 "{error}"
1668 );
1669 assert!(
1670 blocked_manager
1671 .read()
1672 .await
1673 .coordination
1674 .decisions
1675 .is_empty(),
1676 "failed persistence must roll the in-memory decision back"
1677 );
1678
1679 let durable_workspace = tempdir().unwrap();
1680 let state_path = durable_workspace.path().join("subagents.v1.json");
1681 let manager = Arc::new(tokio::sync::RwLock::new(
1682 super::super::SubAgentManager::new(durable_workspace.path().to_path_buf(), 4)
1683 .with_state_path(state_path.clone()),
1684 ));
1685 AgentsCoordinateTool::new(Arc::clone(&manager), None)
1686 .execute(
1687 json!({
1688 "action": "propose",
1689 "decision_id": "durable-decision",
1690 "subject": "durability",
1691 "constraints": ["persist before acknowledgement"]
1692 }),
1693 &ToolContext::new(durable_workspace.path()),
1694 )
1695 .await
1696 .expect("durable mutation");
1697 let mut replayed =
1698 super::super::SubAgentManager::new(durable_workspace.path().to_path_buf(), 4)
1699 .with_state_path(state_path);
1700 replayed.load_state().expect("reload durable action");
1701 assert_eq!(replayed.coordination.decisions.len(), 1);
1702 assert_eq!(
1703 replayed.coordination.decisions[0].decision_id,
1704 "durable-decision"
1705 );
1706 }
1707
1708 #[tokio::test]
1709 async fn release_action_clears_only_stale_write_claims_and_persists() {
1710 let tmp = tempdir().unwrap();
1711 let state_path = tmp.path().join("subagents.v1.json");
1712 let manager = Arc::new(tokio::sync::RwLock::new(
1713 super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
1714 .with_state_path(state_path.clone()),
1715 ));
1716 let live = {
1717 let mut guard = manager.write().await;
1718 guard
1719 .with_store_transaction(|guard| {
1720 let live = guard.insert_test_running_agent("live-builder", tmp.path());
1721 let active = [live.clone()].into_iter().collect::<BTreeSet<_>>();
1722 for claim in [
1723 WriteScopeClaim {
1724 owner: live.clone(),
1725 roots: vec!["src/live".into()],
1726 exact_files: Vec::new(),
1727 contracts: Vec::new(),
1728 },
1729 WriteScopeClaim {
1730 owner: "zombie-builder".into(),
1731 roots: vec!["src/zombie".into()],
1732 exact_files: Vec::new(),
1733 contracts: Vec::new(),
1734 },
1735 ] {
1736 guard
1737 .coordination
1738 .register_claim(claim, false, |candidate| active.contains(candidate))
1739 .expect("initial claim");
1740 }
1741 guard.persist_state_synchronously()?;
1742 Ok(live)
1743 })
1744 .unwrap()
1745 };
1746
1747 let result = AgentsCoordinateTool::new(Arc::clone(&manager), None)
1748 .execute(
1749 json!({ "action": "release" }),
1750 &ToolContext::new(tmp.path()),
1751 )
1752 .await
1753 .expect("release sweeps stale claims");
1754 let body: Value = serde_json::from_str(&result.content).unwrap();
1755 assert_eq!(body["released"], json!(1));
1756 assert_eq!(body["owners"], json!(["zombie-builder"]));
1757
1758 // The sweep is durable: reloading the ledger keeps only the live claim.
1759 let mut replayed = super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
1760 .with_state_path(state_path);
1761 replayed.load_state().expect("reload released ledger");
1762 assert_eq!(replayed.coordination.write_claims.len(), 1);
1763 assert_eq!(replayed.coordination.write_claims[0].claim.owner, live);
1764
1765 // Named-owner release of a live claimant is a no-op and still succeeds.
1766 let noop = AgentsCoordinateTool::new(Arc::clone(&manager), None)
1767 .execute(
1768 json!({ "action": "release", "owner": live }),
1769 &ToolContext::new(tmp.path()),
1770 )
1771 .await
1772 .expect("live release is a no-op");
1773 let body: Value = serde_json::from_str(&noop.content).unwrap();
1774 assert_eq!(body["released"], json!(0));
1775 }
1776
1777 #[tokio::test]
1778 async fn rejected_claim_contention_is_persisted_before_returning_the_error() {
1779 let tmp = tempdir().unwrap();
1780 let state_path = tmp.path().join("subagents.v1.json");
1781 let manager = Arc::new(tokio::sync::RwLock::new(
1782 super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
1783 .with_state_path(state_path.clone()),
1784 ));
1785 let (claimant, owner) = {
1786 let mut guard = manager.write().await;
1787 guard
1788 .with_store_transaction(|guard| {
1789 let claimant = guard.insert_test_running_agent("claimant", tmp.path());
1790 let owner = guard.insert_test_running_agent("owner", tmp.path());
1791 let active = [claimant.clone(), owner.clone()]
1792 .into_iter()
1793 .collect::<BTreeSet<_>>();
1794 for claim in [
1795 WriteScopeClaim {
1796 owner: claimant.clone(),
1797 roots: vec!["src/claimant".into()],
1798 exact_files: Vec::new(),
1799 contracts: Vec::new(),
1800 },
1801 WriteScopeClaim {
1802 owner: owner.clone(),
1803 roots: vec!["src/shared".into()],
1804 exact_files: Vec::new(),
1805 contracts: Vec::new(),
1806 },
1807 ] {
1808 guard
1809 .coordination
1810 .register_claim(claim, false, |candidate| active.contains(candidate))
1811 .expect("initial non-overlapping claim");
1812 }
1813 Ok((claimant, owner))
1814 })
1815 .unwrap()
1816 };
1817
1818 let error = AgentsCoordinateTool::new(Arc::clone(&manager), Some(claimant.clone()))
1819 .execute(
1820 json!({ "action": "claim", "roots": ["src/shared/nested"] }),
1821 &ToolContext::new(tmp.path()),
1822 )
1823 .await
1824 .expect_err("overlap must block")
1825 .to_string();
1826 assert!(
1827 error.contains(&owner) && error.contains("contention"),
1828 "{error}"
1829 );
1830
1831 let mut replayed = super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
1832 .with_state_path(state_path);
1833 replayed.load_state().expect("reload contention receipt");
1834 assert_eq!(replayed.coordination.contentions.len(), 1);
1835 assert_eq!(replayed.coordination.contentions[0].claimant, claimant);
1836 assert_eq!(
1837 replayed.coordination.contentions[0].conflicting_owner,
1838 owner
1839 );
1840 }
1841
1842 #[tokio::test]
1843 async fn coordination_resolution_survives_reload_and_resolving_claim_eviction() {
1844 let tmp = tempdir().unwrap();
1845 let state_path = tmp.path().join("subagents.v1.json");
1846 let manager = Arc::new(tokio::sync::RwLock::new(
1847 super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
1848 .with_state_path(state_path.clone()),
1849 ));
1850 let claimant = {
1851 let mut guard = manager.write().await;
1852 guard
1853 .with_store_transaction(|guard| {
1854 let claimant = guard.insert_test_running_agent("claimant", tmp.path());
1855 let owner = guard.insert_test_running_agent("owner", tmp.path());
1856 let active = [claimant.clone(), owner.clone()]
1857 .into_iter()
1858 .collect::<BTreeSet<_>>();
1859 for claim in [
1860 WriteScopeClaim {
1861 owner: claimant.clone(),
1862 roots: vec!["src/claimant".into()],
1863 exact_files: Vec::new(),
1864 contracts: Vec::new(),
1865 },
1866 WriteScopeClaim {
1867 owner: owner.clone(),
1868 roots: vec!["src/shared".into()],
1869 exact_files: Vec::new(),
1870 contracts: Vec::new(),
1871 },
1872 ] {
1873 guard
1874 .coordination
1875 .register_claim(claim, false, |candidate| active.contains(candidate))
1876 .expect("initial non-overlapping claim");
1877 }
1878 Ok(claimant)
1879 })
1880 .unwrap()
1881 };
1882
1883 AgentsCoordinateTool::new(Arc::clone(&manager), Some(claimant.clone()))
1884 .execute(
1885 json!({ "action": "claim", "roots": ["src/shared/nested"] }),
1886 &ToolContext::new(tmp.path()),
1887 )
1888 .await
1889 .expect_err("overlap must block and persist its receipt");
1890
1891 let resolution_sequence = {
1892 let mut guard = manager.write().await;
1893 guard
1894 .with_store_transaction(|guard| {
1895 let record = guard
1896 .coordination
1897 .register_claim(
1898 WriteScopeClaim {
1899 owner: claimant.clone(),
1900 roots: vec!["src/isolated".into()],
1901 exact_files: Vec::new(),
1902 contracts: Vec::new(),
1903 },
1904 true,
1905 |_| true,
1906 )
1907 .expect("later isolated claim resolves contention");
1908 guard
1909 .persist_state_synchronously()
1910 .expect("persist resolved contention");
1911 Ok(record.sequence)
1912 })
1913 .unwrap()
1914 };
1915
1916 let mut replayed = super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
1917 .with_state_path(state_path.clone());
1918 replayed.load_state().expect("reload resolved contention");
1919 assert_eq!(replayed.coordination.contentions.len(), 1);
1920 assert_eq!(
1921 replayed.coordination.contentions[0].disposition,
1922 WriteContentionDisposition::ResolvedBySuccessfulClaim
1923 );
1924 assert_eq!(
1925 replayed.coordination.contentions[0].resolution_sequence,
1926 Some(resolution_sequence)
1927 );
1928
1929 replayed
1930 .with_store_transaction(|held| {
1931 let slots = COORDINATION_RECORD_LIMIT - held.coordination.write_claims.len();
1932 for index in 0..slots {
1933 held.coordination
1934 .register_claim(
1935 WriteScopeClaim {
1936 owner: format!("inactive-fill-{index:03}"),
1937 roots: vec![format!("pkg/fill-{index:03}")],
1938 exact_files: Vec::new(),
1939 contracts: Vec::new(),
1940 },
1941 true,
1942 |_| false,
1943 )
1944 .expect("fill inactive claim capacity");
1945 }
1946 for index in 0..2 {
1947 held.coordination
1948 .register_claim(
1949 WriteScopeClaim {
1950 owner: format!("inactive-overflow-{index}"),
1951 roots: vec![format!("pkg/overflow-{index}")],
1952 exact_files: Vec::new(),
1953 contracts: Vec::new(),
1954 },
1955 true,
1956 |_| false,
1957 )
1958 .expect("evict oldest inactive claim at capacity");
1959 }
1960 assert!(
1961 !held
1962 .coordination
1963 .write_claims
1964 .iter()
1965 .any(|claim| claim.claim.owner == claimant),
1966 "the resolving claimant claim must be evicted for the durability regression"
1967 );
1968 held.persist_state_synchronously()
1969 .expect("persist after inactive claim eviction");
1970 Ok(())
1971 })
1972 .unwrap();
1973
1974 let mut final_replay = super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
1975 .with_state_path(state_path);
1976 final_replay
1977 .load_state()
1978 .expect("reload after resolving claim eviction");
1979 let projection = final_replay.coordination_detail_projection(None, 24);
1980 assert!(
1981 !projection
1982 .write_claims
1983 .iter()
1984 .any(|claim| claim.claim.owner == claimant)
1985 );
1986 assert_eq!(projection.contentions.len(), 1);
1987 assert_eq!(
1988 projection.contentions[0].disposition,
1989 WriteContentionDisposition::ResolvedBySuccessfulClaim
1990 );
1991 assert_eq!(
1992 projection.contentions[0].resolution_sequence,
1993 Some(resolution_sequence)
1994 );
1995 }
1996
1997 #[tokio::test]
1998 async fn interrupt_fails_closed_on_self() {
1999 let tmp = tempdir().unwrap();
2000 let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
2001 let tool = AgentsInterruptTool::new(Arc::clone(&manager)).with_caller(agent_id.clone());
2002 let err = tool
2003 .execute(
2004 json!({ "agent_id": agent_id }),
2005 &ToolContext::new(tmp.path()),
2006 )
2007 .await
2008 .expect_err("self interrupt must fail");
2009 let msg = err.to_string().to_ascii_lowercase();
2010 assert!(
2011 msg.contains("self") || msg.contains("own"),
2012 "unexpected error: {err}"
2013 );
2014 }
2015
2016 #[tokio::test]
2017 async fn interrupt_fails_closed_on_missing_target() {
2018 let tmp = tempdir().unwrap();
2019 let manager = Arc::new(tokio::sync::RwLock::new(
2020 super::super::SubAgentManager::new(tmp.path().to_path_buf(), 2),
2021 ));
2022 let tool = AgentsInterruptTool::new(manager);
2023 let err = tool
2024 .execute(
2025 json!({ "agent_id": "agent_missing" }),
2026 &ToolContext::new(tmp.path()),
2027 )
2028 .await
2029 .expect_err("missing target");
2030 assert!(err.to_string().contains("not found") || err.to_string().contains("Agent"));
2031 }
2032
2033 #[tokio::test]
2034 async fn wait_times_out_when_child_stays_running() {
2035 let tmp = tempdir().unwrap();
2036 let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
2037 let tool = AgentsWaitTool::new(manager);
2038 let result = tool
2039 .execute(
2040 json!({
2041 "agent_id": agent_id,
2042 "timeout_secs": 1,
2043 "until": "activity"
2044 }),
2045 &ToolContext::new(tmp.path()),
2046 )
2047 .await
2048 .expect("wait returns");
2049 let body: Value = serde_json::from_str(&result.content).unwrap();
2050 assert_eq!(body["timed_out"], json!(true));
2051 }
2052
2053 #[tokio::test]
2054 async fn list_resolves_target_and_reports_queue() {
2055 let tmp = tempdir().unwrap();
2056 let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
2057 {
2058 let mut guard = manager.write().await;
2059 guard
2060 .queue_parent_message(&agent_id, "note".into(), false)
2061 .unwrap();
2062 }
2063 let tool = AgentsListTool::new(manager);
2064 let result = tool
2065 .execute(
2066 json!({ "agent_id": agent_id }),
2067 &ToolContext::new(tmp.path()),
2068 )
2069 .await
2070 .expect("list ok");
2071 let body: Value = serde_json::from_str(&result.content).unwrap();
2072 assert_eq!(body["count"], json!(1));
2073 assert_eq!(body["agents"][0]["agent_id"], json!(agent_id));
2074 assert!(body["agents"][0]["queued_mail"].as_u64().unwrap_or(0) >= 1);
2075 }
2076
2077 #[tokio::test]
2078 async fn followup_interrupted_continuable_without_runtime_queues_honestly() {
2079 let tmp = tempdir().unwrap();
2080 let manager = Arc::new(tokio::sync::RwLock::new(
2081 super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4),
2082 ));
2083 let (agent_id, handle) = {
2084 let mut guard = manager.write().await;
2085 guard.insert_test_interrupted_continuable_agent(
2086 "paused_child",
2087 tmp.path(),
2088 vec![codewhale_models::Message {
2089 role: Role::User,
2090 content: vec![codewhale_models::ContentBlock::Text {
2091 text: "prior work".to_string(),
2092 cache_control: None,
2093 }],
2094 }],
2095 )
2096 };
2097 // No runtime attached: checkpoint resume is unavailable, so followup
2098 // keeps the honest queue-only semantics with the continuation handle.
2099 let tool = AgentsFollowupTool::new(Arc::clone(&manager));
2100 let result = tool
2101 .execute(
2102 json!({ "agent_id": agent_id, "message": "please continue" }),
2103 &ToolContext::new(tmp.path()),
2104 )
2105 .await
2106 .expect("followup ok");
2107 let body: Value = serde_json::from_str(&result.content).unwrap();
2108 assert_eq!(body["queued"], json!(true));
2109 assert_eq!(body["woke"], json!(false));
2110 assert_eq!(body["continued_from_checkpoint"], json!(false));
2111 assert_eq!(body["continuation_handle"], json!(handle));
2112 let note = body["note"].as_str().unwrap_or_default();
2113 assert!(
2114 note.contains("with a runtime attached")
2115 && note.contains("agent action=followup")
2116 && note.contains(&handle),
2117 "note must point at the resume path with the continuation handle: {note}"
2118 );
2119
2120 let guard = manager.read().await;
2121 assert_eq!(guard.queued_mail_depth(&agent_id).unwrap(), 1);
2122 assert!(!guard.child_was_woken(&agent_id));
2123 }
2124
2125 // === until="all": the fan-out join ===================================
2126 //
2127 // Before this existed a parent with five children had to issue five
2128 // waits — while the prompt told it not to poll. These lock the join in.
2129
2130 fn empty_manager(workspace: &std::path::Path) -> SharedSubAgentManager {
2131 Arc::new(tokio::sync::RwLock::new(
2132 super::super::SubAgentManager::new(workspace.to_path_buf(), 8),
2133 ))
2134 }
2135
2136 async fn settle(manager: &SharedSubAgentManager, agent_id: &str, status: SubAgentStatus) {
2137 let mut guard = manager.write().await;
2138 if let Some(agent) = guard.agents.get_mut(agent_id) {
2139 agent.status = status;
2140 }
2141 }
2142
2143 #[test]
2144 fn wait_schema_offers_all_as_a_first_class_until() {
2145 let tmp = tempdir().unwrap();
2146 let tool = AgentsWaitTool::new(empty_manager(tmp.path()));
2147 let schema = tool.input_schema();
2148 let until = &schema["properties"]["until"];
2149 assert_eq!(
2150 until["enum"],
2151 json!(["completion", "all", "activity"]),
2152 "until must expose all alongside completion/activity: {schema}"
2153 );
2154 let described = until["description"].as_str().unwrap_or_default();
2155 assert!(
2156 described.contains("every watched child") && described.contains("any one child"),
2157 "the schema must make completion vs all unmistakable: {described}"
2158 );
2159 }
2160
2161 #[tokio::test]
2162 async fn wait_until_all_on_an_already_settled_child_reports_its_outcome() {
2163 let tmp = tempdir().unwrap();
2164 let manager = empty_manager(tmp.path());
2165 let agent_id = {
2166 let mut guard = manager.write().await;
2167 guard.insert_test_running_agent("all_already_done", tmp.path())
2168 };
2169 settle(&manager, &agent_id, SubAgentStatus::Completed).await;
2170
2171 let result = dispatch_wait(
2172 &json!({ "until": "all", "agent_id": agent_id, "timeout_secs": 60 }),
2173 Arc::clone(&manager),
2174 &ToolContext::new(tmp.path()),
2175 )
2176 .await
2177 .expect("a settled child is an immediate return");
2178 let body: Value = serde_json::from_str(&result.content).unwrap();
2179 assert_eq!(body["all_settled"], json!(true), "{body}");
2180 let settled = body["settled"].as_array().unwrap();
2181 assert_eq!(settled.len(), 1, "{body}");
2182 assert_eq!(settled[0]["status"], json!("completed"), "{body}");
2183 }
2184
2185 #[tokio::test]
2186 async fn foreign_session_is_excluded_from_default_and_explicit_list_waits() {
2187 let tmp = tempdir().unwrap();
2188 let manager = empty_manager(tmp.path());
2189 let agent_a = {
2190 let mut guard = manager.write().await;
2191 let agent_id = guard.insert_test_running_agent("foreign_wait_a", tmp.path());
2192 guard.assign_test_session_owner(&agent_id, "session-a");
2193 agent_id
2194 };
2195 let context_b = ToolContext::new(tmp.path()).with_state_namespace("session-b");
2196
2197 let listed = AgentsListTool::new(Arc::clone(&manager))
2198 .execute(json!({}), &context_b)
2199 .await
2200 .expect("B list");
2201 let listed: Value = serde_json::from_str(&listed.content).unwrap();
2202 assert_eq!(listed["count"], json!(0));
2203
2204 let default_wait = dispatch_wait(
2205 &json!({ "until": "all", "timeout_secs": 60 }),
2206 Arc::clone(&manager),
2207 &context_b,
2208 )
2209 .await
2210 .expect("B default wait has no visible children");
2211 let default_wait: Value = serde_json::from_str(&default_wait.content).unwrap();
2212 assert!(default_wait["settled"].as_array().unwrap().is_empty());
2213
2214 let error = dispatch_wait(
2215 &json!({ "until": "all", "agent_id": agent_a, "timeout_secs": 60 }),
2216 manager,
2217 &context_b,
2218 )
2219 .await
2220 .expect_err("B explicit wait must reject A")
2221 .to_string();
2222 assert!(
2223 error.contains("Agent not found in the active session"),
2224 "{error}"
2225 );
2226 }
2227
2228 #[tokio::test]
2229 async fn wait_until_all_returns_immediately_with_no_children() {
2230 let tmp = tempdir().unwrap();
2231 let started = Instant::now();
2232 let result = dispatch_wait(
2233 &json!({ "until": "all", "timeout_secs": 60 }),
2234 empty_manager(tmp.path()),
2235 &ToolContext::new(tmp.path()),
2236 )
2237 .await
2238 .expect("wait-for-all with zero children must return, not hang");
2239 assert!(
2240 started.elapsed() < Duration::from_secs(5),
2241 "zero children must not burn the timeout"
2242 );
2243 let body: Value = serde_json::from_str(&result.content).unwrap();
2244 assert_eq!(body["all_settled"], json!(true));
2245 assert_eq!(body["timed_out"], json!(false));
2246 assert!(body["settled"].as_array().unwrap().is_empty(), "{body}");
2247 }
2248
2249 #[tokio::test]
2250 async fn wait_until_all_blocks_until_every_child_settles() {
2251 let tmp = tempdir().unwrap();
2252 let manager = empty_manager(tmp.path());
2253 let (first, second, third) = {
2254 let mut guard = manager.write().await;
2255 (
2256 guard.insert_test_running_agent("all_first", tmp.path()),
2257 guard.insert_test_running_agent("all_second", tmp.path()),
2258 guard.insert_test_running_agent("all_third", tmp.path()),
2259 )
2260 };
2261
2262 // Staggered settles: an `until=completion` wait would return after the
2263 // first one. `until=all` must stay blocked through the last.
2264 let flip = Arc::clone(&manager);
2265 let (a, b, c) = (first.clone(), second.clone(), third.clone());
2266 tokio::spawn(async move {
2267 tokio::time::sleep(Duration::from_millis(50)).await;
2268 settle(&flip, &a, SubAgentStatus::Completed).await;
2269 tokio::time::sleep(Duration::from_millis(150)).await;
2270 settle(&flip, &b, SubAgentStatus::Failed("boom".to_string())).await;
2271 tokio::time::sleep(Duration::from_millis(150)).await;
2272 settle(&flip, &c, SubAgentStatus::Cancelled).await;
2273 });
2274
2275 let result = dispatch_wait(
2276 &json!({ "until": "all", "timeout_secs": 30 }),
2277 Arc::clone(&manager),
2278 &ToolContext::new(tmp.path()),
2279 )
2280 .await
2281 .expect("wait-for-all should succeed");
2282 let body: Value = serde_json::from_str(&result.content).unwrap();
2283 assert_eq!(body["all_settled"], json!(true), "{body}");
2284 assert_eq!(body["timed_out"], json!(false), "{body}");
2285 assert!(
2286 body["still_running"].as_array().unwrap().is_empty(),
2287 "{body}"
2288 );
2289
2290 // Per-child outcomes come back on the single return.
2291 let settled = body["settled"].as_array().unwrap();
2292 assert_eq!(settled.len(), 3, "{body}");
2293 let outcomes: std::collections::BTreeMap<&str, &str> = settled
2294 .iter()
2295 .map(|entry| {
2296 (
2297 entry["agent_id"].as_str().unwrap(),
2298 entry["status"].as_str().unwrap(),
2299 )
2300 })
2301 .collect();
2302 assert_eq!(outcomes.get(first.as_str()), Some(&"completed"), "{body}");
2303 assert_eq!(outcomes.get(second.as_str()), Some(&"failed"), "{body}");
2304 assert_eq!(outcomes.get(third.as_str()), Some(&"cancelled"), "{body}");
2305 }
2306
2307 #[tokio::test]
2308 async fn wait_until_all_times_out_reporting_settled_and_still_running() {
2309 let tmp = tempdir().unwrap();
2310 let manager = empty_manager(tmp.path());
2311 let (done, stuck) = {
2312 let mut guard = manager.write().await;
2313 (
2314 guard.insert_test_running_agent("all_done", tmp.path()),
2315 guard.insert_test_running_agent("all_stuck", tmp.path()),
2316 )
2317 };
2318
2319 let request = json!({ "until": "all", "timeout_secs": 1 });
2320 let context = ToolContext::new(tmp.path());
2321 let wait = dispatch_wait(&request, Arc::clone(&manager), &context);
2322 tokio::pin!(wait);
2323 // Capture both running children before completing one. The timeout
2324 // receipt must not depend on a background task winning a 50ms race.
2325 assert!(futures_util::poll!(wait.as_mut()).is_pending());
2326 settle(&manager, &done, SubAgentStatus::Completed).await;
2327
2328 let result = wait
2329 .await
2330 .expect("a timeout is a partial receipt, not an error");
2331 let body: Value = serde_json::from_str(&result.content).unwrap();
2332 assert_eq!(body["timed_out"], json!(true), "{body}");
2333 assert_eq!(body["all_settled"], json!(false), "{body}");
2334
2335 let settled = body["settled"].as_array().unwrap();
2336 assert_eq!(settled.len(), 1, "{body}");
2337 assert_eq!(settled[0]["agent_id"], json!(done), "{body}");
2338 assert_eq!(settled[0]["status"], json!("completed"), "{body}");
2339
2340 let running = body["still_running"].as_array().unwrap();
2341 assert_eq!(running.len(), 1, "{body}");
2342 assert_eq!(running[0]["agent_id"], json!(stuck), "{body}");
2343 }
2344
2345 #[tokio::test]
2346 async fn wait_until_all_ignores_children_spawned_mid_wait() {
2347 let tmp = tempdir().unwrap();
2348 let manager = empty_manager(tmp.path());
2349 let original = {
2350 let mut guard = manager.write().await;
2351 guard.insert_test_running_agent("all_original", tmp.path())
2352 };
2353
2354 let flip = Arc::clone(&manager);
2355 let tmp_path = tmp.path().to_path_buf();
2356 let original_id = original.clone();
2357 tokio::spawn(async move {
2358 tokio::time::sleep(Duration::from_millis(50)).await;
2359 {
2360 let mut guard = flip.write().await;
2361 guard.insert_test_running_agent("all_latecomer", &tmp_path);
2362 }
2363 settle(&flip, &original_id, SubAgentStatus::Completed).await;
2364 });
2365
2366 let result = dispatch_wait(
2367 &json!({ "until": "all", "timeout_secs": 30 }),
2368 Arc::clone(&manager),
2369 &ToolContext::new(tmp.path()),
2370 )
2371 .await
2372 .expect("wait-for-all should succeed");
2373 let body: Value = serde_json::from_str(&result.content).unwrap();
2374 // The watch set is the batch as of call time: the latecomer must not
2375 // extend a wait the caller never asked to include it in.
2376 assert_eq!(body["all_settled"], json!(true), "{body}");
2377 assert_eq!(body["timed_out"], json!(false), "{body}");
2378 let settled = body["settled"].as_array().unwrap();
2379 assert_eq!(settled.len(), 1, "{body}");
2380 assert_eq!(settled[0]["agent_id"], json!(original), "{body}");
2381 }
2382
2383 #[tokio::test]
2384 async fn wait_rejects_unknown_until_naming_every_supported_mode() {
2385 let tmp = tempdir().unwrap();
2386 let error = dispatch_wait(
2387 &json!({ "until": "forever" }),
2388 empty_manager(tmp.path()),
2389 &ToolContext::new(tmp.path()),
2390 )
2391 .await
2392 .expect_err("an unknown until must fail loudly");
2393 let message = error.to_string();
2394 for mode in ["completion", "all", "activity"] {
2395 assert!(message.contains(mode), "{message}");
2396 }
2397 }
2398
2399 #[tokio::test]
2400 async fn followup_interrupted_continuable_resumes_with_runtime() {
2401 let tmp = tempdir().unwrap();
2402 let manager = Arc::new(tokio::sync::RwLock::new(
2403 super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4),
2404 ));
2405 let (agent_id, _handle) = {
2406 let mut guard = manager.write().await;
2407 let interrupted = guard.insert_test_interrupted_continuable_agent(
2408 "paused_child",
2409 tmp.path(),
2410 vec![codewhale_models::Message {
2411 role: Role::User,
2412 content: vec![codewhale_models::ContentBlock::Text {
2413 text: "prior work".to_string(),
2414 cache_control: None,
2415 }],
2416 }],
2417 );
2418 // This fixture is resumed by root, rather than a fabricated parent_session agent.
2419 let record = guard.worker_records.get_mut(&interrupted.0).unwrap();
2420 record.parent_run_id = None;
2421 record.spec.parent_run_id = None;
2422 interrupted
2423 };
2424 let mut runtime = super::super::tests::stub_runtime();
2425 runtime.manager = Arc::clone(&manager);
2426 runtime.context = ToolContext::new(tmp.path());
2427 let tool = AgentsFollowupTool::new(Arc::clone(&manager)).with_runtime(runtime);
2428 let result = tool
2429 .execute(
2430 json!({ "agent_id": agent_id, "message": "please continue" }),
2431 &ToolContext::new(tmp.path()),
2432 )
2433 .await
2434 .expect("followup ok");
2435 let body: Value = serde_json::from_str(&result.content).unwrap();
2436 assert_eq!(body["queued"], json!(true));
2437 assert_eq!(body["woke"], json!(true));
2438 assert_eq!(body["continued_from_checkpoint"], json!(true));
2439 let note = body["note"].as_str().unwrap_or_default();
2440 assert!(note.contains("resumed from checkpoint"), "{note}");
2441 let resumed_id = body["agent_id"].as_str().unwrap_or_default();
2442 assert_ne!(
2443 resumed_id, agent_id,
2444 "resume re-dispatches under a new agent id"
2445 );
2446
2447 // A fresh record exists for the resumed session; the prior terminal
2448 // record stays immutable (receipts are never rewritten).
2449 let guard = manager.read().await;
2450 guard.get_result(resumed_id).expect("resumed agent exists");
2451 let prior = guard.get_result(&agent_id).expect("prior record");
2452 assert!(matches!(prior.status, SubAgentStatus::Interrupted(_)));
2453 }
2454
2455 #[tokio::test]
2456 async fn followup_rejects_oversized_message_before_queueing_and_keeps_count_cap() {
2457 let tmp = tempdir().unwrap();
2458 let manager = Arc::new(tokio::sync::RwLock::new(
2459 super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4),
2460 ));
2461 let make_paused = |name: &str| {
2462 let messages = vec![codewhale_models::Message {
2463 role: Role::User,
2464 content: vec![codewhale_models::ContentBlock::Text {
2465 text: "prior work".to_string(),
2466 cache_control: None,
2467 }],
2468 }];
2469 (name.to_string(), messages)
2470 };
2471 let (agent_id, _) = {
2472 let mut guard = manager.write().await;
2473 let (name, messages) = make_paused("bounded_count");
2474 guard.insert_test_interrupted_continuable_agent(&name, tmp.path(), messages)
2475 };
2476 let tool = AgentsFollowupTool::new(Arc::clone(&manager));
2477 let context = ToolContext::new(tmp.path());
2478
2479 let oversized = "x".repeat(super::super::MAX_PARENT_MESSAGE_BYTES + 1);
2480 let err = tool
2481 .execute(
2482 json!({ "agent_id": agent_id, "message": oversized }),
2483 &context,
2484 )
2485 .await
2486 .expect_err("oversized followup message must be rejected");
2487 assert!(matches!(err, ToolError::InvalidInput { .. }), "{err:?}");
2488 assert_eq!(
2489 manager
2490 .read()
2491 .await
2492 .queued_mail_depth(&agent_id)
2493 .unwrap_or(0),
2494 0
2495 );
2496
2497 for index in 0..super::super::MAX_QUEUED_PARENT_MESSAGES {
2498 tool.execute(
2499 json!({ "agent_id": agent_id, "message": format!("ping {index}") }),
2500 &context,
2501 )
2502 .await
2503 .expect("small followup within count cap should queue");
2504 }
2505 assert_eq!(
2506 manager.read().await.queued_mail_depth(&agent_id).unwrap(),
2507 super::super::MAX_QUEUED_PARENT_MESSAGES
2508 );
2509 let count_err = tool
2510 .execute(
2511 json!({ "agent_id": agent_id, "message": "one too many" }),
2512 &context,
2513 )
2514 .await
2515 .expect_err("65th queued message must hit count cap");
2516 assert!(
2517 matches!(count_err, ToolError::InvalidInput { .. }),
2518 "{count_err:?}"
2519 );
2520
2521 let (byte_agent_id, _) = {
2522 let mut guard = manager.write().await;
2523 let (name, messages) = make_paused("bounded_bytes");
2524 guard.insert_test_interrupted_continuable_agent(&name, tmp.path(), messages)
2525 };
2526 let max_msg = "y".repeat(super::super::MAX_PARENT_MESSAGE_BYTES);
2527 let full_chunks =
2528 super::super::MAX_QUEUED_PARENT_MAIL_BYTES / super::super::MAX_PARENT_MESSAGE_BYTES;
2529 for _ in 0..full_chunks {
2530 tool.execute(
2531 json!({ "agent_id": byte_agent_id, "message": max_msg }),
2532 &context,
2533 )
2534 .await
2535 .expect("chunk within aggregate byte budget should queue");
2536 }
2537 let byte_err = tool
2538 .execute(
2539 json!({ "agent_id": byte_agent_id, "message": "overflow" }),
2540 &context,
2541 )
2542 .await
2543 .expect_err("exceeding aggregate mail byte budget must fail");
2544 assert!(
2545 matches!(byte_err, ToolError::InvalidInput { .. }),
2546 "{byte_err:?}"
2547 );
2548 }
2549 }
2550
2550 lines RUST