1use crate::child_turn;
4use crate::session_runner::AgentSession;
5use anyhow::{Context as _, Result};
6use kiss_agent::{AgentMessage, AgentTool, DynTool, ToolResult, ToolUpdateSink};
7use kiss_ai::StopReason;
8use serde::{Deserialize, Serialize};
9use serde_json::{Value, json};
10use std::collections::HashMap;
11use std::sync::{Arc, Mutex, Weak};
12use std::time::Duration;
13use tokio::sync::{Semaphore, watch};
14use tokio_util::sync::CancellationToken;
15
16const MAX_ACTIVE_TURNS: usize = 4;
17const MAX_AGENT_RECORDS: usize = 16;
18const DEFAULT_WAIT_MS: u64 = 30_000;
19const MIN_WAIT_MS: u64 = 250;
20const MAX_WAIT_MS: u64 = 600_000;
21
22pub const SUBAGENT_SYSTEM_PROMPT: &str = "Subagent coordination:\n- Subagents share this working directory. Give each child one bounded task.\n- Fresh child context is the default. Copy parent turns only when the task needs them.\n- Use wait_agent when a child result is required. Do not use repeated list calls as polling.\n- Check child findings and edits before you give the final answer.\n- Start subagents only when the user or the current task justifies delegation.";
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
25#[serde(rename_all = "snake_case")]
26pub enum AgentStatus {
27 Queued,
28 Running,
29 Completed,
30 Failed,
31 Interrupted,
32}
33
34impl AgentStatus {
35 fn is_terminal(self) -> bool {
36 matches!(self, Self::Completed | Self::Failed | Self::Interrupted)
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
41#[serde(rename_all = "camelCase")]
42pub struct AgentInfo {
43 pub id: String,
44 pub task_name: String,
45 pub canonical_path: String,
46 pub status: AgentStatus,
47 #[serde(skip_serializing_if = "Option::is_none")]
48 pub result: Option<String>,
49 #[serde(skip_serializing_if = "Option::is_none")]
50 pub error: Option<String>,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum ForkTurns {
55 None,
56 All,
57 Recent(usize),
58}
59
60impl ForkTurns {
61 fn parse(value: Option<&Value>) -> Result<Self> {
62 match value {
63 None => Ok(Self::None),
64 Some(Value::String(value)) if value == "none" => Ok(Self::None),
65 Some(Value::String(value)) if value == "all" => Ok(Self::All),
66 Some(Value::Number(value)) => {
67 let count = value
68 .as_u64()
69 .filter(|count| *count > 0)
70 .and_then(|count| usize::try_from(count).ok())
71 .context("fork_turns must be 'none', 'all', or a positive integer")?;
72 Ok(Self::Recent(count))
73 }
74 _ => anyhow::bail!("fork_turns must be 'none', 'all', or a positive integer"),
75 }
76 }
77}
78
79struct AgentState {
80 turn: u64,
83 status: AgentStatus,
84 result: Option<String>,
85 error: Option<String>,
86}
87
88struct AgentRecord {
89 id: String,
90 task_name: String,
91 canonical_path: String,
92 session: Arc<AgentSession>,
93 state: Mutex<AgentState>,
94 turn_lock: tokio::sync::Mutex<()>,
97}
98
99impl AgentRecord {
100 fn snapshot(&self) -> AgentInfo {
101 let state = self.state.lock().unwrap();
102 AgentInfo {
103 id: self.id.clone(),
104 task_name: self.task_name.clone(),
105 canonical_path: self.canonical_path.clone(),
106 status: state.status,
107 result: state.result.clone(),
108 error: state.error.clone(),
109 }
110 }
111}
112
113pub struct SubagentRuntime {
114 parent: Weak<AgentSession>,
115 records: Mutex<Vec<Arc<AgentRecord>>>,
116 targets: Mutex<HashMap<String, Arc<AgentRecord>>>,
117 permits: Arc<Semaphore>,
118 activity: watch::Sender<u64>,
119 spawn_lock: Mutex<()>,
120}
121
122impl SubagentRuntime {
123 pub(crate) fn new(parent: Weak<AgentSession>) -> Arc<Self> {
124 Self::with_permits(parent, MAX_ACTIVE_TURNS)
125 }
126
127 fn with_permits(parent: Weak<AgentSession>, permits: usize) -> Arc<Self> {
128 let (activity, _) = watch::channel(0);
129 Arc::new(Self {
130 parent,
131 records: Mutex::new(Vec::new()),
132 targets: Mutex::new(HashMap::new()),
133 permits: Arc::new(Semaphore::new(permits)),
134 activity,
135 spawn_lock: Mutex::new(()),
136 })
137 }
138
139 pub(crate) fn control_tools(self: &Arc<Self>) -> Vec<DynTool> {
140 vec![
141 Arc::new(SpawnAgentTool(self.clone())),
142 Arc::new(SendMessageTool(self.clone())),
143 Arc::new(FollowupTaskTool(self.clone())),
144 Arc::new(WaitAgentTool(self.clone())),
145 Arc::new(ListAgentsTool(self.clone())),
146 Arc::new(InterruptAgentTool(self.clone())),
147 ]
148 }
149
150 fn signal_activity(&self) {
151 self.activity
152 .send_modify(|version| *version = version.wrapping_add(1));
153 }
154
155 fn resolve(&self, target: &str) -> Result<Arc<AgentRecord>> {
156 self.targets
157 .lock()
158 .unwrap()
159 .get(target)
160 .cloned()
161 .with_context(|| format!("unknown subagent target '{target}'"))
162 }
163
164 fn list(&self) -> Vec<AgentInfo> {
165 self.records
166 .lock()
167 .unwrap()
168 .iter()
169 .map(|record| record.snapshot())
170 .collect()
171 }
172
173 fn spawn(
174 self: &Arc<Self>,
175 task_name: String,
176 prompt: String,
177 fork_turns: ForkTurns,
178 model: Option<String>,
179 reasoning_effort: Option<String>,
180 ) -> Result<AgentInfo> {
181 let _spawn_guard = self.spawn_lock.lock().unwrap();
182 validate_task_name(&task_name)?;
183 if prompt.trim().is_empty() {
184 anyhow::bail!("prompt must not be empty");
185 }
186 {
187 let records = self.records.lock().unwrap();
188 if records.len() >= MAX_AGENT_RECORDS {
189 anyhow::bail!("the subagent limit of {MAX_AGENT_RECORDS} has been reached");
190 }
191 if records.iter().any(|record| record.task_name == task_name) {
192 anyhow::bail!(
193 "task name '{task_name}' already exists. Use followup_task for that child"
194 );
195 }
196 }
197
198 let canonical_path = format!("/root/{task_name}");
199 let parent = self
200 .parent
201 .upgrade()
202 .context("the parent session is no longer available")?;
203 let child = parent.create_subagent_session(
204 &task_name,
205 &canonical_path,
206 fork_turns,
207 model.as_deref(),
208 reasoning_effort.as_deref(),
209 )?;
210 let id = child.manager.lock().unwrap().session_id().to_string();
211 let record = Arc::new(AgentRecord {
212 id: id.clone(),
213 task_name: task_name.clone(),
214 canonical_path: canonical_path.clone(),
215 session: child,
216 state: Mutex::new(AgentState {
217 turn: 0,
218 status: AgentStatus::Queued,
219 result: None,
220 error: None,
221 }),
222 turn_lock: tokio::sync::Mutex::new(()),
223 });
224 self.records.lock().unwrap().push(record.clone());
225 let mut targets = self.targets.lock().unwrap();
226 for target in [&id, &task_name, &canonical_path] {
227 targets.insert(target.clone(), record.clone());
228 }
229 drop(targets);
230
231 let info = record.snapshot();
232 self.signal_activity();
233 self.start_turn(record, 0, prompt);
234 Ok(info)
235 }
236
237 fn start_turn(self: &Arc<Self>, record: Arc<AgentRecord>, turn: u64, prompt: String) {
238 let runtime = self.clone();
239 tokio::spawn(async move {
240 let _turn_lock = record.turn_lock.lock().await;
241 let permit = match runtime.permits.clone().acquire_owned().await {
242 Ok(permit) => permit,
243 Err(_) => return,
244 };
245 {
246 let mut state = record.state.lock().unwrap();
247 if state.turn != turn || state.status != AgentStatus::Queued {
248 return;
249 }
250 state.status = AgentStatus::Running;
251 }
252 runtime.signal_activity();
253
254 let outcome =
255 child_turn::run_child_turn(&runtime.parent, &record.session, prompt, None, None)
256 .await;
257 drop(permit);
258
259 let mut state = record.state.lock().unwrap();
260 if state.status == AgentStatus::Running {
261 state.status = outcome.status;
262 state.result = outcome.result;
263 state.error = outcome.error;
264 }
265 drop(state);
266 runtime.signal_activity();
267 });
268 }
269
270 fn send_message(&self, target: &str, message: String) -> Result<AgentInfo> {
271 if message.trim().is_empty() {
272 anyhow::bail!("message must not be empty");
273 }
274 let record = self.resolve(target)?;
275 let status = record.state.lock().unwrap().status;
276 if !matches!(status, AgentStatus::Queued | AgentStatus::Running) {
277 anyhow::bail!(
278 "subagent '{}' is {}. Use followup_task to start another turn",
279 record.task_name,
280 status_name(status)
281 );
282 }
283 record.session.queue_steering(AgentMessage::user(message));
284 self.signal_activity();
285 Ok(record.snapshot())
286 }
287
288 fn followup(self: &Arc<Self>, target: &str, prompt: String) -> Result<AgentInfo> {
289 if prompt.trim().is_empty() {
290 anyhow::bail!("prompt must not be empty");
291 }
292 let record = self.resolve(target)?;
293 let turn = {
294 let mut state = record.state.lock().unwrap();
295 if !state.status.is_terminal() {
296 anyhow::bail!("subagent '{}' is still busy", record.task_name);
297 }
298 state.turn += 1;
299 state.status = AgentStatus::Queued;
300 state.result = None;
301 state.error = None;
302 state.turn
303 };
304 let _ = record.session.reclaim_queued();
305 let info = record.snapshot();
306 self.signal_activity();
307 self.start_turn(record, turn, prompt);
308 Ok(info)
309 }
310
311 async fn wait(
312 &self,
313 targets: &[String],
314 timeout_ms: u64,
315 cancel: CancellationToken,
316 ) -> Result<WaitOutcome> {
317 if targets.is_empty() {
318 anyhow::bail!("targets must contain at least one subagent");
319 }
320 let records = targets
321 .iter()
322 .map(|target| self.resolve(target))
323 .collect::<Result<Vec<_>>>()?;
324 let timeout_ms = timeout_ms.clamp(MIN_WAIT_MS, MAX_WAIT_MS);
325 let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms);
326 let mut activity = self.activity.subscribe();
327
328 loop {
329 let agents = records
330 .iter()
331 .map(|record| record.snapshot())
332 .collect::<Vec<_>>();
333 if agents.iter().any(|agent| agent.status.is_terminal()) {
334 return Ok(WaitOutcome {
335 timed_out: false,
336 agents,
337 });
338 }
339 let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
340 if remaining.is_zero() {
341 return Ok(WaitOutcome {
342 timed_out: true,
343 agents,
344 });
345 }
346 tokio::select! {
347 _ = cancel.cancelled() => anyhow::bail!("wait cancelled"),
348 result = tokio::time::timeout(remaining, activity.changed()) => {
349 if result.is_err() {
350 return Ok(WaitOutcome { timed_out: true, agents });
351 }
352 }
353 }
354 }
355 }
356
357 fn interrupt(&self, target: &str) -> Result<AgentInfo> {
358 let record = self.resolve(target)?;
359 interrupt_record(&record);
360 self.signal_activity();
361 Ok(record.snapshot())
362 }
363
364 pub(crate) fn interrupt_all(&self) {
365 let records = self.records.lock().unwrap().clone();
366 for record in records {
367 interrupt_record(&record);
368 }
369 self.signal_activity();
370 }
371
372 pub(crate) fn reset(&self) {
373 self.interrupt_all();
374 self.records.lock().unwrap().clear();
375 self.targets.lock().unwrap().clear();
376 self.signal_activity();
377 }
378}
379
380fn interrupt_record(record: &AgentRecord) {
381 let mut state = record.state.lock().unwrap();
382 if matches!(state.status, AgentStatus::Queued | AgentStatus::Running) {
383 state.status = AgentStatus::Interrupted;
384 state.result = None;
385 state.error = Some("interrupted".into());
386 record.session.abort();
387 }
388}
389
390pub(crate) fn turn_outcome(
391 session: &AgentSession,
392) -> (AgentStatus, Option<String>, Option<String>) {
393 let manager = session.manager.lock().unwrap();
394 let assistant = manager
395 .build_session_context()
396 .messages
397 .into_iter()
398 .rev()
399 .find_map(|message| match message {
400 AgentMessage::Assistant(assistant) => Some(assistant),
401 _ => None,
402 });
403 let Some(assistant) = assistant else {
404 return (
405 AgentStatus::Failed,
406 None,
407 Some("the child returned no assistant message".into()),
408 );
409 };
410 match assistant.stop_reason {
411 StopReason::Error => (
412 AgentStatus::Failed,
413 None,
414 Some(
415 assistant
416 .error_message
417 .unwrap_or_else(|| "the child request failed".into()),
418 ),
419 ),
420 StopReason::Aborted => (AgentStatus::Interrupted, None, Some("interrupted".into())),
421 _ => {
422 let text = assistant.text();
423 if text.trim().is_empty() {
424 (
425 AgentStatus::Failed,
426 None,
427 Some("the child returned an empty result".into()),
428 )
429 } else {
430 (AgentStatus::Completed, Some(text), None)
431 }
432 }
433 }
434}
435
436fn validate_task_name(name: &str) -> Result<()> {
437 if name.is_empty()
438 || name.len() > 64
439 || !name
440 .bytes()
441 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
442 {
443 anyhow::bail!(
444 "task_name must use 1 to 64 lower-case ASCII letters, digits, or underscores"
445 );
446 }
447 Ok(())
448}
449
450fn status_name(status: AgentStatus) -> &'static str {
451 match status {
452 AgentStatus::Queued => "queued",
453 AgentStatus::Running => "running",
454 AgentStatus::Completed => "completed",
455 AgentStatus::Failed => "failed",
456 AgentStatus::Interrupted => "interrupted",
457 }
458}
459
460#[derive(Serialize)]
461#[serde(rename_all = "camelCase")]
462struct WaitOutcome {
463 timed_out: bool,
464 agents: Vec<AgentInfo>,
465}
466
467fn json_result(value: &impl Serialize) -> Result<ToolResult> {
468 Ok(ToolResult::text(serde_json::to_string_pretty(value)?))
469}
470
471#[derive(Deserialize)]
472struct SpawnArgs {
473 task_name: String,
474 prompt: String,
475 #[serde(default)]
476 fork_turns: Option<Value>,
477 #[serde(default)]
478 model: Option<String>,
479 #[serde(default)]
480 reasoning_effort: Option<String>,
481}
482
483struct SpawnAgentTool(Arc<SubagentRuntime>);
484
485#[async_trait::async_trait]
486impl AgentTool for SpawnAgentTool {
487 fn name(&self) -> &str {
488 "spawn_agent"
489 }
490
491 fn description(&self) -> String {
492 "Start a named child coding agent in the background. Fresh context is the default.".into()
493 }
494
495 fn parameters(&self) -> Value {
496 json!({
497 "type": "object",
498 "properties": {
499 "task_name": {"type": "string", "pattern": "^[a-z0-9_]{1,64}$"},
500 "prompt": {"type": "string", "minLength": 1},
501 "fork_turns": {"oneOf": [
502 {"type": "string", "enum": ["none", "all"]},
503 {"type": "integer", "minimum": 1}
504 ]},
505 "model": {"type": "string"},
506 "reasoning_effort": {"type": "string"}
507 },
508 "required": ["task_name", "prompt"],
509 "additionalProperties": false
510 })
511 }
512
513 async fn execute(
514 &self,
515 _tool_call_id: &str,
516 args: Value,
517 _cancel: CancellationToken,
518 _on_update: Option<ToolUpdateSink>,
519 ) -> Result<ToolResult> {
520 let args: SpawnArgs = serde_json::from_value(args)?;
521 let fork_turns = ForkTurns::parse(args.fork_turns.as_ref())?;
522 json_result(&self.0.spawn(
523 args.task_name,
524 args.prompt,
525 fork_turns,
526 args.model,
527 args.reasoning_effort,
528 )?)
529 }
530}
531
532#[derive(Deserialize)]
533struct MessageArgs {
534 target: String,
535 message: String,
536}
537
538struct SendMessageTool(Arc<SubagentRuntime>);
539
540#[async_trait::async_trait]
541impl AgentTool for SendMessageTool {
542 fn name(&self) -> &str {
543 "send_message"
544 }
545
546 fn description(&self) -> String {
547 "Send steering guidance to a queued or running child agent.".into()
548 }
549
550 fn parameters(&self) -> Value {
551 json!({
552 "type": "object",
553 "properties": {
554 "target": {"type": "string"},
555 "message": {"type": "string", "minLength": 1}
556 },
557 "required": ["target", "message"],
558 "additionalProperties": false
559 })
560 }
561
562 async fn execute(
563 &self,
564 _tool_call_id: &str,
565 args: Value,
566 _cancel: CancellationToken,
567 _on_update: Option<ToolUpdateSink>,
568 ) -> Result<ToolResult> {
569 let args: MessageArgs = serde_json::from_value(args)?;
570 json_result(&self.0.send_message(&args.target, args.message)?)
571 }
572}
573
574#[derive(Deserialize)]
575struct FollowupArgs {
576 target: String,
577 prompt: String,
578}
579
580struct FollowupTaskTool(Arc<SubagentRuntime>);
581
582#[async_trait::async_trait]
583impl AgentTool for FollowupTaskTool {
584 fn name(&self) -> &str {
585 "followup_task"
586 }
587
588 fn description(&self) -> String {
589 "Start a new turn in an idle child agent and keep its existing context.".into()
590 }
591
592 fn parameters(&self) -> Value {
593 json!({
594 "type": "object",
595 "properties": {
596 "target": {"type": "string"},
597 "prompt": {"type": "string", "minLength": 1}
598 },
599 "required": ["target", "prompt"],
600 "additionalProperties": false
601 })
602 }
603
604 async fn execute(
605 &self,
606 _tool_call_id: &str,
607 args: Value,
608 _cancel: CancellationToken,
609 _on_update: Option<ToolUpdateSink>,
610 ) -> Result<ToolResult> {
611 let args: FollowupArgs = serde_json::from_value(args)?;
612 json_result(&self.0.followup(&args.target, args.prompt)?)
613 }
614}
615
616#[derive(Deserialize)]
617struct WaitArgs {
618 targets: Vec<String>,
619 #[serde(default = "default_wait_ms")]
620 timeout_ms: u64,
621}
622
623fn default_wait_ms() -> u64 {
624 DEFAULT_WAIT_MS
625}
626
627struct WaitAgentTool(Arc<SubagentRuntime>);
628
629#[async_trait::async_trait]
630impl AgentTool for WaitAgentTool {
631 fn name(&self) -> &str {
632 "wait_agent"
633 }
634
635 fn description(&self) -> String {
636 "Wait for one requested child agent to finish or for a bounded timeout.".into()
637 }
638
639 fn parameters(&self) -> Value {
640 json!({
641 "type": "object",
642 "properties": {
643 "targets": {"type": "array", "items": {"type": "string"}, "minItems": 1, "uniqueItems": true},
644 "timeout_ms": {"type": "integer", "minimum": MIN_WAIT_MS, "maximum": MAX_WAIT_MS}
645 },
646 "required": ["targets"],
647 "additionalProperties": false
648 })
649 }
650
651 async fn execute(
652 &self,
653 _tool_call_id: &str,
654 args: Value,
655 cancel: CancellationToken,
656 _on_update: Option<ToolUpdateSink>,
657 ) -> Result<ToolResult> {
658 let args: WaitArgs = serde_json::from_value(args)?;
659 json_result(&self.0.wait(&args.targets, args.timeout_ms, cancel).await?)
660 }
661}
662
663struct ListAgentsTool(Arc<SubagentRuntime>);
664
665#[async_trait::async_trait]
666impl AgentTool for ListAgentsTool {
667 fn name(&self) -> &str {
668 "list_agents"
669 }
670
671 fn description(&self) -> String {
672 "List child agents in creation order with their current status.".into()
673 }
674
675 fn parameters(&self) -> Value {
676 json!({"type": "object", "properties": {}, "additionalProperties": false})
677 }
678
679 async fn execute(
680 &self,
681 _tool_call_id: &str,
682 _args: Value,
683 _cancel: CancellationToken,
684 _on_update: Option<ToolUpdateSink>,
685 ) -> Result<ToolResult> {
686 json_result(&self.0.list())
687 }
688}
689
690#[derive(Deserialize)]
691struct TargetArgs {
692 target: String,
693}
694
695struct InterruptAgentTool(Arc<SubagentRuntime>);
696
697#[async_trait::async_trait]
698impl AgentTool for InterruptAgentTool {
699 fn name(&self) -> &str {
700 "interrupt_agent"
701 }
702
703 fn description(&self) -> String {
704 "Interrupt a queued or running child agent.".into()
705 }
706
707 fn parameters(&self) -> Value {
708 json!({
709 "type": "object",
710 "properties": {"target": {"type": "string"}},
711 "required": ["target"],
712 "additionalProperties": false
713 })
714 }
715
716 async fn execute(
717 &self,
718 _tool_call_id: &str,
719 args: Value,
720 _cancel: CancellationToken,
721 _on_update: Option<ToolUpdateSink>,
722 ) -> Result<ToolResult> {
723 let args: TargetArgs = serde_json::from_value(args)?;
724 json_result(&self.0.interrupt(&args.target)?)
725 }
726}
727
728pub(crate) fn fork_messages(messages: &[AgentMessage], fork: ForkTurns) -> Vec<AgentMessage> {
729 let safe = messages
730 .iter()
731 .filter(|message| match message {
732 AgentMessage::User(_)
733 | AgentMessage::BranchSummary(_)
734 | AgentMessage::CompactionSummary(_) => true,
735 AgentMessage::Assistant(assistant) => assistant.tool_calls().next().is_none(),
736 AgentMessage::ToolResult(_)
737 | AgentMessage::BashExecution(_)
738 | AgentMessage::Custom(_) => false,
739 })
740 .cloned()
741 .collect::<Vec<_>>();
742
743 match fork {
744 ForkTurns::None => Vec::new(),
745 ForkTurns::All => safe,
746 ForkTurns::Recent(count) => {
747 let start = safe
748 .iter()
749 .enumerate()
750 .rev()
751 .filter(|(_, message)| matches!(message, AgentMessage::User(_)))
752 .nth(count.saturating_sub(1))
753 .map(|(index, _)| index)
754 .unwrap_or(0);
755 safe[start..].to_vec()
756 }
757 }
758}
759
760#[cfg(test)]
761mod tests {
762 use super::*;
763 use kiss_ai::{AssistantMessage, ContentBlock, ToolCall};
764
765 fn assistant(text: &str) -> AgentMessage {
766 let mut message = AssistantMessage::empty("fake", "fake", "fake");
767 message.content.push(ContentBlock::text(text));
768 AgentMessage::Assistant(message)
769 }
770
771 fn parent_session() -> Arc<AgentSession> {
772 let registry = kiss_ai::Registry::from_builtin();
773 let model = registry.all().first().expect("built-in model").clone();
774 AgentSession::new_with_subagents_allowed(
775 crate::SessionManager::in_memory(std::path::Path::new("/test")),
776 Vec::new(),
777 registry,
778 crate::Settings::default(),
779 "test".into(),
780 model,
781 kiss_ai::ThinkingLevel::Off,
782 None,
783 Arc::new(|_| {}),
784 false,
785 )
786 }
787
788 #[test]
789 fn task_names_are_bounded_and_portable() {
790 assert!(validate_task_name("review_2").is_ok());
791 assert!(validate_task_name("").is_err());
792 assert!(validate_task_name("Review").is_err());
793 assert!(validate_task_name("has-dash").is_err());
794 assert!(validate_task_name(&"a".repeat(65)).is_err());
795 }
796
797 #[test]
798 fn fork_turns_accepts_only_documented_values() {
799 assert_eq!(ForkTurns::parse(None).unwrap(), ForkTurns::None);
800 assert_eq!(
801 ForkTurns::parse(Some(&json!("all"))).unwrap(),
802 ForkTurns::All
803 );
804 assert_eq!(
805 ForkTurns::parse(Some(&json!(2))).unwrap(),
806 ForkTurns::Recent(2)
807 );
808 assert!(ForkTurns::parse(Some(&json!(0))).is_err());
809 assert!(ForkTurns::parse(Some(&json!("recent"))).is_err());
810 }
811
812 #[test]
813 fn context_fork_removes_tool_pairs_and_keeps_recent_turns() {
814 let mut tool_message = AssistantMessage::empty("fake", "fake", "fake");
815 tool_message.content.push(ContentBlock::ToolCall(ToolCall {
816 id: "call".into(),
817 name: "read".into(),
818 arguments: json!({}),
819 thought_signature: None,
820 arguments_error: None,
821 }));
822 let history = vec![
823 AgentMessage::user("first"),
824 assistant("one"),
825 AgentMessage::Assistant(tool_message),
826 AgentMessage::user("second"),
827 assistant("two"),
828 ];
829
830 assert!(fork_messages(&history, ForkTurns::None).is_empty());
831 let all = fork_messages(&history, ForkTurns::All);
832 assert_eq!(all.len(), 4);
833 assert!(
834 all.iter()
835 .all(|message| !matches!(message, AgentMessage::ToolResult(_)))
836 );
837 let recent = fork_messages(&history, ForkTurns::Recent(1));
838 assert_eq!(recent, history[3..]);
839 }
840
841 #[test]
842 fn control_tool_catalog_uses_codex_names() {
843 let parent = Weak::new();
844 let runtime = SubagentRuntime::new(parent);
845 let names = runtime
846 .control_tools()
847 .into_iter()
848 .map(|tool| tool.name().to_string())
849 .collect::<Vec<_>>();
850 assert_eq!(
851 names,
852 [
853 "spawn_agent",
854 "send_message",
855 "followup_task",
856 "wait_agent",
857 "list_agents",
858 "interrupt_agent"
859 ]
860 );
861 for tool in runtime.control_tools() {
862 let schema = tool.parameters();
863 assert_eq!(schema["type"], "object", "{} schema", tool.name());
864 assert_eq!(
865 schema["additionalProperties"],
866 false,
867 "{} schema",
868 tool.name()
869 );
870 }
871 let spawn = runtime.control_tools().remove(0).parameters();
872 assert_eq!(spawn["required"], json!(["task_name", "prompt"]));
873 assert_eq!(
874 spawn["properties"]["fork_turns"]["oneOf"]
875 .as_array()
876 .unwrap()
877 .len(),
878 2
879 );
880 }
881
882 #[tokio::test]
883 async fn a_followup_after_an_interrupt_waits_for_the_old_turn_to_stop() {
884 let parent = parent_session();
885 let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
886 let observed_calls = calls.clone();
887 parent.set_stream_fn(Some(Arc::new(move |_, _, options| {
889 let step = observed_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
890 let mut message = kiss_ai::AssistantMessage::empty("test", "test", "test");
891 let (sink, stream) = kiss_ai::EventStream::channel();
892 if step == 0 {
893 let cancel = options.cancel.clone();
894 tokio::spawn(async move {
895 cancel.cancelled().await;
896 tokio::time::sleep(Duration::from_millis(50)).await;
897 message.stop_reason = StopReason::Aborted;
898 sink.error(message);
899 });
900 } else {
901 message.content = vec![kiss_ai::ContentBlock::Text {
902 text: "second answer".into(),
903 text_signature: None,
904 }];
905 message.stop_reason = StopReason::Stop;
906 sink.done(message);
907 }
908 stream
909 })));
910 let runtime = SubagentRuntime::with_permits(Arc::downgrade(&parent), 2);
911 runtime
912 .spawn(
913 "review_tests".into(),
914 "first".into(),
915 ForkTurns::None,
916 None,
917 None,
918 )
919 .unwrap();
920 tokio::time::timeout(Duration::from_secs(5), async {
921 while calls.load(std::sync::atomic::Ordering::SeqCst) == 0 {
922 tokio::task::yield_now().await;
923 }
924 })
925 .await
926 .expect("the first turn reaches the model");
927
928 runtime.interrupt("review_tests").unwrap();
929 runtime
930 .followup("review_tests", "second".into())
931 .expect("an interrupted agent accepts a follow-up");
932
933 let outcome = runtime
934 .wait(&["review_tests".into()], 5_000, CancellationToken::new())
935 .await
936 .unwrap();
937 assert!(!outcome.timed_out);
938 assert_eq!(outcome.agents[0].status, AgentStatus::Completed);
939 assert_eq!(outcome.agents[0].result.as_deref(), Some("second answer"));
940 assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2);
941 }
942
943 #[tokio::test]
944 async fn queued_agent_can_be_listed_interrupted_and_waited_for() {
945 let parent = parent_session();
946 let runtime = SubagentRuntime::with_permits(Arc::downgrade(&parent), 0);
947 let spawned = runtime
948 .spawn(
949 "review_tests".into(),
950 "Review the tests".into(),
951 ForkTurns::None,
952 None,
953 None,
954 )
955 .unwrap();
956 assert_eq!(spawned.status, AgentStatus::Queued);
957 assert_eq!(runtime.list(), vec![spawned.clone()]);
958 assert!(
959 runtime
960 .spawn(
961 "review_tests".into(),
962 "Duplicate".into(),
963 ForkTurns::None,
964 None,
965 None,
966 )
967 .is_err()
968 );
969
970 let waiting_runtime = runtime.clone();
971 let target = spawned.id.clone();
972 let waiting = tokio::spawn(async move {
973 waiting_runtime
974 .wait(&[target], 5_000, CancellationToken::new())
975 .await
976 .unwrap()
977 });
978 tokio::task::yield_now().await;
979 let interrupted = runtime.interrupt("review_tests").unwrap();
980 assert_eq!(interrupted.status, AgentStatus::Interrupted);
981 runtime.permits.add_permits(1);
982
983 let outcome = tokio::time::timeout(Duration::from_secs(1), waiting)
984 .await
985 .expect("mailbox wait")
986 .unwrap();
987 assert!(!outcome.timed_out);
988 assert_eq!(outcome.agents[0].status, AgentStatus::Interrupted);
989 }
990}