Skip to main content

microclaw_engine/tools/
subagents.rs

1use async_trait::async_trait;
2use serde_json::json;
3use std::collections::{BTreeSet, HashMap};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, LazyLock, Mutex};
6use tokio::sync::Semaphore;
7use tracing::{info, warn};
8
9use super::{
10    auth_context_from_input, authorize_chat_access, schema_object, Tool, ToolAuthContext,
11    ToolRegistry, ToolResult,
12};
13use crate::config::{Config, ResolvedSubagentAcpTargetConfig};
14use crate::internal::channels::channel::deliver_and_store_bot_message;
15use crate::internal::channels::channel_adapter::ChannelRegistry;
16use crate::internal::storage::db::{
17    call_blocking, CreateSubagentRunParams, Database, FinishSubagentRunParams,
18};
19use microclaw_core::llm_types::{
20    ContentBlock, Message, MessageContent, ResponseContentBlock, ToolDefinition,
21};
22
23const MAX_SUB_AGENT_ITERATIONS: usize = 16;
24
25#[derive(Debug, Clone, Copy)]
26enum SubagentExecutionRuntime {
27    Native,
28    Acp,
29}
30
31impl SubagentExecutionRuntime {
32    fn from_raw(raw: Option<&str>) -> Result<Self, String> {
33        match raw.unwrap_or("native").trim().to_ascii_lowercase().as_str() {
34            "" | "native" => Ok(Self::Native),
35            "acp" => Ok(Self::Acp),
36            other => Err(format!(
37                "Unsupported subagent runtime '{other}'. Expected 'native' or 'acp'."
38            )),
39        }
40    }
41
42    fn from_input(
43        input: &serde_json::Value,
44        parent_meta: Option<&SubagentRuntimeMeta>,
45    ) -> Result<Self, String> {
46        let runtime = input
47            .get("runtime")
48            .and_then(|v| v.as_str())
49            .or_else(|| parent_meta.and_then(|meta| meta.runtime.as_deref()));
50        Self::from_raw(runtime)
51    }
52
53    fn as_str(&self) -> &'static str {
54        match self {
55            Self::Native => "native",
56            Self::Acp => "acp",
57        }
58    }
59}
60
61#[derive(Debug, Clone)]
62struct SubagentRuntimeMeta {
63    depth: i64,
64    token_budget_remaining: Option<i64>,
65    runtime: Option<String>,
66    runtime_target: Option<String>,
67}
68
69fn subagent_runtime_meta_from_input(input: &serde_json::Value) -> Option<SubagentRuntimeMeta> {
70    let meta = input.get("__subagent_runtime")?;
71    let depth = meta.get("depth").and_then(|v| v.as_i64()).unwrap_or(0);
72    let token_budget_remaining = meta
73        .get("token_budget_remaining")
74        .and_then(|v| v.as_i64())
75        .filter(|v| *v > 0);
76    let runtime = meta
77        .get("runtime")
78        .and_then(|v| v.as_str())
79        .map(str::trim)
80        .filter(|v| !v.is_empty())
81        .map(ToOwned::to_owned);
82    let runtime_target = meta
83        .get("runtime_target")
84        .and_then(|v| v.as_str())
85        .map(str::trim)
86        .filter(|v| !v.is_empty())
87        .map(ToOwned::to_owned);
88    Some(SubagentRuntimeMeta {
89        depth,
90        token_budget_remaining,
91        runtime,
92        runtime_target,
93    })
94}
95
96fn compute_child_token_budget(
97    requested_budget: Option<i64>,
98    parent_budget_remaining: Option<i64>,
99    configured_max: i64,
100) -> Result<i64, String> {
101    let configured_max = configured_max.clamp(2_000, 2_000_000);
102    if let Some(parent_remaining) = parent_budget_remaining {
103        if parent_remaining < 2_000 {
104            return Err(format!(
105                "subagent budget exhausted: parent remaining {} < 2000",
106                parent_remaining
107            ));
108        }
109        let desired = requested_budget.unwrap_or((parent_remaining / 2).max(2_000));
110        return Ok(desired.clamp(2_000, parent_remaining.min(configured_max)));
111    }
112    let desired = requested_budget.unwrap_or(configured_max);
113    Ok(desired.clamp(2_000, configured_max))
114}
115
116/// Name of the synthetic tool a sub-agent calls to return its final structured
117/// result. Using a tool input schema is the provider-native way to constrain the
118/// shape of the output (validated function/tool arguments on both Anthropic and
119/// OpenAI), which is far more reliable than parsing free-text JSON.
120const SUBMIT_RESULT_TOOL: &str = "submit_result";
121
122/// The contract schema, expressed as a tool so the model emits it as validated
123/// tool input rather than free text.
124fn submit_result_tool_definition() -> ToolDefinition {
125    ToolDefinition {
126        name: SUBMIT_RESULT_TOOL.to_string(),
127        description:
128            "Submit your final structured result and end the run. Call this exactly once when the \
129             task is complete, instead of writing the result as plain text."
130                .to_string(),
131        input_schema: json!({
132            "type": "object",
133            "properties": {
134                "summary": {"type": "string", "description": "One-line summary of what you did."},
135                "findings": {"type": "array", "items": {"type": "string"}, "description": "Key findings or results."},
136                "artifacts": {"type": "array", "items": {"type": "object"}, "description": "Files/artifacts produced, each {type, path, description}."},
137                "next_actions": {"type": "array", "items": {"type": "string"}, "description": "Suggested follow-up actions."},
138                "final_answer": {"type": "string", "description": "The full answer delivered to the user."}
139            },
140            "required": ["summary", "final_answer"]
141        }),
142    }
143}
144
145/// Whether the sub-agent's terminal text actually carries the structured
146/// output contract — a JSON object with a non-empty `summary` or `final_answer`
147/// — as opposed to raw prose or leaked reasoning. Drives the one-shot repair
148/// re-ask in the sub-agent loop before falling back to best-effort
149/// normalization.
150pub(crate) fn subagent_output_is_structured(raw_text: &str) -> bool {
151    let cleaned = crate::agent_engine::sanitize_user_visible_text(raw_text);
152    let text = cleaned.trim();
153    let parsed = serde_json::from_str::<serde_json::Value>(text)
154        .ok()
155        .or_else(|| {
156            let start = text.find('{')?;
157            let end = text.rfind('}')?;
158            if end > start {
159                serde_json::from_str::<serde_json::Value>(&text[start..=end]).ok()
160            } else {
161                None
162            }
163        });
164    parsed
165        .as_ref()
166        .and_then(|v| v.as_object())
167        .map(|obj| {
168            ["final_answer", "summary"].iter().any(|k| {
169                obj.get(*k)
170                    .and_then(|v| v.as_str())
171                    .map(|s| !s.trim().is_empty())
172                    .unwrap_or(false)
173            })
174        })
175        .unwrap_or(false)
176}
177
178pub(crate) fn normalize_subagent_artifact_payload(raw_text: &str) -> (String, String) {
179    // Strip any chain-of-thought the model emitted so it never leaks into the
180    // chat announcement, and so a JSON object that follows a <think> block can
181    // still be parsed (a leading reasoning block makes a whole-string parse fail).
182    let cleaned = crate::agent_engine::sanitize_user_visible_text(raw_text);
183    let text = cleaned.trim();
184    // Prefer a clean whole-string parse; otherwise recover an embedded {...}
185    // object (model wrapped the JSON in prose) so we don't fall back to dumping
186    // raw reasoning as the answer.
187    let parsed = serde_json::from_str::<serde_json::Value>(text)
188        .ok()
189        .or_else(|| {
190            let start = text.find('{')?;
191            let end = text.rfind('}')?;
192            if end > start {
193                serde_json::from_str::<serde_json::Value>(&text[start..=end]).ok()
194            } else {
195                None
196            }
197        });
198    let mut summary = String::new();
199    let mut final_answer = String::new();
200    let mut findings: Vec<String> = Vec::new();
201    let mut next_actions: Vec<String> = Vec::new();
202    let mut artifacts: Vec<serde_json::Value> = Vec::new();
203    if let Some(obj) = parsed.as_ref().and_then(|v| v.as_object()) {
204        summary = obj
205            .get("summary")
206            .and_then(|v| v.as_str())
207            .unwrap_or("")
208            .trim()
209            .to_string();
210        final_answer = obj
211            .get("final_answer")
212            .and_then(|v| v.as_str())
213            .unwrap_or("")
214            .trim()
215            .to_string();
216        if let Some(arr) = obj.get("findings").and_then(|v| v.as_array()) {
217            findings = arr
218                .iter()
219                .filter_map(|v| v.as_str())
220                .map(str::trim)
221                .filter(|v| !v.is_empty())
222                .map(ToOwned::to_owned)
223                .collect();
224        }
225        if let Some(arr) = obj.get("next_actions").and_then(|v| v.as_array()) {
226            next_actions = arr
227                .iter()
228                .filter_map(|v| v.as_str())
229                .map(str::trim)
230                .filter(|v| !v.is_empty())
231                .map(ToOwned::to_owned)
232                .collect();
233        }
234        if let Some(arr) = obj.get("artifacts").and_then(|v| v.as_array()) {
235            artifacts = arr.clone();
236        }
237    }
238    if summary.is_empty() {
239        summary = text
240            .chars()
241            .take(600)
242            .collect::<String>()
243            .trim()
244            .to_string();
245    }
246    if final_answer.is_empty() {
247        final_answer = summary.clone();
248    }
249    let envelope = json!({
250        "protocol": "subagent_artifact_v1",
251        "summary": summary,
252        "findings": findings,
253        "artifacts": artifacts,
254        "next_actions": next_actions,
255        "final_answer": final_answer,
256        "raw_text": text,
257    });
258    let answer_text = envelope
259        .get("final_answer")
260        .and_then(|v| v.as_str())
261        .unwrap_or("(sub-agent produced no output)")
262        .to_string();
263    (answer_text, envelope.to_string())
264}
265
266struct SubagentRuntime {
267    semaphore: Semaphore,
268    cancel_flags: Mutex<HashMap<String, Arc<AtomicBool>>>,
269}
270
271impl SubagentRuntime {
272    fn new(max_concurrent: usize) -> Self {
273        Self {
274            semaphore: Semaphore::new(max_concurrent.max(1)),
275            cancel_flags: Mutex::new(HashMap::new()),
276        }
277    }
278
279    fn register_run(&self, run_id: &str) -> Arc<AtomicBool> {
280        let flag = Arc::new(AtomicBool::new(false));
281        if let Ok(mut guard) = self.cancel_flags.lock() {
282            guard.insert(run_id.to_string(), flag.clone());
283        }
284        flag
285    }
286
287    fn cancel_run(&self, run_id: &str) {
288        if let Ok(guard) = self.cancel_flags.lock() {
289            if let Some(flag) = guard.get(run_id) {
290                flag.store(true, Ordering::Relaxed);
291            }
292        }
293    }
294
295    fn remove_run(&self, run_id: &str) {
296        if let Ok(mut guard) = self.cancel_flags.lock() {
297            guard.remove(run_id);
298        }
299    }
300}
301
302static RUNTIME: LazyLock<Mutex<Option<Arc<SubagentRuntime>>>> = LazyLock::new(|| Mutex::new(None));
303
304// Subagent runs must outlive the Tokio runtime of the foreground caller. MicroClaw Code
305// intentionally creates a short-lived runtime for each turn; spawning on that
306// runtime used to abort accepted background runs as soon as the Main Agent
307// finished. A process-lifetime executor gives Server and Code the same durable
308// in-process lifecycle while SQLite remains the restart recovery authority.
309static TASK_RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
310    tokio::runtime::Builder::new_multi_thread()
311        .enable_all()
312        .thread_name("microclaw-subagent")
313        .build()
314        .expect("failed to create process-lifetime subagent runtime")
315});
316
317fn subagent_runtime(config: &Config) -> Arc<SubagentRuntime> {
318    let mut guard = match RUNTIME.lock() {
319        Ok(g) => g,
320        Err(poisoned) => poisoned.into_inner(),
321    };
322    if let Some(existing) = guard.as_ref() {
323        return existing.clone();
324    }
325    let runtime = Arc::new(SubagentRuntime::new(config.subagents.max_concurrent));
326    *guard = Some(runtime.clone());
327    runtime
328}
329
330/// Shared cancellation boundary for product UIs that already resolved and
331/// authorized the owning chat. The database flag survives process failure;
332/// the in-memory flag interrupts a currently executing run promptly.
333pub fn request_subagent_cancel(
334    config: &Config,
335    db: &Database,
336    chat_id: i64,
337    run_id: &str,
338) -> Result<bool, microclaw_core::error::MicroClawError> {
339    let requested = db.request_subagent_cancel(run_id, chat_id)?;
340    if requested {
341        subagent_runtime(config).cancel_run(run_id);
342    }
343    Ok(requested)
344}
345
346async fn log_subagent_event(
347    db: Arc<Database>,
348    run_id: &str,
349    event_type: &str,
350    detail: Option<String>,
351) {
352    let run_id = run_id.to_string();
353    let event_type = event_type.to_string();
354    let _ = call_blocking(db, move |db| {
355        db.append_subagent_event(&run_id, &event_type, detail.as_deref())
356    })
357    .await;
358}
359
360pub(crate) async fn is_cancelled(
361    db: Arc<Database>,
362    run_id: &str,
363    local_flag: &Arc<AtomicBool>,
364) -> Result<bool, String> {
365    if local_flag.load(Ordering::Relaxed) {
366        return Ok(true);
367    }
368    let run_id_owned = run_id.to_string();
369    let db_cancel = call_blocking(db, move |db| db.is_subagent_cancel_requested(&run_id_owned))
370        .await
371        .map_err(|e| format!("Failed checking cancel state: {e}"))?;
372    Ok(db_cancel)
373}
374
375struct RunSubAgentTaskParams {
376    config: Config,
377    db: Arc<Database>,
378    channel_registry: Arc<ChannelRegistry>,
379    auth_context: ToolAuthContext,
380    run_id: String,
381    runtime: SubagentExecutionRuntime,
382    acp_target: Option<ResolvedSubagentAcpTargetConfig>,
383    depth: i64,
384    run_token_budget: i64,
385    task: String,
386    context: String,
387    specialist: String,
388    /// A project agent (`.microclaw/agents/<name>.md`) to run as: its
389    /// prompt replaces the specialist persona and its `tools` narrow the
390    /// tool set.
391    agent: Option<crate::tools::explore::ProjectAgent>,
392    exit_criteria: Vec<crate::completion_contract::ExitCriterion>,
393    local_cancel: Arc<AtomicBool>,
394}
395
396/// Bash-backed runner for `Command` exit criteria: routes through the
397/// sub-agent's own tool registry, so the sandbox router, dangerous-pattern
398/// checks, and tool_policy apply exactly as for agent-issued commands.
399struct SubagentBashRunner<'a> {
400    tools: &'a ToolRegistry,
401    auth: &'a ToolAuthContext,
402}
403
404#[async_trait::async_trait]
405impl crate::completion_contract::CommandRunner for SubagentBashRunner<'_> {
406    async fn run(&self, command: &str) -> (bool, String) {
407        let result = self
408            .tools
409            .execute_with_auth("bash", json!({ "command": command }), self.auth)
410            .await;
411        (!result.is_error, result.content)
412    }
413}
414
415/// Result of verifying a finished sub-agent result against its contract.
416struct ContractVerdict {
417    /// Result text with the evidence report prepended.
418    annotated: String,
419    /// The report alone (used to prompt the bounded in-run retry).
420    report: String,
421    passed: bool,
422}
423
424/// Verify a finished result against its completion contract (if any) and
425/// build the evidence report, so the parent loop and the user see
426/// VERIFIED/FAILED with per-criterion evidence instead of trusting the
427/// sub-agent's self-report. Returns `None` when no contract was declared.
428#[allow(clippy::too_many_arguments)]
429async fn apply_completion_contract(
430    criteria: &[crate::completion_contract::ExitCriterion],
431    final_text: &str,
432    config: &Config,
433    tools: &ToolRegistry,
434    auth: &ToolAuthContext,
435    db: Arc<Database>,
436    run_id: &str,
437) -> Option<ContractVerdict> {
438    if criteria.is_empty() {
439        return None;
440    }
441    let base = std::path::Path::new(&config.working_dir);
442    let working_dir = match config.working_dir_isolation {
443        crate::config::WorkingDirIsolation::Direct => base.to_path_buf(),
444        crate::config::WorkingDirIsolation::Shared => base.join("shared"),
445        crate::config::WorkingDirIsolation::Chat => {
446            crate::internal::tool_runtime::runtime::chat_working_dir(
447                base,
448                &auth.caller_channel,
449                auth.caller_chat_id,
450            )
451        }
452    };
453    let runner = SubagentBashRunner { tools, auth };
454    let outcomes = crate::completion_contract::verify_criteria(
455        criteria,
456        final_text,
457        &working_dir,
458        Some(&runner),
459    )
460    .await;
461    let passed = outcomes.iter().filter(|o| o.passed).count();
462    log_subagent_event(
463        db,
464        run_id,
465        "contract",
466        Some(format!(
467            "{} {passed}/{}",
468            if passed == outcomes.len() {
469                "verified"
470            } else {
471                "failed"
472            },
473            outcomes.len()
474        )),
475    )
476    .await;
477    let report = crate::completion_contract::render_report(&outcomes);
478    Some(ContractVerdict {
479        annotated: format!("{report}\n{final_text}"),
480        passed: passed == outcomes.len(),
481        report,
482    })
483}
484
485/// Prompt sent back into the sub-agent conversation for the single bounded
486/// contract retry.
487fn contract_retry_prompt(report: &str) -> String {
488    format!(
489        "Completion contract verification FAILED:\n{report}\nThe failed criteria are unmet \
490         work — complete them now (use tools), then submit your result again via `submit_result`. \
491         This is your final attempt."
492    )
493}
494
495async fn run_sub_agent_task(
496    params: RunSubAgentTaskParams,
497) -> Result<(String, String, i64, i64), String> {
498    let RunSubAgentTaskParams {
499        config,
500        db,
501        channel_registry,
502        auth_context,
503        run_id,
504        runtime,
505        acp_target,
506        depth,
507        run_token_budget,
508        task,
509        context,
510        specialist,
511        agent,
512        exit_criteria,
513        local_cancel,
514    } = params;
515    if matches!(runtime, SubagentExecutionRuntime::Acp) {
516        let Some(acp_target) = acp_target else {
517            return Err("ACP runtime target was not resolved".into());
518        };
519        // Contracts on the ACP runtime: the external agent's conversation is
520        // not ours to continue, so the bounded retry is a full re-run with
521        // the failure evidence appended to the context.
522        let mut context = context;
523        if !exit_criteria.is_empty() {
524            context.push_str(&crate::completion_contract::render_for_prompt(
525                &exit_criteria,
526            ));
527        }
528        let first = crate::acp_subagent::run_acp_subagent_task(
529            crate::acp_subagent::AcpSubagentTaskParams {
530                config: config.clone(),
531                db: db.clone(),
532                auth_context: auth_context.clone(),
533                run_id: run_id.clone(),
534                task: task.clone(),
535                context: context.clone(),
536                local_cancel: local_cancel.clone(),
537                target: acp_target.clone(),
538            },
539        )
540        .await?;
541        if exit_criteria.is_empty() {
542            return Ok(first);
543        }
544        // Verification (and its command runner) go through our own sub-agent
545        // tool registry — same sandbox/policy guards as the native runtime.
546        let tools = ToolRegistry::new_sub_agent(&config, db.clone(), Some(channel_registry), false);
547        let (final_text, artifact_json, mut in_tok, mut out_tok) = first;
548        let verdict = apply_completion_contract(
549            &exit_criteria,
550            &final_text,
551            &config,
552            &tools,
553            &auth_context,
554            db.clone(),
555            &run_id,
556        )
557        .await
558        .expect("criteria checked non-empty");
559        if verdict.passed {
560            return Ok((verdict.annotated, artifact_json, in_tok, out_tok));
561        }
562        log_subagent_event(db.clone(), &run_id, "contract_retry", None).await;
563        let retry_context = format!("{context}\n\n{}", contract_retry_prompt(&verdict.report));
564        let (retry_text, retry_artifact, retry_in, retry_out) =
565            crate::acp_subagent::run_acp_subagent_task(
566                crate::acp_subagent::AcpSubagentTaskParams {
567                    config: config.clone(),
568                    db: db.clone(),
569                    auth_context: auth_context.clone(),
570                    run_id: run_id.clone(),
571                    task,
572                    context: retry_context,
573                    local_cancel,
574                    target: acp_target,
575                },
576            )
577            .await?;
578        in_tok += retry_in;
579        out_tok += retry_out;
580        let verdict = apply_completion_contract(
581            &exit_criteria,
582            &retry_text,
583            &config,
584            &tools,
585            &auth_context,
586            db.clone(),
587            &run_id,
588        )
589        .await
590        .expect("criteria checked non-empty");
591        return Ok((verdict.annotated, retry_artifact, in_tok, out_tok));
592    }
593
594    let llm = crate::llm::create_provider(&config);
595    let allow_session_tools = depth < config.subagents.max_spawn_depth as i64;
596    let tools = ToolRegistry::new_sub_agent(
597        &config,
598        db.clone(),
599        Some(channel_registry),
600        allow_session_tools,
601    );
602    // The sub-agent's normal tools plus a synthetic `submit_result` tool used to
603    // return the final structured result as validated tool input (native
604    // constrained decoding) rather than hand-written JSON text.
605    let mut tool_defs = tools.definitions_for(&auth_context);
606    if let Some(agent) = &agent {
607        tool_defs.retain(|d| agent.allows(&d.name));
608    }
609    tool_defs.push(submit_result_tool_definition());
610
611    let profile = crate::tools::specialists::resolve_specialist(Some(specialist.as_str()));
612    let persona = match &agent {
613        Some(agent) => agent.prompt.as_str(),
614        None => profile.persona,
615    };
616    let system_prompt = format!(
617        "{persona}\n\nComplete the task thoroughly with tool use when needed.\nYou are a background worker: you have NO tools to message the chat, write memory, or schedule tasks (no `send_message`, `write_memory`, or `schedule` — do not look for them or stall when they are missing). `read_memory` and `structured_memory_search` are read-only lookups. Any durable facts you surface in `findings`/`final_answer` are persisted by the orchestrator automatically — just report them, don't try to save them yourself.\nFor long tasks, call `report_progress` at meaningful milestones with a one-line status so the user gets colleague-style updates while you work.\nIf a sub-problem falls outside your expertise, get a quick second opinion from the right specialist with `consult_specialist` (e.g. as a researcher, hand a draft to the writer; as a coder, ask the mathematician to check a formula) and weave their answer into your work — don't fake expertise you don't have. If a sub-problem is large enough to need its own run and you're allowed to spawn, delegate it with `sessions_spawn`; otherwise name the right specialist in next_actions.\nOutput contract (required): when the task is complete, call the `submit_result` tool exactly once with your structured result (summary, findings, artifacts, next_actions, final_answer). Prefer `submit_result` over writing the result as text. If you do answer in text instead, it MUST be a single JSON object with those same keys and nothing else.",
618        persona = persona
619    );
620
621    let mut user_content = if context.is_empty() {
622        task.to_string()
623    } else {
624        format!("Context: {context}\n\nTask: {task}")
625    };
626    if !exit_criteria.is_empty() {
627        user_content.push_str(&crate::completion_contract::render_for_prompt(
628            &exit_criteria,
629        ));
630    }
631
632    let mut messages = vec![Message {
633        role: "user".into(),
634        content: MessageContent::Text(user_content),
635    }];
636    let mut input_tokens_sum = 0_i64;
637    let mut output_tokens_sum = 0_i64;
638    // Bounded (one-shot) repair: if the model ends without the required JSON
639    // contract, we re-ask exactly once before falling back to best-effort
640    // normalization. Prevents an unbounded re-ask loop.
641    let mut repair_attempted = false;
642    // Bounded contract retry: when the completion contract fails, give the
643    // sub-agent exactly ONE chance to finish the unmet criteria before the
644    // failed result is returned as-is.
645    let mut contract_retry_attempted = false;
646
647    for _ in 0..MAX_SUB_AGENT_ITERATIONS {
648        if is_cancelled(db.clone(), &run_id, &local_cancel).await? {
649            return Err("cancelled".into());
650        }
651
652        let response = llm
653            .send_message(&system_prompt, messages.clone(), Some(tool_defs.clone()))
654            .await
655            .map_err(|e| format!("Sub-agent API error: {e}"))?;
656
657        if let Some(usage) = &response.usage {
658            let input_tokens = i64::from(usage.input_tokens);
659            let output_tokens = i64::from(usage.output_tokens);
660            input_tokens_sum += input_tokens;
661            output_tokens_sum += output_tokens;
662
663            let channel = auth_context.caller_channel.clone();
664            let provider = config.llm_provider.clone();
665            let model = config.model.clone();
666            let chat_id = auth_context.caller_chat_id;
667            let _ = call_blocking(db.clone(), move |db| {
668                db.log_llm_usage(
669                    chat_id,
670                    &channel,
671                    &provider,
672                    &model,
673                    input_tokens,
674                    output_tokens,
675                    "subagent_run",
676                )
677                .map(|_| ())
678            })
679            .await;
680            let total = input_tokens_sum + output_tokens_sum;
681            if run_token_budget > 0 && total > run_token_budget {
682                return Err(format!(
683                    "budget_exceeded: total_tokens={} budget={}",
684                    total, run_token_budget
685                ));
686            }
687        }
688
689        let stop_reason = response.stop_reason.as_deref().unwrap_or("end_turn");
690        if stop_reason == "end_turn" || stop_reason == "max_tokens" {
691            let text = response
692                .content
693                .iter()
694                .filter_map(|block| match block {
695                    ResponseContentBlock::Text { text } => Some(text.as_str()),
696                    _ => None,
697                })
698                .collect::<Vec<_>>()
699                .join("");
700            // One-shot repair re-ask: the contract requires a JSON object, but
701            // models sometimes stop on prose or leaked reasoning. Ask once for
702            // clean JSON before falling back to best-effort normalization. Only
703            // for a natural `end_turn`; a `max_tokens` stop is truncation, where
704            // re-asking would just burn more budget without fixing the shape.
705            if stop_reason == "end_turn"
706                && !repair_attempted
707                && !text.trim().is_empty()
708                && !subagent_output_is_structured(&text)
709            {
710                repair_attempted = true;
711                log_subagent_event(db.clone(), &run_id, "output_repair", None).await;
712                messages.push(Message {
713                    role: "assistant".into(),
714                    content: MessageContent::Text(text),
715                });
716                messages.push(Message {
717                    role: "user".into(),
718                    content: MessageContent::Text(
719                        "Your previous reply was not the required output. Respond with ONLY a single JSON object matching the contract: {\"summary\":string,\"findings\":string[],\"artifacts\":[],\"next_actions\":string[],\"final_answer\":string}. No prose, no markdown fences, no <think> tags."
720                            .into(),
721                    ),
722                });
723                continue;
724            }
725            let source = if text.is_empty() {
726                "(sub-agent produced no output)".to_string()
727            } else {
728                text
729            };
730            let (final_text, artifact_json) = normalize_subagent_artifact_payload(&source);
731            match apply_completion_contract(
732                &exit_criteria,
733                &final_text,
734                &config,
735                &tools,
736                &auth_context,
737                db.clone(),
738                &run_id,
739            )
740            .await
741            {
742                Some(verdict) if !verdict.passed && !contract_retry_attempted => {
743                    contract_retry_attempted = true;
744                    log_subagent_event(db.clone(), &run_id, "contract_retry", None).await;
745                    messages.push(Message {
746                        role: "assistant".into(),
747                        content: MessageContent::Text(verdict.annotated),
748                    });
749                    messages.push(Message {
750                        role: "user".into(),
751                        content: MessageContent::Text(contract_retry_prompt(&verdict.report)),
752                    });
753                    continue;
754                }
755                Some(verdict) => {
756                    return Ok((
757                        verdict.annotated,
758                        artifact_json,
759                        input_tokens_sum,
760                        output_tokens_sum,
761                    ));
762                }
763                None => {
764                    return Ok((
765                        final_text,
766                        artifact_json,
767                        input_tokens_sum,
768                        output_tokens_sum,
769                    ));
770                }
771            }
772        }
773
774        if stop_reason == "tool_use" {
775            // If the model called `submit_result`, its (schema-validated) input
776            // IS the final structured result — short-circuit and return it.
777            if let Some(submit_input) = response.content.iter().find_map(|b| match b {
778                ResponseContentBlock::ToolUse { name, input, .. } if name == SUBMIT_RESULT_TOOL => {
779                    Some(input.clone())
780                }
781                _ => None,
782            }) {
783                log_subagent_event(db.clone(), &run_id, "submit_result", None).await;
784                let (final_text, artifact_json) =
785                    normalize_subagent_artifact_payload(&submit_input.to_string());
786                match apply_completion_contract(
787                    &exit_criteria,
788                    &final_text,
789                    &config,
790                    &tools,
791                    &auth_context,
792                    db.clone(),
793                    &run_id,
794                )
795                .await
796                {
797                    Some(verdict) if !verdict.passed && !contract_retry_attempted => {
798                        contract_retry_attempted = true;
799                        log_subagent_event(db.clone(), &run_id, "contract_retry", None).await;
800                        // Keep the tool_use/tool_result pairing the provider
801                        // requires: echo the assistant turn (including the
802                        // submit_result call), then answer that call with the
803                        // failure report.
804                        let submit_id = response
805                            .content
806                            .iter()
807                            .find_map(|b| match b {
808                                ResponseContentBlock::ToolUse { id, name, .. }
809                                    if name == SUBMIT_RESULT_TOOL =>
810                                {
811                                    Some(id.clone())
812                                }
813                                _ => None,
814                            })
815                            .unwrap_or_default();
816                        let assistant_content: Vec<ContentBlock> = response
817                            .content
818                            .iter()
819                            .filter_map(|block| match block {
820                                ResponseContentBlock::Text { text } => {
821                                    Some(ContentBlock::Text { text: text.clone() })
822                                }
823                                ResponseContentBlock::ToolUse {
824                                    id,
825                                    name,
826                                    input,
827                                    thought_signature,
828                                } => Some(ContentBlock::ToolUse {
829                                    id: id.clone(),
830                                    name: name.clone(),
831                                    input: input.clone(),
832                                    thought_signature: thought_signature.clone(),
833                                }),
834                                ResponseContentBlock::Other => None,
835                            })
836                            .collect();
837                        messages.push(Message {
838                            role: "assistant".into(),
839                            content: MessageContent::Blocks(assistant_content),
840                        });
841                        messages.push(Message {
842                            role: "user".into(),
843                            content: MessageContent::Blocks(vec![ContentBlock::ToolResult {
844                                tool_use_id: submit_id,
845                                content: contract_retry_prompt(&verdict.report),
846                                is_error: Some(true),
847                            }]),
848                        });
849                        continue;
850                    }
851                    Some(verdict) => {
852                        return Ok((
853                            verdict.annotated,
854                            artifact_json,
855                            input_tokens_sum,
856                            output_tokens_sum,
857                        ));
858                    }
859                    None => {
860                        return Ok((
861                            final_text,
862                            artifact_json,
863                            input_tokens_sum,
864                            output_tokens_sum,
865                        ));
866                    }
867                }
868            }
869
870            let assistant_content: Vec<ContentBlock> = response
871                .content
872                .iter()
873                .filter_map(|block| match block {
874                    ResponseContentBlock::Text { text } => {
875                        Some(ContentBlock::Text { text: text.clone() })
876                    }
877                    ResponseContentBlock::ToolUse {
878                        id,
879                        name,
880                        input,
881                        thought_signature,
882                    } => Some(ContentBlock::ToolUse {
883                        id: id.clone(),
884                        name: name.clone(),
885                        input: input.clone(),
886                        thought_signature: thought_signature.clone(),
887                    }),
888                    ResponseContentBlock::Other => None,
889                })
890                .collect();
891
892            messages.push(Message {
893                role: "assistant".into(),
894                content: MessageContent::Blocks(assistant_content),
895            });
896
897            let mut tool_results = Vec::new();
898            for block in &response.content {
899                if let ResponseContentBlock::ToolUse {
900                    id, name, input, ..
901                } = block
902                {
903                    log_subagent_event(
904                        db.clone(),
905                        &run_id,
906                        "tool_use",
907                        Some(format!("tool={name}")),
908                    )
909                    .await;
910                    let mut tool_input = input.clone();
911                    if let Some(obj) = tool_input.as_object_mut() {
912                        let remaining_budget = if run_token_budget > 0 {
913                            Some((run_token_budget - input_tokens_sum - output_tokens_sum).max(0))
914                        } else {
915                            None
916                        };
917                        obj.insert(
918                            "__subagent_runtime".to_string(),
919                            json!({
920                                "run_id": run_id.clone(),
921                                "depth": depth,
922                                "runtime": "native",
923                                "runtime_target": serde_json::Value::Null,
924                                "token_budget_remaining": remaining_budget,
925                            }),
926                        );
927                    }
928                    let result = if agent.as_ref().is_some_and(|a| !a.allows(name)) {
929                        ToolResult::error(format!("`{name}` is not in this agent's `tools` list"))
930                    } else {
931                        tools
932                            .execute_with_auth(name, tool_input, &auth_context)
933                            .await
934                    };
935                    tool_results.push(ContentBlock::ToolResult {
936                        tool_use_id: id.clone(),
937                        content: result.content,
938                        is_error: if result.is_error { Some(true) } else { None },
939                    });
940                }
941            }
942
943            messages.push(Message {
944                role: "user".into(),
945                content: MessageContent::Blocks(tool_results),
946            });
947            continue;
948        }
949
950        let text = response
951            .content
952            .iter()
953            .filter_map(|block| match block {
954                ResponseContentBlock::Text { text } => Some(text.as_str()),
955                _ => None,
956            })
957            .collect::<Vec<_>>()
958            .join("");
959        let source = if text.is_empty() {
960            "(sub-agent produced no output)".to_string()
961        } else {
962            text
963        };
964        let (final_text, artifact_json) = normalize_subagent_artifact_payload(&source);
965        match apply_completion_contract(
966            &exit_criteria,
967            &final_text,
968            &config,
969            &tools,
970            &auth_context,
971            db.clone(),
972            &run_id,
973        )
974        .await
975        {
976            Some(verdict) if !verdict.passed && !contract_retry_attempted => {
977                contract_retry_attempted = true;
978                log_subagent_event(db.clone(), &run_id, "contract_retry", None).await;
979                messages.push(Message {
980                    role: "assistant".into(),
981                    content: MessageContent::Text(verdict.annotated),
982                });
983                messages.push(Message {
984                    role: "user".into(),
985                    content: MessageContent::Text(contract_retry_prompt(&verdict.report)),
986                });
987                continue;
988            }
989            Some(verdict) => {
990                return Ok((
991                    verdict.annotated,
992                    artifact_json,
993                    input_tokens_sum,
994                    output_tokens_sum,
995                ));
996            }
997            None => {
998                return Ok((
999                    final_text,
1000                    artifact_json,
1001                    input_tokens_sum,
1002                    output_tokens_sum,
1003                ));
1004            }
1005        }
1006    }
1007
1008    Err("Sub-agent reached maximum iterations without completing the task.".into())
1009}
1010
1011/// When the last child of a parent finishes, post one consolidated summary of
1012/// the whole batch. Idempotent: the announce is keyed on `<parent>:fanin`, whose
1013/// UNIQUE constraint means only one fan-in message is ever enqueued even if
1014/// several children finish at once.
1015async fn maybe_post_fan_in_summary(
1016    config: &Config,
1017    channel_registry: Arc<ChannelRegistry>,
1018    db: Arc<Database>,
1019    chat_id: i64,
1020    parent_id: &str,
1021) {
1022    let parent_owned = parent_id.to_string();
1023    let active = call_blocking(db.clone(), {
1024        let p = parent_owned.clone();
1025        move |db| db.count_active_subagent_children(&p)
1026    })
1027    .await
1028    .unwrap_or(0);
1029    if active > 0 {
1030        return;
1031    }
1032    let children = match call_blocking(db.clone(), {
1033        let p = parent_owned.clone();
1034        move |db| db.list_subagent_children(&p)
1035    })
1036    .await
1037    {
1038        Ok(v) => v,
1039        Err(e) => {
1040            warn!("fan-in: failed to list children of {parent_id}: {e}");
1041            return;
1042        }
1043    };
1044    // Only summarize genuine batches (the single-child case is covered by its
1045    // own completion message).
1046    if children.len() < 2 {
1047        return;
1048    }
1049
1050    let n = children.len();
1051    let mut lines = vec![format!("🧩 All {n} sub-tasks done:")];
1052    let mut caller_channel = String::new();
1053    for c in &children {
1054        if caller_channel.is_empty() {
1055            caller_channel = c.caller_channel.clone();
1056        }
1057        let emoji = match c.status.as_str() {
1058            "completed" => "✅",
1059            "cancelled" => "🛑",
1060            "timed_out" => "⏱️",
1061            _ => "❌",
1062        };
1063        let name = c
1064            .label
1065            .clone()
1066            .filter(|l| !l.trim().is_empty())
1067            .unwrap_or_else(|| c.task.chars().take(40).collect::<String>());
1068        let detail = c
1069            .result_text
1070            .clone()
1071            .or_else(|| c.error_text.clone())
1072            .map(|t| {
1073                let snippet: String = t.trim().chars().take(120).collect();
1074                format!(" — {snippet}")
1075            })
1076            .unwrap_or_default();
1077        lines.push(format!("{emoji} {name}{detail}"));
1078    }
1079    let summary = lines.join("\n");
1080
1081    let announce_id = format!("{parent_owned}:fanin");
1082    let enqueue = call_blocking(db.clone(), {
1083        let channel = caller_channel.clone();
1084        let summary = summary.clone();
1085        move |db| db.enqueue_subagent_announce(&announce_id, chat_id, &channel, &summary)
1086    })
1087    .await;
1088    // A UNIQUE violation here just means another sibling already enqueued it.
1089    if enqueue.is_ok() {
1090        let _ = flush_pending_announces_once(config, channel_registry, db, 10).await;
1091    }
1092}
1093
1094async fn build_announce_payload(
1095    db: Arc<Database>,
1096    chat_id: i64,
1097    run_id: &str,
1098) -> Result<String, String> {
1099    let run_id_owned = run_id.to_string();
1100    let run = match call_blocking(db.clone(), move |db| {
1101        db.get_subagent_run(&run_id_owned, chat_id)
1102    })
1103    .await
1104    {
1105        Ok(Some(run)) => run,
1106        Ok(None) => return Err("run_not_found".into()),
1107        Err(e) => return Err(format!("failed_loading_run: {e}")),
1108    };
1109
1110    let status_emoji = match run.status.as_str() {
1111        "completed" => "✅",
1112        "cancelled" => "🛑",
1113        "timed_out" => "⏱️",
1114        _ => "❌",
1115    };
1116
1117    let mut text = format!(
1118        "{status_emoji} Subagent `{}` finished\nstatus: {}\ninput_tokens: {}\noutput_tokens: {}\nbudget: {}",
1119        run.run_id, run.status, run.input_tokens, run.output_tokens, run.token_budget
1120    );
1121    if let Some(err) = &run.error_text {
1122        text.push_str(&format!("\nerror: {err}"));
1123    }
1124    if let Some(result) = &run.result_text {
1125        let visible = crate::agent_engine::sanitize_user_visible_text(result);
1126        let clipped: String = visible.chars().take(1200).collect();
1127        text.push_str("\nresult:\n");
1128        text.push_str(&clipped);
1129    }
1130    Ok(text)
1131}
1132
1133pub async fn flush_pending_announces_once(
1134    config: &Config,
1135    channel_registry: Arc<ChannelRegistry>,
1136    db: Arc<Database>,
1137    max_batch: usize,
1138) -> usize {
1139    let now = chrono::Utc::now().to_rfc3339();
1140    let rows = match call_blocking(db.clone(), move |db| {
1141        db.list_due_subagent_announces(&now, max_batch)
1142    })
1143    .await
1144    {
1145        Ok(v) => v,
1146        Err(e) => {
1147            warn!("failed to list due subagent announces: {e}");
1148            return 0;
1149        }
1150    };
1151
1152    let mut processed = 0usize;
1153    for row in rows {
1154        let bot_username = config.bot_username_for_channel(&row.caller_channel);
1155        let delivery = deliver_and_store_bot_message(
1156            channel_registry.as_ref(),
1157            db.clone(),
1158            &bot_username,
1159            row.chat_id,
1160            &row.payload_text,
1161        )
1162        .await;
1163        match delivery {
1164            Ok(_) => {
1165                let id = row.id;
1166                let _ =
1167                    call_blocking(db.clone(), move |db| db.mark_subagent_announce_sent(id)).await;
1168            }
1169            Err(err) => {
1170                let next_attempts = row.attempts + 1;
1171                let terminal = next_attempts >= 5;
1172                let delay_secs = 1_i64 << next_attempts.min(6);
1173                let next_at = if terminal {
1174                    None
1175                } else {
1176                    Some((chrono::Utc::now() + chrono::Duration::seconds(delay_secs)).to_rfc3339())
1177                };
1178                let id = row.id;
1179                let err_text = err;
1180                let _ = call_blocking(db.clone(), move |db| {
1181                    db.mark_subagent_announce_retry(
1182                        id,
1183                        next_attempts,
1184                        next_at.as_deref(),
1185                        &err_text,
1186                        terminal,
1187                    )
1188                })
1189                .await;
1190            }
1191        }
1192        processed += 1;
1193    }
1194    processed
1195}
1196
1197pub struct SessionsSpawnTool {
1198    config: Config,
1199    db: Arc<Database>,
1200    channel_registry: Arc<ChannelRegistry>,
1201    /// Project agents offered as `agent` (trusted workspaces only).
1202    agents: Vec<crate::tools::explore::ProjectAgent>,
1203}
1204
1205impl SessionsSpawnTool {
1206    pub fn new(config: &Config, db: Arc<Database>, channel_registry: Arc<ChannelRegistry>) -> Self {
1207        let agents = config
1208            .project_agents_dir
1209            .as_deref()
1210            .map(|dir| crate::tools::explore::load_project_agents(std::path::Path::new(dir)))
1211            .unwrap_or_default();
1212        Self {
1213            config: config.clone(),
1214            db,
1215            channel_registry,
1216            agents,
1217        }
1218    }
1219}
1220
1221#[async_trait]
1222impl Tool for SessionsSpawnTool {
1223    fn name(&self) -> &str {
1224        "sessions_spawn"
1225    }
1226
1227    fn definition(&self) -> ToolDefinition {
1228        let mut definition = ToolDefinition {
1229            name: "sessions_spawn".into(),
1230            description: format!(
1231                "Spawn an asynchronous sub-agent run for long tasks. Returns immediately with a run id. Use subagents_list/subagents_info/subagents_kill to manage runs. Pick a `specialist` to route the work to a focused expert. Available specialists: {}.",
1232                crate::tools::specialists::specialist_catalog()
1233            ),
1234            input_schema: schema_object(
1235                json!({
1236                    "task": {
1237                        "type": "string",
1238                        "description": "Task for the spawned sub-agent"
1239                    },
1240                    "context": {
1241                        "type": "string",
1242                        "description": "Optional extra context passed to the sub-agent"
1243                    },
1244                    "specialist": {
1245                        "type": "string",
1246                        "enum": crate::tools::specialists::specialist_names(),
1247                        "description": "Which specialist persona the sub-agent adopts. Defaults to generalist."
1248                    },
1249                    "label": {
1250                        "type": "string",
1251                        "description": "Short human-friendly name for this task (e.g. 'competitor research'), shown when listing/reporting progress. Recommended when running several tasks at once."
1252                    },
1253                    "runtime": {
1254                        "type": "string",
1255                        "enum": ["native", "acp"],
1256                        "description": "Execution backend for the sub-agent. Defaults to native."
1257                    },
1258                    "runtime_target": {
1259                        "type": "string",
1260                        "description": "Optional named ACP target when runtime is 'acp'."
1261                    },
1262                    "chat_id": {
1263                        "type": "integer",
1264                        "description": "Target chat id. Defaults to current chat."
1265                    },
1266                    "token_budget": {
1267                        "type": "integer",
1268                        "description": "Optional token budget cap for this run."
1269                    },
1270                    "exit_criteria": {
1271                        "type": "array",
1272                        "maxItems": 8,
1273                        "description": "Optional completion contract: machine-checkable exit criteria the runtime VERIFIES when the run finishes (the result is marked VERIFIED/FAILED with evidence). Entries: {type:'file_exists', path} | {type:'file_contains', path, needle} | {type:'file_min_bytes', path, min_bytes} | {type:'result_contains', needle} | {type:'command', run, expect_contains?}. Paths are relative to the chat working dir; commands run through the sandboxed bash tool. Declare criteria whenever the task has an objectively checkable outcome.",
1274                        "items": {"type": "object"}
1275                    }
1276                }),
1277                &["task"],
1278            ),
1279        };
1280        if !self.agents.is_empty() {
1281            if let Some(properties) = definition
1282                .input_schema
1283                .get_mut("properties")
1284                .and_then(|p| p.as_object_mut())
1285            {
1286                properties.insert(
1287                    "agent".into(),
1288                    json!({
1289                        "type": "string",
1290                        "enum": self.agents.iter().map(|a| a.name.clone()).collect::<Vec<_>>(),
1291                        "description": "Project agent to run as (its own instructions, model and tools) instead of a specialist"
1292                    }),
1293                );
1294            }
1295            let list: Vec<String> = self
1296                .agents
1297                .iter()
1298                .map(|a| {
1299                    if a.description.is_empty() {
1300                        a.name.clone()
1301                    } else {
1302                        format!("{} ({})", a.name, a.description)
1303                    }
1304                })
1305                .collect();
1306            definition.description.push_str(&format!(
1307                " Project agents (pass as `agent`): {}.",
1308                list.join("; ")
1309            ));
1310        }
1311        definition
1312    }
1313
1314    async fn execute(&self, input: serde_json::Value) -> ToolResult {
1315        let auth =
1316            match auth_context_from_input(&input) {
1317                Some(v) => v,
1318                None => return ToolResult::error(
1319                    "sessions_spawn requires caller auth context; run from an active chat session"
1320                        .into(),
1321                ),
1322            };
1323
1324        let chat_id = input
1325            .get("chat_id")
1326            .and_then(|v| v.as_i64())
1327            .unwrap_or(auth.caller_chat_id);
1328        if let Err(e) = authorize_chat_access(&input, chat_id) {
1329            return ToolResult::error(e);
1330        }
1331
1332        let task = match input.get("task").and_then(|v| v.as_str()) {
1333            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
1334            _ => return ToolResult::error("Missing required parameter: task".into()),
1335        };
1336        let context = input
1337            .get("context")
1338            .and_then(|v| v.as_str())
1339            .unwrap_or("")
1340            .trim()
1341            .to_string();
1342        // Resolve the requested specialist (falls back to generalist for unknown/empty).
1343        let specialist = crate::tools::specialists::resolve_specialist(
1344            input.get("specialist").and_then(|v| v.as_str()),
1345        )
1346        .name
1347        .to_string();
1348        let exit_criteria =
1349            match crate::completion_contract::parse_exit_criteria(input.get("exit_criteria")) {
1350                Ok(v) => v,
1351                Err(e) => return ToolResult::error(e),
1352            };
1353        // Optional human-friendly label ("competitor research") for "what am I working on".
1354        let label = input
1355            .get("label")
1356            .and_then(|v| v.as_str())
1357            .map(str::trim)
1358            .filter(|v| !v.is_empty())
1359            .map(|v| v.chars().take(80).collect::<String>());
1360        let parent_meta = subagent_runtime_meta_from_input(&input);
1361        let execution_runtime =
1362            match SubagentExecutionRuntime::from_input(&input, parent_meta.as_ref()) {
1363                Ok(v) => v,
1364                Err(e) => return ToolResult::error(e),
1365            };
1366        let runtime_target = input
1367            .get("runtime_target")
1368            .and_then(|v| v.as_str())
1369            .map(str::trim)
1370            .filter(|v| !v.is_empty())
1371            .map(ToOwned::to_owned)
1372            .or_else(|| {
1373                parent_meta
1374                    .as_ref()
1375                    .and_then(|meta| meta.runtime_target.clone())
1376            });
1377        let parent_depth = parent_meta.as_ref().map(|m| m.depth).unwrap_or(0);
1378        let parent_budget_remaining = parent_meta.as_ref().and_then(|m| m.token_budget_remaining);
1379        let child_depth = if parent_depth > 0 {
1380            parent_depth + 1
1381        } else {
1382            1
1383        };
1384        if child_depth as usize > self.config.subagents.max_spawn_depth {
1385            return ToolResult::error(format!(
1386                "subagent spawn depth exceeded: requested depth {}, max {}",
1387                child_depth, self.config.subagents.max_spawn_depth
1388            ));
1389        }
1390        let parent_run_id = input
1391            .get("__subagent_runtime")
1392            .and_then(|v| v.get("run_id"))
1393            .and_then(|v| v.as_str())
1394            .map(str::to_string);
1395        let requested_budget = input
1396            .get("token_budget")
1397            .and_then(|v| v.as_i64())
1398            .filter(|v| *v > 0);
1399        let child_token_budget = match compute_child_token_budget(
1400            requested_budget,
1401            parent_budget_remaining,
1402            self.config.subagents.max_tokens_per_run,
1403        ) {
1404            Ok(v) => v,
1405            Err(e) => return ToolResult::error(e),
1406        };
1407
1408        let db_for_count = self.db.clone();
1409        let active_count = match call_blocking(db_for_count, move |db| {
1410            db.count_active_subagent_runs_for_chat(chat_id)
1411        })
1412        .await
1413        {
1414            Ok(v) => v,
1415            Err(e) => {
1416                return ToolResult::error(format!("Failed checking active subagent runs: {e}"));
1417            }
1418        };
1419        if active_count as usize >= self.config.subagents.max_active_per_chat {
1420            return ToolResult::error(format!(
1421                "Too many active subagent runs for this chat (limit: {})",
1422                self.config.subagents.max_active_per_chat
1423            ));
1424        }
1425        if let Some(parent_id) = parent_run_id.as_ref() {
1426            let parent_id_for_count = parent_id.clone();
1427            let active_children = match call_blocking(self.db.clone(), move |db| {
1428                db.count_active_subagent_children(&parent_id_for_count)
1429            })
1430            .await
1431            {
1432                Ok(v) => v,
1433                Err(e) => {
1434                    return ToolResult::error(format!(
1435                        "Failed checking active subagent child runs: {e}"
1436                    ));
1437                }
1438            };
1439            if active_children as usize >= self.config.subagents.max_children_per_run {
1440                return ToolResult::error(format!(
1441                    "Too many active child runs for this parent (limit: {})",
1442                    self.config.subagents.max_children_per_run
1443                ));
1444            }
1445        }
1446
1447        let agent = match input.get("agent").and_then(|v| v.as_str()).map(str::trim) {
1448            Some(name) if !name.is_empty() => match self.agents.iter().find(|a| a.name == name) {
1449                Some(agent) => Some(agent.clone()),
1450                None => {
1451                    return ToolResult::error(format!(
1452                        "Unknown project agent `{name}`{}",
1453                        if self.agents.is_empty() {
1454                            String::new()
1455                        } else {
1456                            format!(
1457                                "; available: {}",
1458                                self.agents
1459                                    .iter()
1460                                    .map(|a| a.name.as_str())
1461                                    .collect::<Vec<_>>()
1462                                    .join(", ")
1463                            )
1464                        }
1465                    ))
1466                }
1467            },
1468            _ => None,
1469        };
1470        if agent.is_some() && matches!(execution_runtime, SubagentExecutionRuntime::Acp) {
1471            return ToolResult::error(
1472                "Project agents run on the native runtime; drop `runtime: acp` or `agent`".into(),
1473            );
1474        }
1475        let label = label.or_else(|| agent.as_ref().map(|a| a.name.clone()));
1476
1477        let run_id = format!("subrun-{}", uuid::Uuid::new_v4());
1478        let (provider, model, acp_target) = match execution_runtime {
1479            SubagentExecutionRuntime::Native => (
1480                self.config.llm_provider.clone(),
1481                agent
1482                    .as_ref()
1483                    .and_then(|a| a.model.clone())
1484                    .unwrap_or_else(|| {
1485                        self.config
1486                            .aux_models
1487                            .subagent_model(&self.config.model)
1488                            .to_string()
1489                    }),
1490                None,
1491            ),
1492            SubagentExecutionRuntime::Acp => {
1493                if !self.config.subagents.acp.default_target.enabled {
1494                    return ToolResult::error(
1495                        "ACP runtime is disabled. Set `subagents.acp.enabled: true` and configure `subagents.acp.command` or `subagents.acp.targets` first."
1496                            .into(),
1497                    );
1498                }
1499                let resolved = match self
1500                    .config
1501                    .subagents
1502                    .acp
1503                    .resolve_target(runtime_target.as_deref())
1504                {
1505                    Ok(target) => target,
1506                    Err(err) => return ToolResult::error(err),
1507                };
1508                (
1509                    crate::acp_subagent::acp_runtime_provider(resolved.name.as_deref()),
1510                    crate::acp_subagent::acp_runtime_model(&resolved),
1511                    Some(resolved),
1512                )
1513            }
1514        };
1515
1516        let subagent_model = model.clone();
1517        let run_id_for_insert = run_id.clone();
1518        let task_for_insert = task.clone();
1519        let context_for_insert = context.clone();
1520        let caller_channel_for_insert = auth.caller_channel.clone();
1521        let parent_for_insert = parent_run_id.clone();
1522        let label_for_insert = label.clone();
1523        if let Err(e) = call_blocking(self.db.clone(), move |db| {
1524            db.create_subagent_run(CreateSubagentRunParams {
1525                run_id: &run_id_for_insert,
1526                parent_run_id: parent_for_insert.as_deref(),
1527                depth: child_depth,
1528                token_budget: child_token_budget,
1529                chat_id,
1530                caller_channel: &caller_channel_for_insert,
1531                task: &task_for_insert,
1532                context: &context_for_insert,
1533                provider: &provider,
1534                model: &model,
1535                label: label_for_insert.as_deref(),
1536            })
1537        })
1538        .await
1539        {
1540            return ToolResult::error(format!("Failed creating subagent run: {e}"));
1541        }
1542        log_subagent_event(
1543            self.db.clone(),
1544            &run_id,
1545            "accepted",
1546            Some(format!(
1547                "depth={child_depth} runtime={} specialist={specialist}{}",
1548                execution_runtime.as_str(),
1549                runtime_target
1550                    .as_deref()
1551                    .map(|target| format!(" runtime_target={target}"))
1552                    .unwrap_or_default()
1553            )),
1554        )
1555        .await;
1556
1557        let runtime = subagent_runtime(&self.config);
1558        let local_cancel = runtime.register_run(&run_id);
1559        let db = self.db.clone();
1560        let mut cfg = self.config.clone();
1561        if matches!(execution_runtime, SubagentExecutionRuntime::Native) {
1562            // The sub-agent's provider uses `cfg.model` as its model.
1563            cfg.model = subagent_model;
1564        }
1565        let agent_async = agent.clone();
1566        let run_id_async = run_id.clone();
1567        let task_async = task.clone();
1568        let context_async = context.clone();
1569        let specialist_async = specialist.clone();
1570        let exit_criteria_async = exit_criteria.clone();
1571        let parent_run_id_async = parent_run_id.clone();
1572        let auth_async = ToolAuthContext {
1573            caller_channel: auth.caller_channel.clone(),
1574            caller_chat_id: chat_id,
1575            principal: format!("subagent:{run_id}"),
1576            control_chat_ids: auth.control_chat_ids.clone(),
1577            env_files: auth.env_files.clone(),
1578        };
1579        let channel_registry = self.channel_registry.clone();
1580        let subagent_channel_registry = self.channel_registry.clone();
1581        let fan_in_channel_registry = self.channel_registry.clone();
1582        let caller_channel_for_event = auth.caller_channel.clone();
1583        TASK_RUNTIME.spawn(async move {
1584            let run_id_for_finish = run_id_async.clone();
1585            let _ = call_blocking(db.clone(), {
1586                let run_id = run_id_async.clone();
1587                move |db| db.mark_subagent_queued(&run_id)
1588            })
1589            .await;
1590            log_subagent_event(db.clone(), &run_id_async, "queued", None).await;
1591
1592            let _permit = match runtime.semaphore.acquire().await {
1593                Ok(p) => p,
1594                Err(_) => {
1595                    let _ = call_blocking(db.clone(), move |db| {
1596                        db.mark_subagent_finished(FinishSubagentRunParams {
1597                            run_id: &run_id_for_finish,
1598                            status: "failed",
1599                            error_text: Some("subagent runtime is shutting down"),
1600                            result_text: None,
1601                            artifact_json: None,
1602                            input_tokens: 0,
1603                            output_tokens: 0,
1604                        })
1605                    })
1606                    .await;
1607                    runtime.remove_run(&run_id_async);
1608                    return;
1609                }
1610            };
1611
1612            let _ = call_blocking(db.clone(), {
1613                let run_id = run_id_async.clone();
1614                move |db| db.mark_subagent_running(&run_id)
1615            })
1616            .await;
1617            log_subagent_event(db.clone(), &run_id_async, "running", None).await;
1618
1619            let timeout_secs = cfg.subagents.run_timeout_secs;
1620            let run_future = run_sub_agent_task(RunSubAgentTaskParams {
1621                config: cfg.clone(),
1622                db: db.clone(),
1623                channel_registry: subagent_channel_registry,
1624                auth_context: auth_async,
1625                run_id: run_id_async.clone(),
1626                runtime: execution_runtime,
1627                acp_target,
1628                depth: child_depth,
1629                run_token_budget: child_token_budget,
1630                task: task_async,
1631                context: context_async,
1632                specialist: specialist_async,
1633                agent: agent_async,
1634                exit_criteria: exit_criteria_async,
1635                local_cancel,
1636            });
1637
1638            let final_outcome = if timeout_secs > 0 {
1639                match tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), run_future)
1640                    .await
1641                {
1642                    Ok(result) => result,
1643                    Err(_) => Err("timed_out".to_string()),
1644                }
1645            } else {
1646                run_future.await
1647            };
1648
1649            let finish_status = match &final_outcome {
1650                Ok(_) => "completed",
1651                Err(err) if err == "cancelled" => "cancelled",
1652                Err(err) if err == "timed_out" => "timed_out",
1653                Err(err) if err.contains("budget_exceeded:") => "budget_exceeded",
1654                Err(_) => "failed",
1655            };
1656            // Surface completion into the parent turn's heartbeat if it is
1657            // still running (no-op otherwise).
1658            crate::agent_engine::send_turn_event(
1659                &auth.caller_channel,
1660                chat_id,
1661                crate::agent_engine::AgentEvent::SubagentFinished {
1662                    run_id: run_id_async.clone(),
1663                    status: finish_status.to_string(),
1664                },
1665            );
1666
1667            match final_outcome {
1668                Ok((result, artifact_json, input_tokens, output_tokens)) => {
1669                    let rid = run_id_for_finish.clone();
1670                    let _ = call_blocking(db.clone(), move |db| {
1671                        db.mark_subagent_finished(FinishSubagentRunParams {
1672                            run_id: &rid,
1673                            status: "completed",
1674                            error_text: None,
1675                            result_text: Some(&result),
1676                            artifact_json: Some(&artifact_json),
1677                            input_tokens,
1678                            output_tokens,
1679                        })
1680                    })
1681                    .await;
1682                    log_subagent_event(db.clone(), &run_id_for_finish, "completed", None).await;
1683                }
1684                Err(err) if err == "cancelled" => {
1685                    let rid = run_id_for_finish.clone();
1686                    let _ = call_blocking(db.clone(), move |db| {
1687                        db.mark_subagent_finished(FinishSubagentRunParams {
1688                            run_id: &rid,
1689                            status: "cancelled",
1690                            error_text: Some("Cancelled by user"),
1691                            result_text: None,
1692                            artifact_json: None,
1693                            input_tokens: 0,
1694                            output_tokens: 0,
1695                        })
1696                    })
1697                    .await;
1698                    log_subagent_event(db.clone(), &run_id_for_finish, "cancelled", None).await;
1699                }
1700                Err(err) if err == "timed_out" => {
1701                    let rid = run_id_for_finish.clone();
1702                    let _ = call_blocking(db.clone(), move |db| {
1703                        db.mark_subagent_finished(FinishSubagentRunParams {
1704                            run_id: &rid,
1705                            status: "timed_out",
1706                            error_text: Some("Sub-agent run exceeded configured timeout"),
1707                            result_text: None,
1708                            artifact_json: None,
1709                            input_tokens: 0,
1710                            output_tokens: 0,
1711                        })
1712                    })
1713                    .await;
1714                    log_subagent_event(db.clone(), &run_id_for_finish, "timed_out", None).await;
1715                }
1716                Err(err) => {
1717                    let rid = run_id_for_finish.clone();
1718                    let err_for_db = err.clone();
1719                    let status = if err_for_db.contains("budget_exceeded:") {
1720                        "budget_exceeded"
1721                    } else {
1722                        "failed"
1723                    };
1724                    let _ = call_blocking(db.clone(), move |db| {
1725                        db.mark_subagent_finished(FinishSubagentRunParams {
1726                            run_id: &rid,
1727                            status,
1728                            error_text: Some(&err_for_db),
1729                            result_text: None,
1730                            artifact_json: None,
1731                            input_tokens: 0,
1732                            output_tokens: 0,
1733                        })
1734                    })
1735                    .await;
1736                    log_subagent_event(db.clone(), &run_id_for_finish, "failed", Some(err)).await;
1737                }
1738            }
1739
1740            runtime.remove_run(&run_id_async);
1741
1742            let user_chat_announces_enabled = cfg.subagents.announce_to_chat
1743                && auth.caller_channel != "weixin"
1744                && !auth.caller_channel.starts_with("weixin.");
1745            if user_chat_announces_enabled {
1746                match build_announce_payload(db.clone(), chat_id, &run_id_async).await {
1747                    Ok(payload) => {
1748                        let rid = run_id_async.clone();
1749                        let caller_channel = auth.caller_channel.clone();
1750                        let _ = call_blocking(db.clone(), move |db| {
1751                            db.enqueue_subagent_announce(&rid, chat_id, &caller_channel, &payload)
1752                        })
1753                        .await;
1754                        let _ =
1755                            flush_pending_announces_once(&cfg, channel_registry, db.clone(), 10)
1756                                .await;
1757                    }
1758                    Err(e) => {
1759                        warn!("failed to build announce payload for run {run_id_async}: {e}");
1760                    }
1761                }
1762            }
1763
1764            // Fan-in: when this was the last active child of a parent run, post one
1765            // consolidated summary of the whole batch (opt-in).
1766            if user_chat_announces_enabled && cfg.subagents.fan_in_summary {
1767                if let Some(parent_id) = parent_run_id_async.as_ref() {
1768                    maybe_post_fan_in_summary(
1769                        &cfg,
1770                        fan_in_channel_registry,
1771                        db,
1772                        chat_id,
1773                        parent_id,
1774                    )
1775                    .await;
1776                }
1777            }
1778        });
1779
1780        info!("subagent accepted run_id={run_id} chat_id={chat_id}");
1781        crate::agent_engine::send_turn_event(
1782            &caller_channel_for_event,
1783            chat_id,
1784            crate::agent_engine::AgentEvent::SubagentStarted {
1785                run_id: run_id.clone(),
1786                label: label.clone().unwrap_or_else(|| specialist.clone()),
1787            },
1788        );
1789        ToolResult::success(
1790            json!({
1791                "status": "accepted",
1792                "run_id": run_id,
1793                "chat_id": chat_id,
1794                "depth": child_depth,
1795                "specialist": specialist,
1796                "label": label,
1797                "runtime": execution_runtime.as_str(),
1798                "runtime_target": runtime_target,
1799                "token_budget": child_token_budget,
1800                "parent_run_id": parent_run_id,
1801            })
1802            .to_string(),
1803        )
1804    }
1805}
1806
1807pub struct SubagentsListTool {
1808    db: Arc<Database>,
1809}
1810
1811impl SubagentsListTool {
1812    pub fn new(db: Arc<Database>) -> Self {
1813        Self { db }
1814    }
1815}
1816
1817#[async_trait]
1818impl Tool for SubagentsListTool {
1819    fn name(&self) -> &str {
1820        "subagents_list"
1821    }
1822
1823    fn definition(&self) -> ToolDefinition {
1824        ToolDefinition {
1825            name: "subagents_list".into(),
1826            description: "List recent subagent runs for the current chat.".into(),
1827            input_schema: schema_object(
1828                json!({
1829                    "chat_id": {"type": "integer"},
1830                    "limit": {"type": "integer", "minimum": 1, "maximum": 100}
1831                }),
1832                &[],
1833            ),
1834        }
1835    }
1836
1837    async fn execute(&self, input: serde_json::Value) -> ToolResult {
1838        let auth =
1839            match auth_context_from_input(&input) {
1840                Some(v) => v,
1841                None => return ToolResult::error(
1842                    "subagents_list requires caller auth context; run from an active chat session"
1843                        .into(),
1844                ),
1845            };
1846        let chat_id = input
1847            .get("chat_id")
1848            .and_then(|v| v.as_i64())
1849            .unwrap_or(auth.caller_chat_id);
1850        if let Err(e) = authorize_chat_access(&input, chat_id) {
1851            return ToolResult::error(e);
1852        }
1853        let limit = input
1854            .get("limit")
1855            .and_then(|v| v.as_u64())
1856            .unwrap_or(20)
1857            .clamp(1, 100) as usize;
1858
1859        let rows = match call_blocking(self.db.clone(), move |db| {
1860            db.list_subagent_runs(chat_id, limit)
1861        })
1862        .await
1863        {
1864            Ok(v) => v,
1865            Err(e) => return ToolResult::error(format!("Failed listing subagent runs: {e}")),
1866        };
1867        let payload: Vec<serde_json::Value> = rows
1868            .into_iter()
1869            .map(|r| {
1870                json!({
1871                    "run_id": r.run_id,
1872                    "label": r.label,
1873                    "parent_run_id": r.parent_run_id,
1874                    "depth": r.depth,
1875                    "token_budget": r.token_budget,
1876                    "status": r.status,
1877                    "created_at": r.created_at,
1878                    "started_at": r.started_at,
1879                    "finished_at": r.finished_at,
1880                    "cancel_requested": r.cancel_requested,
1881                    "task": r.task,
1882                    "progress": r.progress_text,
1883                    "last_progress_at": r.last_progress_at,
1884                    "input_tokens": r.input_tokens,
1885                    "output_tokens": r.output_tokens,
1886                    "artifact_json": r.artifact_json,
1887                })
1888            })
1889            .collect();
1890
1891        ToolResult::success(json!({"chat_id": chat_id, "runs": payload}).to_string())
1892    }
1893}
1894
1895/// Resolve a run reference (exact run_id or human-friendly label) to a run_id
1896/// within the given chat. Shared by subagents_info / subagents_kill.
1897async fn resolve_subagent_ref(
1898    db: &Arc<Database>,
1899    chat_id: i64,
1900    run_ref: &str,
1901) -> Result<Option<String>, String> {
1902    let run_ref_owned = run_ref.to_string();
1903    call_blocking(db.clone(), move |db| {
1904        db.resolve_subagent_run_id(chat_id, &run_ref_owned)
1905    })
1906    .await
1907    .map_err(|e| format!("Failed resolving subagent reference: {e}"))
1908}
1909
1910pub struct SubagentsInfoTool {
1911    db: Arc<Database>,
1912}
1913
1914impl SubagentsInfoTool {
1915    pub fn new(db: Arc<Database>) -> Self {
1916        Self { db }
1917    }
1918}
1919
1920#[async_trait]
1921impl Tool for SubagentsInfoTool {
1922    fn name(&self) -> &str {
1923        "subagents_info"
1924    }
1925
1926    fn definition(&self) -> ToolDefinition {
1927        ToolDefinition {
1928            name: "subagents_info".into(),
1929            description: "Get detailed information for one subagent run, by run id or task label."
1930                .into(),
1931            input_schema: schema_object(
1932                json!({
1933                    "run_id": {"type": "string", "description": "Run id or the task label given at spawn."},
1934                    "chat_id": {"type": "integer"}
1935                }),
1936                &["run_id"],
1937            ),
1938        }
1939    }
1940
1941    async fn execute(&self, input: serde_json::Value) -> ToolResult {
1942        let auth =
1943            match auth_context_from_input(&input) {
1944                Some(v) => v,
1945                None => return ToolResult::error(
1946                    "subagents_info requires caller auth context; run from an active chat session"
1947                        .into(),
1948                ),
1949            };
1950        let chat_id = input
1951            .get("chat_id")
1952            .and_then(|v| v.as_i64())
1953            .unwrap_or(auth.caller_chat_id);
1954        if let Err(e) = authorize_chat_access(&input, chat_id) {
1955            return ToolResult::error(e);
1956        }
1957        let run_ref = match input.get("run_id").and_then(|v| v.as_str()) {
1958            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
1959            _ => return ToolResult::error("Missing required parameter: run_id".into()),
1960        };
1961        let run_id = match resolve_subagent_ref(&self.db, chat_id, &run_ref).await {
1962            Ok(Some(v)) => v,
1963            Ok(None) => return ToolResult::error(format!("No subagent run matching '{run_ref}'")),
1964            Err(e) => return ToolResult::error(e),
1965        };
1966
1967        let run = match call_blocking(self.db.clone(), move |db| {
1968            db.get_subagent_run(&run_id, chat_id)
1969        })
1970        .await
1971        {
1972            Ok(Some(v)) => v,
1973            Ok(None) => return ToolResult::error("Subagent run not found".into()),
1974            Err(e) => return ToolResult::error(format!("Failed reading subagent run: {e}")),
1975        };
1976
1977        ToolResult::success(
1978            json!({
1979                "run_id": run.run_id,
1980                "label": run.label,
1981                "parent_run_id": run.parent_run_id,
1982                "depth": run.depth,
1983                "chat_id": run.chat_id,
1984                "caller_channel": run.caller_channel,
1985                "task": run.task,
1986                "context": run.context,
1987                "status": run.status,
1988                "created_at": run.created_at,
1989                "started_at": run.started_at,
1990                "finished_at": run.finished_at,
1991                "cancel_requested": run.cancel_requested,
1992                "progress": run.progress_text,
1993                "last_progress_at": run.last_progress_at,
1994                "error_text": run.error_text,
1995                "result_text": run.result_text,
1996                "input_tokens": run.input_tokens,
1997                "output_tokens": run.output_tokens,
1998                "total_tokens": run.total_tokens,
1999                "provider": run.provider,
2000                "model": run.model,
2001                "token_budget": run.token_budget,
2002                "artifact_json": run.artifact_json,
2003            })
2004            .to_string(),
2005        )
2006    }
2007}
2008
2009pub struct SubagentsKillTool {
2010    config: Config,
2011    db: Arc<Database>,
2012}
2013
2014impl SubagentsKillTool {
2015    pub fn new(config: &Config, db: Arc<Database>) -> Self {
2016        Self {
2017            config: config.clone(),
2018            db,
2019        }
2020    }
2021}
2022
2023#[async_trait]
2024impl Tool for SubagentsKillTool {
2025    fn name(&self) -> &str {
2026        "subagents_kill"
2027    }
2028
2029    fn definition(&self) -> ToolDefinition {
2030        ToolDefinition {
2031            name: "subagents_kill".into(),
2032            description: "Request cancellation for one running subagent run (by run id or task label), or all active runs in current chat with run_id=all.".into(),
2033            input_schema: schema_object(
2034                json!({
2035                    "run_id": {"type": "string", "description": "Run id, task label, or 'all'"},
2036                    "chat_id": {"type": "integer"}
2037                }),
2038                &["run_id"],
2039            ),
2040        }
2041    }
2042
2043    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2044        let auth =
2045            match auth_context_from_input(&input) {
2046                Some(v) => v,
2047                None => return ToolResult::error(
2048                    "subagents_kill requires caller auth context; run from an active chat session"
2049                        .into(),
2050                ),
2051            };
2052        let chat_id = input
2053            .get("chat_id")
2054            .and_then(|v| v.as_i64())
2055            .unwrap_or(auth.caller_chat_id);
2056        if let Err(e) = authorize_chat_access(&input, chat_id) {
2057            return ToolResult::error(e);
2058        }
2059        let run_ref = match input.get("run_id").and_then(|v| v.as_str()) {
2060            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2061            _ => return ToolResult::error("Missing required parameter: run_id".into()),
2062        };
2063
2064        let runtime = subagent_runtime(&self.config);
2065
2066        if run_ref.eq_ignore_ascii_case("all") {
2067            let rows = match call_blocking(self.db.clone(), move |db| {
2068                db.list_subagent_runs(chat_id, 200)
2069            })
2070            .await
2071            {
2072                Ok(v) => v,
2073                Err(e) => return ToolResult::error(format!("Failed listing subagent runs: {e}")),
2074            };
2075            let mut cancelled = 0usize;
2076            for row in rows {
2077                if matches!(row.status.as_str(), "accepted" | "queued" | "running") {
2078                    let rid = row.run_id.clone();
2079                    let requested = call_blocking(self.db.clone(), move |db| {
2080                        db.request_subagent_cancel(&rid, chat_id)
2081                    })
2082                    .await
2083                    .unwrap_or(false);
2084                    if requested {
2085                        runtime.cancel_run(&row.run_id);
2086                        log_subagent_event(
2087                            self.db.clone(),
2088                            &row.run_id,
2089                            "cancel_requested",
2090                            Some("kill_all".to_string()),
2091                        )
2092                        .await;
2093                        cancelled += 1;
2094                    }
2095                }
2096            }
2097            return ToolResult::success(
2098                json!({"status": "ok", "cancelled": cancelled, "chat_id": chat_id}).to_string(),
2099            );
2100        }
2101
2102        let run_id = match resolve_subagent_ref(&self.db, chat_id, &run_ref).await {
2103            Ok(Some(v)) => v,
2104            Ok(None) => return ToolResult::error(format!("No subagent run matching '{run_ref}'")),
2105            Err(e) => return ToolResult::error(e),
2106        };
2107
2108        let run_id_for_db = run_id.clone();
2109        let requested = match call_blocking(self.db.clone(), move |db| {
2110            db.request_subagent_cancel(&run_id_for_db, chat_id)
2111        })
2112        .await
2113        {
2114            Ok(v) => v,
2115            Err(e) => {
2116                return ToolResult::error(format!("Failed requesting cancellation: {e}"));
2117            }
2118        };
2119
2120        if !requested {
2121            return ToolResult::error("Subagent run not found or already finished".into());
2122        }
2123        runtime.cancel_run(&run_id);
2124        log_subagent_event(
2125            self.db.clone(),
2126            &run_id,
2127            "cancel_requested",
2128            Some("kill_one".to_string()),
2129        )
2130        .await;
2131        ToolResult::success(json!({"status": "ok", "run_id": run_id}).to_string())
2132    }
2133}
2134
2135pub struct SubagentsRetryAnnouncesTool {
2136    config: Config,
2137    db: Arc<Database>,
2138    channel_registry: Arc<ChannelRegistry>,
2139}
2140
2141pub struct SubagentsFocusTool {
2142    db: Arc<Database>,
2143}
2144
2145impl SubagentsFocusTool {
2146    pub fn new(db: Arc<Database>) -> Self {
2147        Self { db }
2148    }
2149}
2150
2151#[async_trait]
2152impl Tool for SubagentsFocusTool {
2153    fn name(&self) -> &str {
2154        "subagents_focus"
2155    }
2156
2157    fn definition(&self) -> ToolDefinition {
2158        ToolDefinition {
2159            name: "subagents_focus".into(),
2160            description: "Bind the current chat to a subagent run for follow-up actions.".into(),
2161            input_schema: schema_object(
2162                json!({
2163                    "run_id": {"type":"string"},
2164                    "chat_id": {"type":"integer"}
2165                }),
2166                &["run_id"],
2167            ),
2168        }
2169    }
2170
2171    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2172        let auth = match auth_context_from_input(&input) {
2173            Some(v) => v,
2174            None => {
2175                return ToolResult::error("subagents_focus requires caller auth context".into())
2176            }
2177        };
2178        let chat_id = input
2179            .get("chat_id")
2180            .and_then(|v| v.as_i64())
2181            .unwrap_or(auth.caller_chat_id);
2182        if let Err(e) = authorize_chat_access(&input, chat_id) {
2183            return ToolResult::error(e);
2184        }
2185        let run_id = match input.get("run_id").and_then(|v| v.as_str()) {
2186            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2187            _ => return ToolResult::error("Missing required parameter: run_id".into()),
2188        };
2189        let run_id_for_check = run_id.clone();
2190        let exists = match call_blocking(self.db.clone(), move |db| {
2191            db.get_subagent_run(&run_id_for_check, chat_id)
2192        })
2193        .await
2194        {
2195            Ok(v) => v.is_some(),
2196            Err(e) => return ToolResult::error(format!("Failed reading subagent run: {e}")),
2197        };
2198        if !exists {
2199            return ToolResult::error("Subagent run not found".into());
2200        }
2201        let run_id_for_set = run_id.clone();
2202        if let Err(e) = call_blocking(self.db.clone(), move |db| {
2203            db.set_subagent_focus(chat_id, &run_id_for_set)
2204        })
2205        .await
2206        {
2207            return ToolResult::error(format!("Failed setting subagent focus: {e}"));
2208        }
2209        ToolResult::success(json!({"status":"ok","chat_id":chat_id,"run_id":run_id}).to_string())
2210    }
2211}
2212
2213pub struct SubagentsUnfocusTool {
2214    db: Arc<Database>,
2215}
2216
2217impl SubagentsUnfocusTool {
2218    pub fn new(db: Arc<Database>) -> Self {
2219        Self { db }
2220    }
2221}
2222
2223#[async_trait]
2224impl Tool for SubagentsUnfocusTool {
2225    fn name(&self) -> &str {
2226        "subagents_unfocus"
2227    }
2228
2229    fn definition(&self) -> ToolDefinition {
2230        ToolDefinition {
2231            name: "subagents_unfocus".into(),
2232            description: "Clear focused subagent binding for the current chat.".into(),
2233            input_schema: schema_object(
2234                json!({
2235                    "chat_id": {"type":"integer"}
2236                }),
2237                &[],
2238            ),
2239        }
2240    }
2241
2242    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2243        let auth = match auth_context_from_input(&input) {
2244            Some(v) => v,
2245            None => {
2246                return ToolResult::error("subagents_unfocus requires caller auth context".into())
2247            }
2248        };
2249        let chat_id = input
2250            .get("chat_id")
2251            .and_then(|v| v.as_i64())
2252            .unwrap_or(auth.caller_chat_id);
2253        if let Err(e) = authorize_chat_access(&input, chat_id) {
2254            return ToolResult::error(e);
2255        }
2256        if let Err(e) =
2257            call_blocking(self.db.clone(), move |db| db.clear_subagent_focus(chat_id)).await
2258        {
2259            return ToolResult::error(format!("Failed clearing subagent focus: {e}"));
2260        }
2261        ToolResult::success(json!({"status":"ok","chat_id":chat_id}).to_string())
2262    }
2263}
2264
2265pub struct SubagentsFocusedTool {
2266    db: Arc<Database>,
2267}
2268
2269impl SubagentsFocusedTool {
2270    pub fn new(db: Arc<Database>) -> Self {
2271        Self { db }
2272    }
2273}
2274
2275#[async_trait]
2276impl Tool for SubagentsFocusedTool {
2277    fn name(&self) -> &str {
2278        "subagents_focused"
2279    }
2280
2281    fn definition(&self) -> ToolDefinition {
2282        ToolDefinition {
2283            name: "subagents_focused".into(),
2284            description: "Show focused subagent binding for current chat.".into(),
2285            input_schema: schema_object(
2286                json!({
2287                    "chat_id": {"type":"integer"}
2288                }),
2289                &[],
2290            ),
2291        }
2292    }
2293
2294    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2295        let auth = match auth_context_from_input(&input) {
2296            Some(v) => v,
2297            None => {
2298                return ToolResult::error("subagents_focused requires caller auth context".into())
2299            }
2300        };
2301        let chat_id = input
2302            .get("chat_id")
2303            .and_then(|v| v.as_i64())
2304            .unwrap_or(auth.caller_chat_id);
2305        if let Err(e) = authorize_chat_access(&input, chat_id) {
2306            return ToolResult::error(e);
2307        }
2308        let focused =
2309            match call_blocking(self.db.clone(), move |db| db.get_subagent_focus(chat_id)).await {
2310                Ok(v) => v,
2311                Err(e) => return ToolResult::error(format!("Failed loading subagent focus: {e}")),
2312            };
2313        ToolResult::success(json!({"chat_id":chat_id,"run_id":focused}).to_string())
2314    }
2315}
2316
2317pub struct SubagentsSendTool {
2318    config: Config,
2319    db: Arc<Database>,
2320    channel_registry: Arc<ChannelRegistry>,
2321}
2322
2323impl SubagentsSendTool {
2324    pub fn new(config: &Config, db: Arc<Database>, channel_registry: Arc<ChannelRegistry>) -> Self {
2325        Self {
2326            config: config.clone(),
2327            db,
2328            channel_registry,
2329        }
2330    }
2331}
2332
2333#[async_trait]
2334impl Tool for SubagentsSendTool {
2335    fn name(&self) -> &str {
2336        "subagents_send"
2337    }
2338
2339    fn definition(&self) -> ToolDefinition {
2340        ToolDefinition {
2341            name: "subagents_send".into(),
2342            description:
2343                "Send follow-up work to focused subagent by spawning a child continuation run."
2344                    .into(),
2345            input_schema: schema_object(
2346                json!({
2347                    "message": {"type":"string"},
2348                    "chat_id": {"type":"integer"}
2349                }),
2350                &["message"],
2351            ),
2352        }
2353    }
2354
2355    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2356        let auth = match auth_context_from_input(&input) {
2357            Some(v) => v,
2358            None => return ToolResult::error("subagents_send requires caller auth context".into()),
2359        };
2360        let chat_id = input
2361            .get("chat_id")
2362            .and_then(|v| v.as_i64())
2363            .unwrap_or(auth.caller_chat_id);
2364        if let Err(e) = authorize_chat_access(&input, chat_id) {
2365            return ToolResult::error(e);
2366        }
2367        let message = match input.get("message").and_then(|v| v.as_str()) {
2368            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2369            _ => return ToolResult::error("Missing required parameter: message".into()),
2370        };
2371        let focused_run =
2372            match call_blocking(self.db.clone(), move |db| db.get_subagent_focus(chat_id)).await {
2373                Ok(Some(v)) => v,
2374                Ok(None) => return ToolResult::error("No focused subagent for this chat".into()),
2375                Err(e) => return ToolResult::error(format!("Failed loading subagent focus: {e}")),
2376            };
2377        let focused_run_for_load = focused_run.clone();
2378        let parent = match call_blocking(self.db.clone(), move |db| {
2379            db.get_subagent_run(&focused_run_for_load, chat_id)
2380        })
2381        .await
2382        {
2383            Ok(Some(v)) => v,
2384            Ok(None) => return ToolResult::error("Focused subagent run not found".into()),
2385            Err(e) => return ToolResult::error(format!("Failed loading focused subagent: {e}")),
2386        };
2387
2388        let spawn_tool =
2389            SessionsSpawnTool::new(&self.config, self.db.clone(), self.channel_registry.clone());
2390        let remaining_budget = (parent.token_budget - parent.total_tokens).max(0);
2391        let parent_runtime = if parent.provider.starts_with("acp") {
2392            "acp"
2393        } else {
2394            "native"
2395        };
2396        let spawn_input = json!({
2397            "task": format!("Continuation request: {message}"),
2398            "context": format!("This is a follow-up sent to focused run {}. Continue the work based on prior run context and produce actionable output.", focused_run),
2399            "__microclaw_auth": {
2400                "caller_channel": auth.caller_channel,
2401                "caller_chat_id": chat_id,
2402                "control_chat_ids": auth.control_chat_ids,
2403                "env_files": auth.env_files,
2404            },
2405            "__subagent_runtime": {
2406                "run_id": parent.run_id,
2407                "depth": parent.depth,
2408                "runtime": parent_runtime,
2409                "runtime_target": crate::acp_subagent::acp_runtime_target_from_provider(&parent.provider),
2410                "token_budget_remaining": remaining_budget,
2411            }
2412        });
2413        spawn_tool.execute(spawn_input).await
2414    }
2415}
2416
2417pub struct SubagentsLogTool {
2418    db: Arc<Database>,
2419}
2420
2421/// One orchestrate work package: a task plus its optional completion contract.
2422struct OrchestratePackage {
2423    task: String,
2424    exit_criteria: Vec<crate::completion_contract::ExitCriterion>,
2425}
2426
2427/// Marker prefix a failed contract leaves at the head of result_text
2428/// (produced by completion_contract::render_report).
2429const CONTRACT_FAILED_MARKER: &str = "[completion contract] FAILED";
2430
2431pub struct SubagentsOrchestrateTool {
2432    config: Config,
2433    db: Arc<Database>,
2434    channel_registry: Arc<ChannelRegistry>,
2435}
2436
2437impl SubagentsOrchestrateTool {
2438    pub fn new(config: &Config, db: Arc<Database>, channel_registry: Arc<ChannelRegistry>) -> Self {
2439        Self {
2440            config: config.clone(),
2441            db,
2442            channel_registry,
2443        }
2444    }
2445
2446    fn merge_run_artifacts(
2447        runs: &[crate::internal::storage::db::SubagentRunRecord],
2448    ) -> serde_json::Value {
2449        let mut summaries = Vec::new();
2450        let mut findings = BTreeSet::new();
2451        let mut next_actions = BTreeSet::new();
2452        let mut artifacts = Vec::new();
2453        for run in runs {
2454            let Some(raw) = run.artifact_json.as_deref() else {
2455                continue;
2456            };
2457            let Ok(v) = serde_json::from_str::<serde_json::Value>(raw) else {
2458                continue;
2459            };
2460            if let Some(s) = v.get("summary").and_then(|x| x.as_str()) {
2461                if !s.trim().is_empty() {
2462                    summaries.push(s.trim().to_string());
2463                }
2464            }
2465            if let Some(arr) = v.get("findings").and_then(|x| x.as_array()) {
2466                for f in arr.iter().filter_map(|x| x.as_str()) {
2467                    if !f.trim().is_empty() {
2468                        findings.insert(f.trim().to_string());
2469                    }
2470                }
2471            }
2472            if let Some(arr) = v.get("next_actions").and_then(|x| x.as_array()) {
2473                for n in arr.iter().filter_map(|x| x.as_str()) {
2474                    if !n.trim().is_empty() {
2475                        next_actions.insert(n.trim().to_string());
2476                    }
2477                }
2478            }
2479            if let Some(arr) = v.get("artifacts").and_then(|x| x.as_array()) {
2480                artifacts.extend(arr.iter().cloned());
2481            }
2482        }
2483        json!({
2484            "protocol": "orchestrate_merge_v1",
2485            "summary": summaries,
2486            "findings": findings.into_iter().collect::<Vec<_>>(),
2487            "next_actions": next_actions.into_iter().collect::<Vec<_>>(),
2488            "artifacts": artifacts,
2489        })
2490    }
2491}
2492
2493#[async_trait]
2494impl Tool for SubagentsOrchestrateTool {
2495    fn name(&self) -> &str {
2496        "subagents_orchestrate"
2497    }
2498
2499    fn definition(&self) -> ToolDefinition {
2500        ToolDefinition {
2501            name: "subagents_orchestrate".into(),
2502            description: "Depth=2 orchestration template: spawn multiple worker runs and optionally wait+merge structured artifacts.".into(),
2503            input_schema: schema_object(
2504                json!({
2505                    "goal": {"type":"string"},
2506                    "work_packages": {"type":"array", "items":{}, "description":"Work packages: plain strings, or objects {task, exit_criteria?} where exit_criteria is a completion contract (same shape as sessions_spawn) verified when the worker finishes. With wait=true, a worker whose contract FAILED is re-spawned once with the failure evidence (contract-aware fan-in retry)."},
2507                    "chat_id": {"type":"integer"},
2508                    "wait": {"type":"boolean"},
2509                    "wait_timeout_secs": {"type":"integer", "minimum":1, "maximum":1200},
2510                    "token_budget_total": {"type":"integer", "minimum":2000}
2511                }),
2512                &["goal", "work_packages"],
2513            ),
2514        }
2515    }
2516
2517    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2518        let auth = match auth_context_from_input(&input) {
2519            Some(v) => v,
2520            None => {
2521                return ToolResult::error(
2522                    "subagents_orchestrate requires caller auth context".into(),
2523                )
2524            }
2525        };
2526        let chat_id = input
2527            .get("chat_id")
2528            .and_then(|v| v.as_i64())
2529            .unwrap_or(auth.caller_chat_id);
2530        if let Err(e) = authorize_chat_access(&input, chat_id) {
2531            return ToolResult::error(e);
2532        }
2533        let goal = match input.get("goal").and_then(|v| v.as_str()) {
2534            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2535            _ => return ToolResult::error("Missing required parameter: goal".into()),
2536        };
2537        let raw_packages = input
2538            .get("work_packages")
2539            .and_then(|v| v.as_array())
2540            .cloned()
2541            .unwrap_or_default();
2542        let mut packages: Vec<OrchestratePackage> = Vec::new();
2543        for (i, v) in raw_packages.iter().enumerate() {
2544            if let Some(task) = v.as_str() {
2545                if !task.trim().is_empty() {
2546                    packages.push(OrchestratePackage {
2547                        task: task.trim().to_string(),
2548                        exit_criteria: Vec::new(),
2549                    });
2550                }
2551                continue;
2552            }
2553            if v.is_object() {
2554                let task = v
2555                    .get("task")
2556                    .and_then(|t| t.as_str())
2557                    .map(str::trim)
2558                    .unwrap_or_default()
2559                    .to_string();
2560                if task.is_empty() {
2561                    return ToolResult::error(format!(
2562                        "work_packages[{i}] object is missing a non-empty `task`"
2563                    ));
2564                }
2565                let exit_criteria =
2566                    match crate::completion_contract::parse_exit_criteria(v.get("exit_criteria")) {
2567                        Ok(c) => c,
2568                        Err(e) => {
2569                            return ToolResult::error(format!("work_packages[{i}]: {e}"));
2570                        }
2571                    };
2572                packages.push(OrchestratePackage {
2573                    task,
2574                    exit_criteria,
2575                });
2576                continue;
2577            }
2578            return ToolResult::error(format!(
2579                "work_packages[{i}] must be a string or an object {{task, exit_criteria?}}"
2580            ));
2581        }
2582        if packages.is_empty() {
2583            return ToolResult::error("work_packages must include at least one item".into());
2584        }
2585        let max_workers = self
2586            .config
2587            .subagents
2588            .orchestrate_max_workers
2589            .min(self.config.subagents.max_children_per_run);
2590        let wait = input.get("wait").and_then(|v| v.as_bool()).unwrap_or(false);
2591        let wait_timeout_secs = input
2592            .get("wait_timeout_secs")
2593            .and_then(|v| v.as_u64())
2594            .unwrap_or(120)
2595            .clamp(1, 1200);
2596        let total_budget = input
2597            .get("token_budget_total")
2598            .and_then(|v| v.as_i64())
2599            .filter(|v| *v > 0)
2600            .unwrap_or(self.config.subagents.max_tokens_per_run);
2601        let parent_run_id = input
2602            .get("__subagent_runtime")
2603            .and_then(|v| v.get("run_id"))
2604            .and_then(|v| v.as_str())
2605            .map(str::to_string);
2606        let parent_meta = subagent_runtime_meta_from_input(&input);
2607        let parent_remaining = parent_meta.as_ref().and_then(|m| m.token_budget_remaining);
2608        let total_budget = if let Some(remaining) = parent_remaining {
2609            total_budget.min(remaining.max(0))
2610        } else {
2611            total_budget
2612        };
2613        if total_budget < 2_000 {
2614            return ToolResult::error(format!(
2615                "subagent budget exhausted for orchestration: remaining {} < 2000",
2616                total_budget
2617            ));
2618        }
2619        let max_workers_by_budget = (total_budget / 2_000).max(1) as usize;
2620        let allowed_workers = max_workers.min(max_workers_by_budget).max(1);
2621        if packages.len() > allowed_workers {
2622            packages.truncate(allowed_workers);
2623        }
2624        let each_budget = (total_budget / packages.len() as i64).clamp(2_000, total_budget);
2625
2626        let spawn_tool =
2627            SessionsSpawnTool::new(&self.config, self.db.clone(), self.channel_registry.clone());
2628        let mut spawned = Vec::new();
2629        for (idx, pkg) in packages.iter().enumerate() {
2630            let mut spawn_input = json!({
2631                "task": format!("Work package {}: {}", idx + 1, pkg.task),
2632                "context": format!(
2633                    "Orchestration goal: {goal}\nOutput strictly in protocol subagent_artifact_v1 with keys summary/findings/artifacts/next_actions/final_answer."
2634                ),
2635                "chat_id": chat_id,
2636                "token_budget": each_budget,
2637                "__microclaw_auth": {
2638                    "caller_channel": auth.caller_channel.clone(),
2639                    "caller_chat_id": chat_id,
2640                    "control_chat_ids": auth.control_chat_ids.clone(),
2641                    "env_files": auth.env_files.clone(),
2642                }
2643            });
2644            if !pkg.exit_criteria.is_empty() {
2645                if let Some(obj) = spawn_input.as_object_mut() {
2646                    obj.insert(
2647                        "exit_criteria".to_string(),
2648                        serde_json::to_value(&pkg.exit_criteria).unwrap_or_default(),
2649                    );
2650                }
2651            }
2652            let spawn_input = if let (Some(meta), Some(parent_run_id)) =
2653                (parent_meta.as_ref(), parent_run_id.as_deref())
2654            {
2655                let mut obj = spawn_input
2656                    .as_object()
2657                    .cloned()
2658                    .unwrap_or_else(serde_json::Map::new);
2659                obj.insert(
2660                    "__subagent_runtime".to_string(),
2661                    json!({
2662                        "run_id": parent_run_id,
2663                        "depth": meta.depth,
2664                        "runtime": meta.runtime.as_deref().unwrap_or("native"),
2665                        "runtime_target": meta.runtime_target.clone(),
2666                        "token_budget_remaining": each_budget,
2667                    }),
2668                );
2669                serde_json::Value::Object(obj)
2670            } else {
2671                spawn_input
2672            };
2673            let res = spawn_tool.execute(spawn_input).await;
2674            if res.is_error {
2675                return res;
2676            }
2677            let parsed = match serde_json::from_str::<serde_json::Value>(&res.content) {
2678                Ok(v) => v,
2679                Err(e) => return ToolResult::error(format!("Invalid sessions_spawn output: {e}")),
2680            };
2681            let run_id = match parsed.get("run_id").and_then(|v| v.as_str()) {
2682                Some(v) => v.to_string(),
2683                None => return ToolResult::error("sessions_spawn did not return run_id".into()),
2684            };
2685            spawned.push(run_id);
2686        }
2687
2688        if !wait {
2689            return ToolResult::success(
2690                json!({
2691                    "status": "accepted",
2692                    "chat_id": chat_id,
2693                    "goal": goal,
2694                    "workers": spawned.len(),
2695                    "run_ids": spawned,
2696                    "token_budget_total": total_budget,
2697                    "token_budget_each": each_budget,
2698                })
2699                .to_string(),
2700            );
2701        }
2702
2703        let deadline =
2704            std::time::Instant::now() + std::time::Duration::from_secs(wait_timeout_secs);
2705        let mut runs = Vec::new();
2706        let mut wait_timed_out = false;
2707        while std::time::Instant::now() < deadline {
2708            let ids = spawned.clone();
2709            let rows = match call_blocking(self.db.clone(), move |db| {
2710                let mut out = Vec::new();
2711                for run_id in ids {
2712                    if let Some(row) = db.get_subagent_run(&run_id, chat_id)? {
2713                        out.push(row);
2714                    }
2715                }
2716                Ok::<_, microclaw_core::error::MicroClawError>(out)
2717            })
2718            .await
2719            {
2720                Ok(v) => v,
2721                Err(e) => return ToolResult::error(format!("Failed loading runs: {e}")),
2722            };
2723            let done = rows
2724                .iter()
2725                .all(|r| !matches!(r.status.as_str(), "accepted" | "queued" | "running"));
2726            runs = rows;
2727            if done {
2728                break;
2729            }
2730            tokio::time::sleep(std::time::Duration::from_secs(2)).await;
2731        }
2732        if runs
2733            .iter()
2734            .any(|r| matches!(r.status.as_str(), "accepted" | "queued" | "running"))
2735        {
2736            wait_timed_out = true;
2737        }
2738
2739        // Contract-aware fan-in retry: a completed worker whose result carries
2740        // the FAILED contract marker gets exactly ONE replacement run, spawned
2741        // with the failure evidence as extra context. (The in-run bounded
2742        // retry has already happened inside the worker, so this catches the
2743        // cases where the worker gave up.)
2744        let mut retried: Vec<serde_json::Value> = Vec::new();
2745        if !wait_timed_out {
2746            let mut replacements: Vec<(usize, String)> = Vec::new(); // (runs idx, new run_id)
2747            for (idx, run) in runs.iter().enumerate() {
2748                if run.status != "completed" {
2749                    continue;
2750                }
2751                let Some(result_text) = run.result_text.as_deref() else {
2752                    continue;
2753                };
2754                if !result_text.trim_start().starts_with(CONTRACT_FAILED_MARKER) {
2755                    continue;
2756                }
2757                // Recover the package (spawn order matches `packages`).
2758                let Some(pkg_idx) = spawned.iter().position(|id| *id == run.run_id) else {
2759                    continue;
2760                };
2761                let Some(pkg) = packages.get(pkg_idx) else {
2762                    continue;
2763                };
2764                let evidence_end = microclaw_core::text::floor_char_boundary(result_text, 600);
2765                let mut spawn_input = json!({
2766                    "task": format!("Work package {} (retry): {}", pkg_idx + 1, pkg.task),
2767                    "context": format!(
2768                        "Orchestration goal: {goal}\nA previous attempt FAILED its completion contract. Evidence:\n{}\nComplete the unmet criteria.\nOutput strictly in protocol subagent_artifact_v1 with keys summary/findings/artifacts/next_actions/final_answer.",
2769                        &result_text[..evidence_end]
2770                    ),
2771                    "chat_id": chat_id,
2772                    "token_budget": each_budget,
2773                    "exit_criteria": serde_json::to_value(&pkg.exit_criteria).unwrap_or_default(),
2774                    "__microclaw_auth": {
2775                        "caller_channel": auth.caller_channel.clone(),
2776                        "caller_chat_id": chat_id,
2777                        "control_chat_ids": auth.control_chat_ids.clone(),
2778                        "env_files": auth.env_files.clone(),
2779                    }
2780                });
2781                if let (Some(meta), Some(parent_run_id)) =
2782                    (parent_meta.as_ref(), parent_run_id.as_deref())
2783                {
2784                    if let Some(obj) = spawn_input.as_object_mut() {
2785                        obj.insert(
2786                            "__subagent_runtime".to_string(),
2787                            json!({
2788                                "run_id": parent_run_id,
2789                                "depth": meta.depth,
2790                                "runtime": meta.runtime.as_deref().unwrap_or("native"),
2791                                "runtime_target": meta.runtime_target.clone(),
2792                                "token_budget_remaining": each_budget,
2793                            }),
2794                        );
2795                    }
2796                }
2797                let res = spawn_tool.execute(spawn_input).await;
2798                if res.is_error {
2799                    // Budget/depth exhausted: keep the failed result as-is.
2800                    continue;
2801                }
2802                let new_run_id = serde_json::from_str::<serde_json::Value>(&res.content)
2803                    .ok()
2804                    .and_then(|v| v.get("run_id").and_then(|r| r.as_str()).map(str::to_string));
2805                if let Some(new_run_id) = new_run_id {
2806                    retried.push(json!({
2807                        "package": pkg_idx + 1,
2808                        "failed_run_id": run.run_id.clone(),
2809                        "retry_run_id": new_run_id.clone(),
2810                    }));
2811                    replacements.push((idx, new_run_id));
2812                }
2813            }
2814
2815            if !replacements.is_empty() {
2816                // Wait for the replacement runs within the remaining deadline.
2817                let retry_ids: Vec<String> =
2818                    replacements.iter().map(|(_, id)| id.clone()).collect();
2819                loop {
2820                    let ids = retry_ids.clone();
2821                    let rows = match call_blocking(self.db.clone(), move |db| {
2822                        let mut out = Vec::new();
2823                        for run_id in ids {
2824                            if let Some(row) = db.get_subagent_run(&run_id, chat_id)? {
2825                                out.push(row);
2826                            }
2827                        }
2828                        Ok::<_, microclaw_core::error::MicroClawError>(out)
2829                    })
2830                    .await
2831                    {
2832                        Ok(v) => v,
2833                        Err(e) => return ToolResult::error(format!("Failed loading runs: {e}")),
2834                    };
2835                    let done = rows
2836                        .iter()
2837                        .all(|r| !matches!(r.status.as_str(), "accepted" | "queued" | "running"));
2838                    if done {
2839                        // Swap the finished replacements into the merge set.
2840                        for (idx, retry_id) in &replacements {
2841                            if let Some(row) = rows.iter().find(|r| r.run_id == *retry_id) {
2842                                runs[*idx] = row.clone();
2843                            }
2844                        }
2845                        break;
2846                    }
2847                    if std::time::Instant::now() >= deadline {
2848                        wait_timed_out = true;
2849                        break;
2850                    }
2851                    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
2852                }
2853            }
2854        }
2855
2856        let merged = Self::merge_run_artifacts(&runs);
2857        ToolResult::success(
2858            json!({
2859                "status": if wait_timed_out { "timeout_partial" } else { "merged" },
2860                "chat_id": chat_id,
2861                "goal": goal,
2862                "workers": spawned.len(),
2863                "run_ids": spawned,
2864                "retried": retried,
2865                "runs": runs.into_iter().map(|r| json!({
2866                    "run_id": r.run_id,
2867                    "status": r.status,
2868                    "depth": r.depth,
2869                    "token_budget": r.token_budget,
2870                    "total_tokens": r.total_tokens,
2871                    "artifact_json": r.artifact_json,
2872                })).collect::<Vec<_>>(),
2873                "merged": merged,
2874            })
2875            .to_string(),
2876        )
2877    }
2878}
2879
2880impl SubagentsLogTool {
2881    pub fn new(db: Arc<Database>) -> Self {
2882        Self { db }
2883    }
2884}
2885
2886#[async_trait]
2887impl Tool for SubagentsLogTool {
2888    fn name(&self) -> &str {
2889        "subagents_log"
2890    }
2891
2892    fn definition(&self) -> ToolDefinition {
2893        ToolDefinition {
2894            name: "subagents_log".into(),
2895            description: "Get timeline events for one subagent run.".into(),
2896            input_schema: schema_object(
2897                json!({
2898                    "run_id": {"type":"string"},
2899                    "chat_id": {"type":"integer"},
2900                    "limit": {"type":"integer", "minimum":1, "maximum":200}
2901                }),
2902                &["run_id"],
2903            ),
2904        }
2905    }
2906
2907    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2908        let auth = match auth_context_from_input(&input) {
2909            Some(v) => v,
2910            None => return ToolResult::error("subagents_log requires caller auth context".into()),
2911        };
2912        let chat_id = input
2913            .get("chat_id")
2914            .and_then(|v| v.as_i64())
2915            .unwrap_or(auth.caller_chat_id);
2916        if let Err(e) = authorize_chat_access(&input, chat_id) {
2917            return ToolResult::error(e);
2918        }
2919        let run_id = match input.get("run_id").and_then(|v| v.as_str()) {
2920            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2921            _ => return ToolResult::error("Missing required parameter: run_id".into()),
2922        };
2923        let run_id_for_check = run_id.clone();
2924        let run_exists = match call_blocking(self.db.clone(), move |db| {
2925            db.get_subagent_run(&run_id_for_check, chat_id)
2926        })
2927        .await
2928        {
2929            Ok(v) => v.is_some(),
2930            Err(e) => return ToolResult::error(format!("Failed reading subagent run: {e}")),
2931        };
2932        if !run_exists {
2933            return ToolResult::error("Subagent run not found".into());
2934        }
2935        let limit = input
2936            .get("limit")
2937            .and_then(|v| v.as_u64())
2938            .unwrap_or(50)
2939            .clamp(1, 200) as usize;
2940        let run_id_for_events = run_id.clone();
2941        let events = match call_blocking(self.db.clone(), move |db| {
2942            db.list_subagent_events(&run_id_for_events, limit)
2943        })
2944        .await
2945        {
2946            Ok(v) => v,
2947            Err(e) => return ToolResult::error(format!("Failed listing subagent events: {e}")),
2948        };
2949        let payload: Vec<serde_json::Value> = events
2950            .into_iter()
2951            .map(|e| {
2952                json!({
2953                    "id": e.id,
2954                    "run_id": e.run_id,
2955                    "event_type": e.event_type,
2956                    "detail": e.detail,
2957                    "created_at": e.created_at
2958                })
2959            })
2960            .collect();
2961        ToolResult::success(json!({"run_id": run_id, "events": payload}).to_string())
2962    }
2963}
2964
2965impl SubagentsRetryAnnouncesTool {
2966    pub fn new(config: &Config, db: Arc<Database>, channel_registry: Arc<ChannelRegistry>) -> Self {
2967        Self {
2968            config: config.clone(),
2969            db,
2970            channel_registry,
2971        }
2972    }
2973}
2974
2975#[async_trait]
2976impl Tool for SubagentsRetryAnnouncesTool {
2977    fn name(&self) -> &str {
2978        "subagents_retry_announces"
2979    }
2980
2981    fn definition(&self) -> ToolDefinition {
2982        ToolDefinition {
2983            name: "subagents_retry_announces".into(),
2984            description:
2985                "Manually flush pending subagent completion announcements (control chats only)."
2986                    .into(),
2987            input_schema: schema_object(
2988                json!({
2989                    "batch": {"type": "integer", "minimum": 1, "maximum": 200}
2990                }),
2991                &[],
2992            ),
2993        }
2994    }
2995
2996    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2997        let auth = match auth_context_from_input(&input) {
2998            Some(v) => v,
2999            None => {
3000                return ToolResult::error(
3001                    "subagents_retry_announces requires caller auth context".into(),
3002                )
3003            }
3004        };
3005        if !auth.is_control_chat() {
3006            return ToolResult::error(
3007                "Permission denied: subagents_retry_announces requires control chat".into(),
3008            );
3009        }
3010        let batch = input
3011            .get("batch")
3012            .and_then(|v| v.as_u64())
3013            .unwrap_or(50)
3014            .clamp(1, 200) as usize;
3015        let _ = flush_pending_announces_once(
3016            &self.config,
3017            self.channel_registry.clone(),
3018            self.db.clone(),
3019            batch,
3020        )
3021        .await;
3022        ToolResult::success(json!({"status":"ok","batch":batch}).to_string())
3023    }
3024}
3025
3026#[cfg(test)]
3027mod tests {
3028    use super::*;
3029    use crate::config::WorkingDirIsolation;
3030
3031    fn test_config() -> Config {
3032        let mut cfg = Config::test_defaults();
3033        cfg.model = "claude-test".into();
3034        cfg.max_tokens = 2048;
3035        cfg.data_dir = "/tmp".into();
3036        cfg.working_dir = "/tmp".into();
3037        cfg.working_dir_isolation = WorkingDirIsolation::Shared;
3038        cfg.web_enabled = false;
3039        cfg
3040    }
3041
3042    fn test_db() -> Arc<Database> {
3043        let dir = std::env::temp_dir().join(format!(
3044            "microclaw_subagents_tool_test_{}",
3045            uuid::Uuid::new_v4()
3046        ));
3047        std::fs::create_dir_all(&dir).unwrap();
3048        Arc::new(Database::new(dir.to_str().unwrap()).unwrap())
3049    }
3050
3051    #[tokio::test]
3052    async fn test_sessions_spawn_requires_task() {
3053        let tool =
3054            SessionsSpawnTool::new(&test_config(), test_db(), Arc::new(ChannelRegistry::new()));
3055        let result = tool
3056            .execute(json!({"__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}}))
3057            .await;
3058        assert!(result.is_error);
3059        assert!(result.content.contains("task"));
3060    }
3061
3062    #[tokio::test]
3063    async fn test_sessions_spawn_rejects_unknown_runtime() {
3064        let tool =
3065            SessionsSpawnTool::new(&test_config(), test_db(), Arc::new(ChannelRegistry::new()));
3066        let result = tool
3067            .execute(json!({
3068                "task": "run",
3069                "runtime": "mystery",
3070                "__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}
3071            }))
3072            .await;
3073        assert!(result.is_error);
3074        assert!(result.content.contains("Unsupported subagent runtime"));
3075    }
3076
3077    #[tokio::test]
3078    async fn test_sessions_spawn_rejects_disabled_acp_runtime() {
3079        let tool =
3080            SessionsSpawnTool::new(&test_config(), test_db(), Arc::new(ChannelRegistry::new()));
3081        let result = tool
3082            .execute(json!({
3083                "task": "run",
3084                "runtime": "acp",
3085                "__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}
3086            }))
3087            .await;
3088        assert!(result.is_error);
3089        assert!(result.content.contains("ACP runtime is disabled"));
3090    }
3091
3092    #[tokio::test]
3093    async fn test_sessions_spawn_rejects_unknown_acp_target() {
3094        let mut cfg = test_config();
3095        cfg.subagents.acp.default_target.enabled = true;
3096        cfg.subagents.acp.default_target.command = "codex".into();
3097        let tool = SessionsSpawnTool::new(&cfg, test_db(), Arc::new(ChannelRegistry::new()));
3098        let result = tool
3099            .execute(json!({
3100                "task": "run",
3101                "runtime": "acp",
3102                "runtime_target": "missing",
3103                "__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}
3104            }))
3105            .await;
3106        assert!(result.is_error);
3107        assert!(result.content.contains("Unknown ACP runtime target"));
3108    }
3109
3110    #[tokio::test]
3111    async fn test_sessions_spawn_inherits_acp_runtime_target_from_parent_meta() {
3112        let mut cfg = test_config();
3113        cfg.subagents.acp.default_target.enabled = true;
3114        cfg.subagents.acp.targets.insert(
3115            "worker".into(),
3116            crate::config::SubagentAcpTargetConfig {
3117                enabled: true,
3118                command: "codex".into(),
3119                ..crate::config::SubagentAcpTargetConfig::default()
3120            },
3121        );
3122        let tool = SessionsSpawnTool::new(&cfg, test_db(), Arc::new(ChannelRegistry::new()));
3123        let result = tool
3124            .execute(json!({
3125                "task": "run",
3126                "__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1},
3127                "__subagent_runtime": {
3128                    "run_id": "parent",
3129                    "depth": 0,
3130                    "runtime": "acp",
3131                    "runtime_target": "worker",
3132                    "token_budget_remaining": 8000
3133                }
3134            }))
3135            .await;
3136        assert!(!result.is_error);
3137        let parsed: serde_json::Value = serde_json::from_str(&result.content).unwrap();
3138        assert_eq!(parsed.get("runtime").and_then(|v| v.as_str()), Some("acp"));
3139        assert_eq!(
3140            parsed.get("runtime_target").and_then(|v| v.as_str()),
3141            Some("worker")
3142        );
3143    }
3144
3145    #[tokio::test]
3146    async fn sessions_spawn_offers_project_agents_and_uses_the_subagent_model() {
3147        let agents = tempfile::tempdir().unwrap();
3148        std::fs::write(
3149            agents.path().join("reviewer.md"),
3150            "---\ndescription: Reviews diffs\nmodel: agent-model\ntools: read, grep\n---\nYou review code.",
3151        )
3152        .unwrap();
3153        let mut cfg = test_config();
3154        cfg.project_agents_dir = Some(agents.path().to_string_lossy().into_owned());
3155        cfg.aux_models.subagent = Some("cheap-model".into());
3156        let db = test_db();
3157        let tool = SessionsSpawnTool::new(&cfg, db.clone(), Arc::new(ChannelRegistry::new()));
3158        let definition = tool.definition();
3159        assert!(definition.description.contains("reviewer (Reviews diffs)"));
3160        assert_eq!(
3161            definition.input_schema["properties"]["agent"]["enum"],
3162            json!(["reviewer"])
3163        );
3164
3165        let unknown = tool
3166            .execute(json!({
3167                "task": "look",
3168                "agent": "nobody",
3169                "__microclaw_auth": {"caller_channel":"code", "caller_chat_id": 1}
3170            }))
3171            .await;
3172        assert!(unknown.is_error);
3173        assert!(
3174            unknown.content.contains("available: reviewer"),
3175            "{}",
3176            unknown.content
3177        );
3178
3179        let model_of = |result: &ToolResult| {
3180            let parsed: serde_json::Value = serde_json::from_str(&result.content).unwrap();
3181            let run_id = parsed["run_id"].as_str().unwrap().to_string();
3182            db.get_subagent_run(&run_id, 1).unwrap().unwrap().model
3183        };
3184        let plain = tool
3185            .execute(json!({
3186                "task": "look",
3187                "__microclaw_auth": {"caller_channel":"code", "caller_chat_id": 1}
3188            }))
3189            .await;
3190        assert!(!plain.is_error, "{}", plain.content);
3191        assert_eq!(model_of(&plain), "cheap-model");
3192        let as_agent = tool
3193            .execute(json!({
3194                "task": "review",
3195                "agent": "reviewer",
3196                "__microclaw_auth": {"caller_channel":"code", "caller_chat_id": 1}
3197            }))
3198            .await;
3199        assert!(!as_agent.is_error, "{}", as_agent.content);
3200        assert_eq!(model_of(&as_agent), "agent-model");
3201        let parsed: serde_json::Value = serde_json::from_str(&as_agent.content).unwrap();
3202        assert_eq!(parsed["label"], json!("reviewer"));
3203    }
3204
3205    #[tokio::test]
3206    async fn test_subagents_info_requires_run_id() {
3207        let tool = SubagentsInfoTool::new(test_db());
3208        let result = tool
3209            .execute(json!({"__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}}))
3210            .await;
3211        assert!(result.is_error);
3212        assert!(result.content.contains("run_id"));
3213    }
3214
3215    #[test]
3216    fn test_normalize_strips_leaked_thinking() {
3217        // A sub-agent that emits only chain-of-thought (no JSON) must not leak
3218        // the <think> block into the announced answer.
3219        let raw = "<think>The write_memory tool is not available - I see read_memory \
3220                   but not write_memory. Let me inform the user.</think>";
3221        let (answer, envelope) = normalize_subagent_artifact_payload(raw);
3222        assert!(!answer.contains("<think>"));
3223        assert!(!answer.contains("write_memory"));
3224        assert!(!envelope.contains("<think>"));
3225    }
3226
3227    #[test]
3228    fn contract_failed_marker_matches_report_rendering() {
3229        // The fan-in retry detects failed contracts by this marker; it must
3230        // stay in sync with completion_contract::render_report.
3231        let report = crate::completion_contract::render_report(&[
3232            crate::completion_contract::CriterionOutcome {
3233                description: "file `x` exists".into(),
3234                passed: false,
3235                evidence: "missing".into(),
3236            },
3237        ]);
3238        assert!(report.starts_with(CONTRACT_FAILED_MARKER));
3239        // And the VERIFIED path must NOT match the failure marker.
3240        let ok_report = crate::completion_contract::render_report(&[
3241            crate::completion_contract::CriterionOutcome {
3242                description: "file `x` exists".into(),
3243                passed: true,
3244                evidence: "ok".into(),
3245            },
3246        ]);
3247        assert!(!ok_report.starts_with(CONTRACT_FAILED_MARKER));
3248    }
3249
3250    #[test]
3251    fn test_submit_result_tool_definition_shape() {
3252        let def = submit_result_tool_definition();
3253        assert_eq!(def.name, SUBMIT_RESULT_TOOL);
3254        let props = def.input_schema.get("properties").unwrap();
3255        for key in [
3256            "summary",
3257            "findings",
3258            "artifacts",
3259            "next_actions",
3260            "final_answer",
3261        ] {
3262            assert!(props.get(key).is_some(), "missing schema property {key}");
3263        }
3264        let required = def
3265            .input_schema
3266            .get("required")
3267            .unwrap()
3268            .as_array()
3269            .unwrap();
3270        assert!(required.iter().any(|v| v == "final_answer"));
3271        // A submit_result payload normalizes into the announced answer.
3272        let payload = json!({"summary": "s", "final_answer": "the answer"}).to_string();
3273        let (answer, _envelope) = normalize_subagent_artifact_payload(&payload);
3274        assert_eq!(answer, "the answer");
3275    }
3276
3277    #[test]
3278    fn test_subagent_output_is_structured() {
3279        // Prose / leaked reasoning is NOT structured (would trigger a repair).
3280        assert!(!subagent_output_is_structured(
3281            "<think>no write_memory tool</think> I can't save this."
3282        ));
3283        assert!(!subagent_output_is_structured(
3284            "Done, everything looks good."
3285        ));
3286        // A contract object (even after a thinking block) IS structured.
3287        assert!(subagent_output_is_structured(
3288            "<think>ok</think>{\"summary\":\"s\",\"final_answer\":\"done\"}"
3289        ));
3290        // An object with only empty contract fields is not structured.
3291        assert!(!subagent_output_is_structured(
3292            "{\"summary\":\"\",\"final_answer\":\"\"}"
3293        ));
3294    }
3295
3296    #[test]
3297    fn test_normalize_recovers_json_after_thinking() {
3298        // Reasoning block followed by the contract JSON: the JSON must win, not
3299        // the raw text fallback.
3300        let raw = "<think>let me structure this</think>\n\
3301                   {\"summary\":\"done\",\"findings\":[\"a\"],\"artifacts\":[],\
3302                   \"next_actions\":[],\"final_answer\":\"All set.\"}";
3303        let (answer, _envelope) = normalize_subagent_artifact_payload(raw);
3304        assert_eq!(answer, "All set.");
3305    }
3306
3307    #[test]
3308    fn test_compute_child_token_budget_respects_parent_remaining() {
3309        let budget = compute_child_token_budget(Some(5000), Some(3000), 120000).unwrap();
3310        assert_eq!(budget, 3000);
3311    }
3312
3313    #[test]
3314    fn test_compute_child_token_budget_rejects_exhausted_parent() {
3315        let err = compute_child_token_budget(None, Some(1500), 120000).unwrap_err();
3316        assert!(err.contains("budget exhausted"));
3317    }
3318
3319    #[test]
3320    fn process_lifetime_executor_outlives_foreground_runtime() {
3321        let (tx, rx) = std::sync::mpsc::channel();
3322        {
3323            let foreground = tokio::runtime::Runtime::new().unwrap();
3324            foreground.block_on(async {
3325                TASK_RUNTIME.spawn(async move {
3326                    tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3327                    tx.send("finished").unwrap();
3328                });
3329            });
3330        }
3331        assert_eq!(
3332            rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(),
3333            "finished"
3334        );
3335    }
3336}