Skip to main content

kiss_coding/
subagents.rs

1//! Opt-in, in-process subagent sessions and Codex-style control tools.
2
3use 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    /// Identifies the current turn. A turn writes its outcome only while it is
81    /// still the current one.
82    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    /// A turn holds this for its whole life. An interrupted turn can still be
95    /// stopping when the next one is requested, and they share one session.
96    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        // Messages sent to the previous turn after it ended stay queued, so
305        // the new turn delivers them instead of dropping them.
306        let info = record.snapshot();
307        self.signal_activity();
308        self.start_turn(record, turn, prompt);
309        Ok(info)
310    }
311
312    async fn wait(
313        &self,
314        targets: &[String],
315        timeout_ms: u64,
316        cancel: CancellationToken,
317    ) -> Result<WaitOutcome> {
318        if targets.is_empty() {
319            anyhow::bail!("targets must contain at least one subagent");
320        }
321        let records = targets
322            .iter()
323            .map(|target| self.resolve(target))
324            .collect::<Result<Vec<_>>>()?;
325        let timeout_ms = timeout_ms.clamp(MIN_WAIT_MS, MAX_WAIT_MS);
326        let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms);
327        let mut activity = self.activity.subscribe();
328
329        loop {
330            let agents = records
331                .iter()
332                .map(|record| record.snapshot())
333                .collect::<Vec<_>>();
334            if agents.iter().any(|agent| agent.status.is_terminal()) {
335                return Ok(WaitOutcome {
336                    timed_out: false,
337                    agents,
338                });
339            }
340            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
341            if remaining.is_zero() {
342                return Ok(WaitOutcome {
343                    timed_out: true,
344                    agents,
345                });
346            }
347            tokio::select! {
348                _ = cancel.cancelled() => anyhow::bail!("wait cancelled"),
349                result = tokio::time::timeout(remaining, activity.changed()) => {
350                    if result.is_err() {
351                        return Ok(WaitOutcome { timed_out: true, agents });
352                    }
353                }
354            }
355        }
356    }
357
358    fn interrupt(&self, target: &str) -> Result<AgentInfo> {
359        let record = self.resolve(target)?;
360        interrupt_record(&record);
361        self.signal_activity();
362        Ok(record.snapshot())
363    }
364
365    pub(crate) fn interrupt_all(&self) {
366        let records = self.records.lock().unwrap().clone();
367        for record in records {
368            interrupt_record(&record);
369        }
370        self.signal_activity();
371    }
372
373    pub(crate) fn reset(&self) {
374        self.interrupt_all();
375        self.records.lock().unwrap().clear();
376        self.targets.lock().unwrap().clear();
377        self.signal_activity();
378    }
379}
380
381fn interrupt_record(record: &AgentRecord) {
382    let mut state = record.state.lock().unwrap();
383    if matches!(state.status, AgentStatus::Queued | AgentStatus::Running) {
384        state.status = AgentStatus::Interrupted;
385        state.result = None;
386        state.error = Some("interrupted".into());
387        record.session.abort();
388    }
389}
390
391pub(crate) fn turn_outcome(
392    session: &AgentSession,
393) -> (AgentStatus, Option<String>, Option<String>) {
394    let manager = session.manager.lock().unwrap();
395    let assistant = manager
396        .build_session_context()
397        .messages
398        .into_iter()
399        .rev()
400        .find_map(|message| match message {
401            AgentMessage::Assistant(assistant) => Some(assistant),
402            _ => None,
403        });
404    let Some(assistant) = assistant else {
405        return (
406            AgentStatus::Failed,
407            None,
408            Some("the child returned no assistant message".into()),
409        );
410    };
411    match assistant.stop_reason {
412        StopReason::Error => (
413            AgentStatus::Failed,
414            None,
415            Some(
416                assistant
417                    .error_message
418                    .unwrap_or_else(|| "the child request failed".into()),
419            ),
420        ),
421        StopReason::Aborted => (AgentStatus::Interrupted, None, Some("interrupted".into())),
422        _ => {
423            let text = assistant.text();
424            if text.trim().is_empty() {
425                (
426                    AgentStatus::Failed,
427                    None,
428                    Some("the child returned an empty result".into()),
429                )
430            } else {
431                (AgentStatus::Completed, Some(text), None)
432            }
433        }
434    }
435}
436
437fn validate_task_name(name: &str) -> Result<()> {
438    if name.is_empty()
439        || name.len() > 64
440        || !name
441            .bytes()
442            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
443    {
444        anyhow::bail!(
445            "task_name must use 1 to 64 lower-case ASCII letters, digits, or underscores"
446        );
447    }
448    Ok(())
449}
450
451fn status_name(status: AgentStatus) -> &'static str {
452    match status {
453        AgentStatus::Queued => "queued",
454        AgentStatus::Running => "running",
455        AgentStatus::Completed => "completed",
456        AgentStatus::Failed => "failed",
457        AgentStatus::Interrupted => "interrupted",
458    }
459}
460
461#[derive(Serialize)]
462#[serde(rename_all = "camelCase")]
463struct WaitOutcome {
464    timed_out: bool,
465    agents: Vec<AgentInfo>,
466}
467
468fn json_result(value: &impl Serialize) -> Result<ToolResult> {
469    Ok(ToolResult::text(serde_json::to_string_pretty(value)?))
470}
471
472#[derive(Deserialize)]
473struct SpawnArgs {
474    task_name: String,
475    prompt: String,
476    #[serde(default)]
477    fork_turns: Option<Value>,
478    #[serde(default)]
479    model: Option<String>,
480    #[serde(default)]
481    reasoning_effort: Option<String>,
482}
483
484struct SpawnAgentTool(Arc<SubagentRuntime>);
485
486#[async_trait::async_trait]
487impl AgentTool for SpawnAgentTool {
488    fn name(&self) -> &str {
489        "spawn_agent"
490    }
491
492    fn description(&self) -> String {
493        "Start a named child coding agent in the background. Fresh context is the default.".into()
494    }
495
496    fn parameters(&self) -> Value {
497        json!({
498            "type": "object",
499            "properties": {
500                "task_name": {"type": "string", "pattern": "^[a-z0-9_]{1,64}$"},
501                "prompt": {"type": "string", "minLength": 1},
502                "fork_turns": {"oneOf": [
503                    {"type": "string", "enum": ["none", "all"]},
504                    {"type": "integer", "minimum": 1}
505                ]},
506                "model": {"type": "string"},
507                "reasoning_effort": {"type": "string"}
508            },
509            "required": ["task_name", "prompt"],
510            "additionalProperties": false
511        })
512    }
513
514    async fn execute(
515        &self,
516        _tool_call_id: &str,
517        args: Value,
518        _cancel: CancellationToken,
519        _on_update: Option<ToolUpdateSink>,
520    ) -> Result<ToolResult> {
521        let args: SpawnArgs = serde_json::from_value(args)?;
522        let fork_turns = ForkTurns::parse(args.fork_turns.as_ref())?;
523        json_result(&self.0.spawn(
524            args.task_name,
525            args.prompt,
526            fork_turns,
527            args.model,
528            args.reasoning_effort,
529        )?)
530    }
531}
532
533#[derive(Deserialize)]
534struct MessageArgs {
535    target: String,
536    message: String,
537}
538
539struct SendMessageTool(Arc<SubagentRuntime>);
540
541#[async_trait::async_trait]
542impl AgentTool for SendMessageTool {
543    fn name(&self) -> &str {
544        "send_message"
545    }
546
547    fn description(&self) -> String {
548        "Send steering guidance to a queued or running child agent.".into()
549    }
550
551    fn parameters(&self) -> Value {
552        json!({
553            "type": "object",
554            "properties": {
555                "target": {"type": "string"},
556                "message": {"type": "string", "minLength": 1}
557            },
558            "required": ["target", "message"],
559            "additionalProperties": false
560        })
561    }
562
563    async fn execute(
564        &self,
565        _tool_call_id: &str,
566        args: Value,
567        _cancel: CancellationToken,
568        _on_update: Option<ToolUpdateSink>,
569    ) -> Result<ToolResult> {
570        let args: MessageArgs = serde_json::from_value(args)?;
571        json_result(&self.0.send_message(&args.target, args.message)?)
572    }
573}
574
575#[derive(Deserialize)]
576struct FollowupArgs {
577    target: String,
578    prompt: String,
579}
580
581struct FollowupTaskTool(Arc<SubagentRuntime>);
582
583#[async_trait::async_trait]
584impl AgentTool for FollowupTaskTool {
585    fn name(&self) -> &str {
586        "followup_task"
587    }
588
589    fn description(&self) -> String {
590        "Start a new turn in an idle child agent and keep its existing context.".into()
591    }
592
593    fn parameters(&self) -> Value {
594        json!({
595            "type": "object",
596            "properties": {
597                "target": {"type": "string"},
598                "prompt": {"type": "string", "minLength": 1}
599            },
600            "required": ["target", "prompt"],
601            "additionalProperties": false
602        })
603    }
604
605    async fn execute(
606        &self,
607        _tool_call_id: &str,
608        args: Value,
609        _cancel: CancellationToken,
610        _on_update: Option<ToolUpdateSink>,
611    ) -> Result<ToolResult> {
612        let args: FollowupArgs = serde_json::from_value(args)?;
613        json_result(&self.0.followup(&args.target, args.prompt)?)
614    }
615}
616
617#[derive(Deserialize)]
618struct WaitArgs {
619    targets: Vec<String>,
620    #[serde(default = "default_wait_ms")]
621    timeout_ms: u64,
622}
623
624fn default_wait_ms() -> u64 {
625    DEFAULT_WAIT_MS
626}
627
628struct WaitAgentTool(Arc<SubagentRuntime>);
629
630#[async_trait::async_trait]
631impl AgentTool for WaitAgentTool {
632    fn name(&self) -> &str {
633        "wait_agent"
634    }
635
636    fn description(&self) -> String {
637        "Wait for one requested child agent to finish or for a bounded timeout.".into()
638    }
639
640    fn parameters(&self) -> Value {
641        json!({
642            "type": "object",
643            "properties": {
644                "targets": {"type": "array", "items": {"type": "string"}, "minItems": 1, "uniqueItems": true},
645                "timeout_ms": {"type": "integer", "minimum": MIN_WAIT_MS, "maximum": MAX_WAIT_MS}
646            },
647            "required": ["targets"],
648            "additionalProperties": false
649        })
650    }
651
652    async fn execute(
653        &self,
654        _tool_call_id: &str,
655        args: Value,
656        cancel: CancellationToken,
657        _on_update: Option<ToolUpdateSink>,
658    ) -> Result<ToolResult> {
659        let args: WaitArgs = serde_json::from_value(args)?;
660        json_result(&self.0.wait(&args.targets, args.timeout_ms, cancel).await?)
661    }
662}
663
664struct ListAgentsTool(Arc<SubagentRuntime>);
665
666#[async_trait::async_trait]
667impl AgentTool for ListAgentsTool {
668    fn name(&self) -> &str {
669        "list_agents"
670    }
671
672    fn description(&self) -> String {
673        "List child agents in creation order with their current status.".into()
674    }
675
676    fn parameters(&self) -> Value {
677        json!({"type": "object", "properties": {}, "additionalProperties": false})
678    }
679
680    async fn execute(
681        &self,
682        _tool_call_id: &str,
683        _args: Value,
684        _cancel: CancellationToken,
685        _on_update: Option<ToolUpdateSink>,
686    ) -> Result<ToolResult> {
687        json_result(&self.0.list())
688    }
689}
690
691#[derive(Deserialize)]
692struct TargetArgs {
693    target: String,
694}
695
696struct InterruptAgentTool(Arc<SubagentRuntime>);
697
698#[async_trait::async_trait]
699impl AgentTool for InterruptAgentTool {
700    fn name(&self) -> &str {
701        "interrupt_agent"
702    }
703
704    fn description(&self) -> String {
705        "Interrupt a queued or running child agent.".into()
706    }
707
708    fn parameters(&self) -> Value {
709        json!({
710            "type": "object",
711            "properties": {"target": {"type": "string"}},
712            "required": ["target"],
713            "additionalProperties": false
714        })
715    }
716
717    async fn execute(
718        &self,
719        _tool_call_id: &str,
720        args: Value,
721        _cancel: CancellationToken,
722        _on_update: Option<ToolUpdateSink>,
723    ) -> Result<ToolResult> {
724        let args: TargetArgs = serde_json::from_value(args)?;
725        json_result(&self.0.interrupt(&args.target)?)
726    }
727}
728
729pub(crate) fn fork_messages(messages: &[AgentMessage], fork: ForkTurns) -> Vec<AgentMessage> {
730    let safe = messages
731        .iter()
732        .filter(|message| match message {
733            AgentMessage::User(_)
734            | AgentMessage::BranchSummary(_)
735            | AgentMessage::CompactionSummary(_) => true,
736            AgentMessage::Assistant(assistant) => assistant.tool_calls().next().is_none(),
737            AgentMessage::ToolResult(_)
738            | AgentMessage::BashExecution(_)
739            | AgentMessage::Custom(_) => false,
740        })
741        .cloned()
742        .collect::<Vec<_>>();
743
744    match fork {
745        ForkTurns::None => Vec::new(),
746        ForkTurns::All => safe,
747        ForkTurns::Recent(count) => {
748            let start = safe
749                .iter()
750                .enumerate()
751                .rev()
752                .filter(|(_, message)| matches!(message, AgentMessage::User(_)))
753                .nth(count.saturating_sub(1))
754                .map(|(index, _)| index)
755                .unwrap_or(0);
756            safe[start..].to_vec()
757        }
758    }
759}
760
761#[cfg(test)]
762mod tests {
763    use super::*;
764    use kiss_ai::{AssistantMessage, ContentBlock, ToolCall};
765
766    fn assistant(text: &str) -> AgentMessage {
767        let mut message = AssistantMessage::empty("fake", "fake", "fake");
768        message.content.push(ContentBlock::text(text));
769        AgentMessage::Assistant(message)
770    }
771
772    fn parent_session() -> Arc<AgentSession> {
773        let registry = kiss_ai::Registry::from_builtin();
774        let model = registry.all().first().expect("built-in model").clone();
775        AgentSession::new_with_subagents_allowed(
776            crate::SessionManager::in_memory(std::path::Path::new("/test")),
777            Vec::new(),
778            registry,
779            crate::Settings::default(),
780            "test".into(),
781            model,
782            kiss_ai::ThinkingLevel::Off,
783            None,
784            Arc::new(|_| {}),
785            false,
786        )
787    }
788
789    #[test]
790    fn task_names_are_bounded_and_portable() {
791        assert!(validate_task_name("review_2").is_ok());
792        assert!(validate_task_name("").is_err());
793        assert!(validate_task_name("Review").is_err());
794        assert!(validate_task_name("has-dash").is_err());
795        assert!(validate_task_name(&"a".repeat(65)).is_err());
796    }
797
798    #[test]
799    fn fork_turns_accepts_only_documented_values() {
800        assert_eq!(ForkTurns::parse(None).unwrap(), ForkTurns::None);
801        assert_eq!(
802            ForkTurns::parse(Some(&json!("all"))).unwrap(),
803            ForkTurns::All
804        );
805        assert_eq!(
806            ForkTurns::parse(Some(&json!(2))).unwrap(),
807            ForkTurns::Recent(2)
808        );
809        assert!(ForkTurns::parse(Some(&json!(0))).is_err());
810        assert!(ForkTurns::parse(Some(&json!("recent"))).is_err());
811    }
812
813    #[test]
814    fn context_fork_removes_tool_pairs_and_keeps_recent_turns() {
815        let mut tool_message = AssistantMessage::empty("fake", "fake", "fake");
816        tool_message.content.push(ContentBlock::ToolCall(ToolCall {
817            id: "call".into(),
818            name: "read".into(),
819            arguments: json!({}),
820            thought_signature: None,
821            arguments_error: None,
822        }));
823        let history = vec![
824            AgentMessage::user("first"),
825            assistant("one"),
826            AgentMessage::Assistant(tool_message),
827            AgentMessage::user("second"),
828            assistant("two"),
829        ];
830
831        assert!(fork_messages(&history, ForkTurns::None).is_empty());
832        let all = fork_messages(&history, ForkTurns::All);
833        assert_eq!(all.len(), 4);
834        assert!(
835            all.iter()
836                .all(|message| !matches!(message, AgentMessage::ToolResult(_)))
837        );
838        let recent = fork_messages(&history, ForkTurns::Recent(1));
839        assert_eq!(recent, history[3..]);
840    }
841
842    #[test]
843    fn control_tool_catalog_uses_codex_names() {
844        let parent = Weak::new();
845        let runtime = SubagentRuntime::new(parent);
846        let names = runtime
847            .control_tools()
848            .into_iter()
849            .map(|tool| tool.name().to_string())
850            .collect::<Vec<_>>();
851        assert_eq!(
852            names,
853            [
854                "spawn_agent",
855                "send_message",
856                "followup_task",
857                "wait_agent",
858                "list_agents",
859                "interrupt_agent"
860            ]
861        );
862        for tool in runtime.control_tools() {
863            let schema = tool.parameters();
864            assert_eq!(schema["type"], "object", "{} schema", tool.name());
865            assert_eq!(
866                schema["additionalProperties"],
867                false,
868                "{} schema",
869                tool.name()
870            );
871        }
872        let spawn = runtime.control_tools().remove(0).parameters();
873        assert_eq!(spawn["required"], json!(["task_name", "prompt"]));
874        assert_eq!(
875            spawn["properties"]["fork_turns"]["oneOf"]
876                .as_array()
877                .unwrap()
878                .len(),
879            2
880        );
881    }
882
883    #[tokio::test]
884    async fn a_followup_after_an_interrupt_waits_for_the_old_turn_to_stop() {
885        let parent = parent_session();
886        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
887        let observed_calls = calls.clone();
888        // The first turn stops slowly after the abort, as a real tool can.
889        parent.set_stream_fn(Some(Arc::new(move |_, _, options| {
890            let step = observed_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
891            let mut message = kiss_ai::AssistantMessage::empty("test", "test", "test");
892            let (sink, stream) = kiss_ai::EventStream::channel();
893            if step == 0 {
894                let cancel = options.cancel.clone();
895                tokio::spawn(async move {
896                    cancel.cancelled().await;
897                    tokio::time::sleep(Duration::from_millis(50)).await;
898                    message.stop_reason = StopReason::Aborted;
899                    sink.error(message);
900                });
901            } else {
902                message.content = vec![kiss_ai::ContentBlock::Text {
903                    text: "second answer".into(),
904                    text_signature: None,
905                }];
906                message.stop_reason = StopReason::Stop;
907                sink.done(message);
908            }
909            stream
910        })));
911        let runtime = SubagentRuntime::with_permits(Arc::downgrade(&parent), 2);
912        runtime
913            .spawn(
914                "review_tests".into(),
915                "first".into(),
916                ForkTurns::None,
917                None,
918                None,
919            )
920            .unwrap();
921        tokio::time::timeout(Duration::from_secs(5), async {
922            while calls.load(std::sync::atomic::Ordering::SeqCst) == 0 {
923                tokio::task::yield_now().await;
924            }
925        })
926        .await
927        .expect("the first turn reaches the model");
928
929        runtime.interrupt("review_tests").unwrap();
930        runtime
931            .followup("review_tests", "second".into())
932            .expect("an interrupted agent accepts a follow-up");
933
934        let outcome = runtime
935            .wait(&["review_tests".into()], 5_000, CancellationToken::new())
936            .await
937            .unwrap();
938        assert!(!outcome.timed_out);
939        assert_eq!(outcome.agents[0].status, AgentStatus::Completed);
940        assert_eq!(outcome.agents[0].result.as_deref(), Some("second answer"));
941        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2);
942    }
943
944    #[tokio::test]
945    async fn queued_agent_can_be_listed_interrupted_and_waited_for() {
946        let parent = parent_session();
947        let runtime = SubagentRuntime::with_permits(Arc::downgrade(&parent), 0);
948        let spawned = runtime
949            .spawn(
950                "review_tests".into(),
951                "Review the tests".into(),
952                ForkTurns::None,
953                None,
954                None,
955            )
956            .unwrap();
957        assert_eq!(spawned.status, AgentStatus::Queued);
958        assert_eq!(runtime.list(), vec![spawned.clone()]);
959        assert!(
960            runtime
961                .spawn(
962                    "review_tests".into(),
963                    "Duplicate".into(),
964                    ForkTurns::None,
965                    None,
966                    None,
967                )
968                .is_err()
969        );
970
971        let waiting_runtime = runtime.clone();
972        let target = spawned.id.clone();
973        let waiting = tokio::spawn(async move {
974            waiting_runtime
975                .wait(&[target], 5_000, CancellationToken::new())
976                .await
977                .unwrap()
978        });
979        tokio::task::yield_now().await;
980        let interrupted = runtime.interrupt("review_tests").unwrap();
981        assert_eq!(interrupted.status, AgentStatus::Interrupted);
982        runtime.permits.add_permits(1);
983
984        let outcome = tokio::time::timeout(Duration::from_secs(1), waiting)
985            .await
986            .expect("mailbox wait")
987            .unwrap();
988        assert!(!outcome.timed_out);
989        assert_eq!(outcome.agents[0].status, AgentStatus::Interrupted);
990    }
991}