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 = crate::tools::explore::config_agents(config);
1208        Self {
1209            config: config.clone(),
1210            db,
1211            channel_registry,
1212            agents,
1213        }
1214    }
1215}
1216
1217#[async_trait]
1218impl Tool for SessionsSpawnTool {
1219    fn name(&self) -> &str {
1220        "sessions_spawn"
1221    }
1222
1223    fn definition(&self) -> ToolDefinition {
1224        let mut definition = ToolDefinition {
1225            name: "sessions_spawn".into(),
1226            description: format!(
1227                "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: {}.",
1228                crate::tools::specialists::specialist_catalog()
1229            ),
1230            input_schema: schema_object(
1231                json!({
1232                    "task": {
1233                        "type": "string",
1234                        "description": "Task for the spawned sub-agent"
1235                    },
1236                    "context": {
1237                        "type": "string",
1238                        "description": "Optional extra context passed to the sub-agent"
1239                    },
1240                    "specialist": {
1241                        "type": "string",
1242                        "enum": crate::tools::specialists::specialist_names(),
1243                        "description": "Which specialist persona the sub-agent adopts. Defaults to generalist."
1244                    },
1245                    "label": {
1246                        "type": "string",
1247                        "description": "Short human-friendly name for this task (e.g. 'competitor research'), shown when listing/reporting progress. Recommended when running several tasks at once."
1248                    },
1249                    "runtime": {
1250                        "type": "string",
1251                        "enum": ["native", "acp"],
1252                        "description": "Execution backend for the sub-agent. Defaults to native."
1253                    },
1254                    "runtime_target": {
1255                        "type": "string",
1256                        "description": "Optional named ACP target when runtime is 'acp'."
1257                    },
1258                    "chat_id": {
1259                        "type": "integer",
1260                        "description": "Target chat id. Defaults to current chat."
1261                    },
1262                    "token_budget": {
1263                        "type": "integer",
1264                        "description": "Optional token budget cap for this run."
1265                    },
1266                    "exit_criteria": {
1267                        "type": "array",
1268                        "maxItems": 8,
1269                        "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.",
1270                        "items": {"type": "object"}
1271                    }
1272                }),
1273                &["task"],
1274            ),
1275        };
1276        if !self.agents.is_empty() {
1277            if let Some(properties) = definition
1278                .input_schema
1279                .get_mut("properties")
1280                .and_then(|p| p.as_object_mut())
1281            {
1282                properties.insert(
1283                    "agent".into(),
1284                    json!({
1285                        "type": "string",
1286                        "enum": self.agents.iter().map(|a| a.name.clone()).collect::<Vec<_>>(),
1287                        "description": "Project agent to run as (its own instructions, model and tools) instead of a specialist"
1288                    }),
1289                );
1290            }
1291            let list: Vec<String> = self
1292                .agents
1293                .iter()
1294                .map(|a| {
1295                    if a.description.is_empty() {
1296                        a.name.clone()
1297                    } else {
1298                        format!("{} ({})", a.name, a.description)
1299                    }
1300                })
1301                .collect();
1302            definition.description.push_str(&format!(
1303                " Project agents (pass as `agent`): {}.",
1304                list.join("; ")
1305            ));
1306        }
1307        definition
1308    }
1309
1310    async fn execute(&self, input: serde_json::Value) -> ToolResult {
1311        let auth =
1312            match auth_context_from_input(&input) {
1313                Some(v) => v,
1314                None => return ToolResult::error(
1315                    "sessions_spawn requires caller auth context; run from an active chat session"
1316                        .into(),
1317                ),
1318            };
1319
1320        let chat_id = input
1321            .get("chat_id")
1322            .and_then(|v| v.as_i64())
1323            .unwrap_or(auth.caller_chat_id);
1324        if let Err(e) = authorize_chat_access(&input, chat_id) {
1325            return ToolResult::error(e);
1326        }
1327
1328        let task = match input.get("task").and_then(|v| v.as_str()) {
1329            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
1330            _ => return ToolResult::error("Missing required parameter: task".into()),
1331        };
1332        let context = input
1333            .get("context")
1334            .and_then(|v| v.as_str())
1335            .unwrap_or("")
1336            .trim()
1337            .to_string();
1338        // Resolve the requested specialist (falls back to generalist for unknown/empty).
1339        let specialist = crate::tools::specialists::resolve_specialist(
1340            input.get("specialist").and_then(|v| v.as_str()),
1341        )
1342        .name
1343        .to_string();
1344        let exit_criteria =
1345            match crate::completion_contract::parse_exit_criteria(input.get("exit_criteria")) {
1346                Ok(v) => v,
1347                Err(e) => return ToolResult::error(e),
1348            };
1349        // Optional human-friendly label ("competitor research") for "what am I working on".
1350        let label = input
1351            .get("label")
1352            .and_then(|v| v.as_str())
1353            .map(str::trim)
1354            .filter(|v| !v.is_empty())
1355            .map(|v| v.chars().take(80).collect::<String>());
1356        let parent_meta = subagent_runtime_meta_from_input(&input);
1357        let execution_runtime =
1358            match SubagentExecutionRuntime::from_input(&input, parent_meta.as_ref()) {
1359                Ok(v) => v,
1360                Err(e) => return ToolResult::error(e),
1361            };
1362        let runtime_target = input
1363            .get("runtime_target")
1364            .and_then(|v| v.as_str())
1365            .map(str::trim)
1366            .filter(|v| !v.is_empty())
1367            .map(ToOwned::to_owned)
1368            .or_else(|| {
1369                parent_meta
1370                    .as_ref()
1371                    .and_then(|meta| meta.runtime_target.clone())
1372            });
1373        let parent_depth = parent_meta.as_ref().map(|m| m.depth).unwrap_or(0);
1374        let parent_budget_remaining = parent_meta.as_ref().and_then(|m| m.token_budget_remaining);
1375        let child_depth = if parent_depth > 0 {
1376            parent_depth + 1
1377        } else {
1378            1
1379        };
1380        if child_depth as usize > self.config.subagents.max_spawn_depth {
1381            return ToolResult::error(format!(
1382                "subagent spawn depth exceeded: requested depth {}, max {}",
1383                child_depth, self.config.subagents.max_spawn_depth
1384            ));
1385        }
1386        let parent_run_id = input
1387            .get("__subagent_runtime")
1388            .and_then(|v| v.get("run_id"))
1389            .and_then(|v| v.as_str())
1390            .map(str::to_string);
1391        let requested_budget = input
1392            .get("token_budget")
1393            .and_then(|v| v.as_i64())
1394            .filter(|v| *v > 0);
1395        let child_token_budget = match compute_child_token_budget(
1396            requested_budget,
1397            parent_budget_remaining,
1398            self.config.subagents.max_tokens_per_run,
1399        ) {
1400            Ok(v) => v,
1401            Err(e) => return ToolResult::error(e),
1402        };
1403
1404        let db_for_count = self.db.clone();
1405        let active_count = match call_blocking(db_for_count, move |db| {
1406            db.count_active_subagent_runs_for_chat(chat_id)
1407        })
1408        .await
1409        {
1410            Ok(v) => v,
1411            Err(e) => {
1412                return ToolResult::error(format!("Failed checking active subagent runs: {e}"));
1413            }
1414        };
1415        if active_count as usize >= self.config.subagents.max_active_per_chat {
1416            return ToolResult::error(format!(
1417                "Too many active subagent runs for this chat (limit: {})",
1418                self.config.subagents.max_active_per_chat
1419            ));
1420        }
1421        if let Some(parent_id) = parent_run_id.as_ref() {
1422            let parent_id_for_count = parent_id.clone();
1423            let active_children = match call_blocking(self.db.clone(), move |db| {
1424                db.count_active_subagent_children(&parent_id_for_count)
1425            })
1426            .await
1427            {
1428                Ok(v) => v,
1429                Err(e) => {
1430                    return ToolResult::error(format!(
1431                        "Failed checking active subagent child runs: {e}"
1432                    ));
1433                }
1434            };
1435            if active_children as usize >= self.config.subagents.max_children_per_run {
1436                return ToolResult::error(format!(
1437                    "Too many active child runs for this parent (limit: {})",
1438                    self.config.subagents.max_children_per_run
1439                ));
1440            }
1441        }
1442
1443        let agent = match input.get("agent").and_then(|v| v.as_str()).map(str::trim) {
1444            Some(name) if !name.is_empty() => match self.agents.iter().find(|a| a.name == name) {
1445                Some(agent) => Some(agent.clone()),
1446                None => {
1447                    return ToolResult::error(format!(
1448                        "Unknown project agent `{name}`{}",
1449                        if self.agents.is_empty() {
1450                            String::new()
1451                        } else {
1452                            format!(
1453                                "; available: {}",
1454                                self.agents
1455                                    .iter()
1456                                    .map(|a| a.name.as_str())
1457                                    .collect::<Vec<_>>()
1458                                    .join(", ")
1459                            )
1460                        }
1461                    ))
1462                }
1463            },
1464            _ => None,
1465        };
1466        if agent.is_some() && matches!(execution_runtime, SubagentExecutionRuntime::Acp) {
1467            return ToolResult::error(
1468                "Project agents run on the native runtime; drop `runtime: acp` or `agent`".into(),
1469            );
1470        }
1471        let label = label.or_else(|| agent.as_ref().map(|a| a.name.clone()));
1472
1473        let run_id = format!("subrun-{}", uuid::Uuid::new_v4());
1474        let (provider, model, acp_target) = match execution_runtime {
1475            SubagentExecutionRuntime::Native => (
1476                self.config.llm_provider.clone(),
1477                agent
1478                    .as_ref()
1479                    .and_then(|a| a.model.clone())
1480                    .unwrap_or_else(|| {
1481                        self.config
1482                            .aux_models
1483                            .subagent_model(&self.config.model)
1484                            .to_string()
1485                    }),
1486                None,
1487            ),
1488            SubagentExecutionRuntime::Acp => {
1489                if !self.config.subagents.acp.default_target.enabled {
1490                    return ToolResult::error(
1491                        "ACP runtime is disabled. Set `subagents.acp.enabled: true` and configure `subagents.acp.command` or `subagents.acp.targets` first."
1492                            .into(),
1493                    );
1494                }
1495                let resolved = match self
1496                    .config
1497                    .subagents
1498                    .acp
1499                    .resolve_target(runtime_target.as_deref())
1500                {
1501                    Ok(target) => target,
1502                    Err(err) => return ToolResult::error(err),
1503                };
1504                (
1505                    crate::acp_subagent::acp_runtime_provider(resolved.name.as_deref()),
1506                    crate::acp_subagent::acp_runtime_model(&resolved),
1507                    Some(resolved),
1508                )
1509            }
1510        };
1511
1512        let subagent_model = model.clone();
1513        let run_id_for_insert = run_id.clone();
1514        let task_for_insert = task.clone();
1515        let context_for_insert = context.clone();
1516        let caller_channel_for_insert = auth.caller_channel.clone();
1517        let parent_for_insert = parent_run_id.clone();
1518        let label_for_insert = label.clone();
1519        if let Err(e) = call_blocking(self.db.clone(), move |db| {
1520            db.create_subagent_run(CreateSubagentRunParams {
1521                run_id: &run_id_for_insert,
1522                parent_run_id: parent_for_insert.as_deref(),
1523                depth: child_depth,
1524                token_budget: child_token_budget,
1525                chat_id,
1526                caller_channel: &caller_channel_for_insert,
1527                task: &task_for_insert,
1528                context: &context_for_insert,
1529                provider: &provider,
1530                model: &model,
1531                label: label_for_insert.as_deref(),
1532            })
1533        })
1534        .await
1535        {
1536            return ToolResult::error(format!("Failed creating subagent run: {e}"));
1537        }
1538        log_subagent_event(
1539            self.db.clone(),
1540            &run_id,
1541            "accepted",
1542            Some(format!(
1543                "depth={child_depth} runtime={} specialist={specialist}{}",
1544                execution_runtime.as_str(),
1545                runtime_target
1546                    .as_deref()
1547                    .map(|target| format!(" runtime_target={target}"))
1548                    .unwrap_or_default()
1549            )),
1550        )
1551        .await;
1552
1553        let runtime = subagent_runtime(&self.config);
1554        let local_cancel = runtime.register_run(&run_id);
1555        let db = self.db.clone();
1556        let mut cfg = self.config.clone();
1557        if matches!(execution_runtime, SubagentExecutionRuntime::Native) {
1558            // The sub-agent's provider uses `cfg.model` as its model.
1559            cfg.model = subagent_model;
1560        }
1561        let agent_async = agent.clone();
1562        let run_id_async = run_id.clone();
1563        let task_async = task.clone();
1564        let context_async = context.clone();
1565        let specialist_async = specialist.clone();
1566        let exit_criteria_async = exit_criteria.clone();
1567        let parent_run_id_async = parent_run_id.clone();
1568        let auth_async = ToolAuthContext {
1569            caller_channel: auth.caller_channel.clone(),
1570            caller_chat_id: chat_id,
1571            principal: format!("subagent:{run_id}"),
1572            control_chat_ids: auth.control_chat_ids.clone(),
1573            env_files: auth.env_files.clone(),
1574        };
1575        let channel_registry = self.channel_registry.clone();
1576        let subagent_channel_registry = self.channel_registry.clone();
1577        let fan_in_channel_registry = self.channel_registry.clone();
1578        let caller_channel_for_event = auth.caller_channel.clone();
1579        TASK_RUNTIME.spawn(async move {
1580            let run_id_for_finish = run_id_async.clone();
1581            let _ = call_blocking(db.clone(), {
1582                let run_id = run_id_async.clone();
1583                move |db| db.mark_subagent_queued(&run_id)
1584            })
1585            .await;
1586            log_subagent_event(db.clone(), &run_id_async, "queued", None).await;
1587
1588            let _permit = match runtime.semaphore.acquire().await {
1589                Ok(p) => p,
1590                Err(_) => {
1591                    let _ = call_blocking(db.clone(), move |db| {
1592                        db.mark_subagent_finished(FinishSubagentRunParams {
1593                            run_id: &run_id_for_finish,
1594                            status: "failed",
1595                            error_text: Some("subagent runtime is shutting down"),
1596                            result_text: None,
1597                            artifact_json: None,
1598                            input_tokens: 0,
1599                            output_tokens: 0,
1600                        })
1601                    })
1602                    .await;
1603                    runtime.remove_run(&run_id_async);
1604                    return;
1605                }
1606            };
1607
1608            let _ = call_blocking(db.clone(), {
1609                let run_id = run_id_async.clone();
1610                move |db| db.mark_subagent_running(&run_id)
1611            })
1612            .await;
1613            log_subagent_event(db.clone(), &run_id_async, "running", None).await;
1614
1615            let timeout_secs = cfg.subagents.run_timeout_secs;
1616            let run_future = run_sub_agent_task(RunSubAgentTaskParams {
1617                config: cfg.clone(),
1618                db: db.clone(),
1619                channel_registry: subagent_channel_registry,
1620                auth_context: auth_async,
1621                run_id: run_id_async.clone(),
1622                runtime: execution_runtime,
1623                acp_target,
1624                depth: child_depth,
1625                run_token_budget: child_token_budget,
1626                task: task_async,
1627                context: context_async,
1628                specialist: specialist_async,
1629                agent: agent_async,
1630                exit_criteria: exit_criteria_async,
1631                local_cancel,
1632            });
1633
1634            let final_outcome = if timeout_secs > 0 {
1635                match tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), run_future)
1636                    .await
1637                {
1638                    Ok(result) => result,
1639                    Err(_) => Err("timed_out".to_string()),
1640                }
1641            } else {
1642                run_future.await
1643            };
1644
1645            let finish_status = match &final_outcome {
1646                Ok(_) => "completed",
1647                Err(err) if err == "cancelled" => "cancelled",
1648                Err(err) if err == "timed_out" => "timed_out",
1649                Err(err) if err.contains("budget_exceeded:") => "budget_exceeded",
1650                Err(_) => "failed",
1651            };
1652            // Surface completion into the parent turn's heartbeat if it is
1653            // still running (no-op otherwise).
1654            crate::agent_engine::send_turn_event(
1655                &auth.caller_channel,
1656                chat_id,
1657                crate::agent_engine::AgentEvent::SubagentFinished {
1658                    run_id: run_id_async.clone(),
1659                    status: finish_status.to_string(),
1660                },
1661            );
1662
1663            match final_outcome {
1664                Ok((result, artifact_json, input_tokens, output_tokens)) => {
1665                    let rid = run_id_for_finish.clone();
1666                    let _ = call_blocking(db.clone(), move |db| {
1667                        db.mark_subagent_finished(FinishSubagentRunParams {
1668                            run_id: &rid,
1669                            status: "completed",
1670                            error_text: None,
1671                            result_text: Some(&result),
1672                            artifact_json: Some(&artifact_json),
1673                            input_tokens,
1674                            output_tokens,
1675                        })
1676                    })
1677                    .await;
1678                    log_subagent_event(db.clone(), &run_id_for_finish, "completed", None).await;
1679                }
1680                Err(err) if err == "cancelled" => {
1681                    let rid = run_id_for_finish.clone();
1682                    let _ = call_blocking(db.clone(), move |db| {
1683                        db.mark_subagent_finished(FinishSubagentRunParams {
1684                            run_id: &rid,
1685                            status: "cancelled",
1686                            error_text: Some("Cancelled by user"),
1687                            result_text: None,
1688                            artifact_json: None,
1689                            input_tokens: 0,
1690                            output_tokens: 0,
1691                        })
1692                    })
1693                    .await;
1694                    log_subagent_event(db.clone(), &run_id_for_finish, "cancelled", None).await;
1695                }
1696                Err(err) if err == "timed_out" => {
1697                    let rid = run_id_for_finish.clone();
1698                    let _ = call_blocking(db.clone(), move |db| {
1699                        db.mark_subagent_finished(FinishSubagentRunParams {
1700                            run_id: &rid,
1701                            status: "timed_out",
1702                            error_text: Some("Sub-agent run exceeded configured timeout"),
1703                            result_text: None,
1704                            artifact_json: None,
1705                            input_tokens: 0,
1706                            output_tokens: 0,
1707                        })
1708                    })
1709                    .await;
1710                    log_subagent_event(db.clone(), &run_id_for_finish, "timed_out", None).await;
1711                }
1712                Err(err) => {
1713                    let rid = run_id_for_finish.clone();
1714                    let err_for_db = err.clone();
1715                    let status = if err_for_db.contains("budget_exceeded:") {
1716                        "budget_exceeded"
1717                    } else {
1718                        "failed"
1719                    };
1720                    let _ = call_blocking(db.clone(), move |db| {
1721                        db.mark_subagent_finished(FinishSubagentRunParams {
1722                            run_id: &rid,
1723                            status,
1724                            error_text: Some(&err_for_db),
1725                            result_text: None,
1726                            artifact_json: None,
1727                            input_tokens: 0,
1728                            output_tokens: 0,
1729                        })
1730                    })
1731                    .await;
1732                    log_subagent_event(db.clone(), &run_id_for_finish, "failed", Some(err)).await;
1733                }
1734            }
1735
1736            runtime.remove_run(&run_id_async);
1737
1738            let user_chat_announces_enabled = cfg.subagents.announce_to_chat
1739                && auth.caller_channel != "weixin"
1740                && !auth.caller_channel.starts_with("weixin.");
1741            if user_chat_announces_enabled {
1742                match build_announce_payload(db.clone(), chat_id, &run_id_async).await {
1743                    Ok(payload) => {
1744                        let rid = run_id_async.clone();
1745                        let caller_channel = auth.caller_channel.clone();
1746                        let _ = call_blocking(db.clone(), move |db| {
1747                            db.enqueue_subagent_announce(&rid, chat_id, &caller_channel, &payload)
1748                        })
1749                        .await;
1750                        let _ =
1751                            flush_pending_announces_once(&cfg, channel_registry, db.clone(), 10)
1752                                .await;
1753                    }
1754                    Err(e) => {
1755                        warn!("failed to build announce payload for run {run_id_async}: {e}");
1756                    }
1757                }
1758            }
1759
1760            // Fan-in: when this was the last active child of a parent run, post one
1761            // consolidated summary of the whole batch (opt-in).
1762            if user_chat_announces_enabled && cfg.subagents.fan_in_summary {
1763                if let Some(parent_id) = parent_run_id_async.as_ref() {
1764                    maybe_post_fan_in_summary(
1765                        &cfg,
1766                        fan_in_channel_registry,
1767                        db,
1768                        chat_id,
1769                        parent_id,
1770                    )
1771                    .await;
1772                }
1773            }
1774        });
1775
1776        info!("subagent accepted run_id={run_id} chat_id={chat_id}");
1777        crate::agent_engine::send_turn_event(
1778            &caller_channel_for_event,
1779            chat_id,
1780            crate::agent_engine::AgentEvent::SubagentStarted {
1781                run_id: run_id.clone(),
1782                label: label.clone().unwrap_or_else(|| specialist.clone()),
1783            },
1784        );
1785        ToolResult::success(
1786            json!({
1787                "status": "accepted",
1788                "run_id": run_id,
1789                "chat_id": chat_id,
1790                "depth": child_depth,
1791                "specialist": specialist,
1792                "label": label,
1793                "runtime": execution_runtime.as_str(),
1794                "runtime_target": runtime_target,
1795                "token_budget": child_token_budget,
1796                "parent_run_id": parent_run_id,
1797            })
1798            .to_string(),
1799        )
1800    }
1801}
1802
1803pub struct SubagentsListTool {
1804    db: Arc<Database>,
1805}
1806
1807impl SubagentsListTool {
1808    pub fn new(db: Arc<Database>) -> Self {
1809        Self { db }
1810    }
1811}
1812
1813#[async_trait]
1814impl Tool for SubagentsListTool {
1815    fn name(&self) -> &str {
1816        "subagents_list"
1817    }
1818
1819    fn definition(&self) -> ToolDefinition {
1820        ToolDefinition {
1821            name: "subagents_list".into(),
1822            description: "List recent subagent runs for the current chat.".into(),
1823            input_schema: schema_object(
1824                json!({
1825                    "chat_id": {"type": "integer"},
1826                    "limit": {"type": "integer", "minimum": 1, "maximum": 100}
1827                }),
1828                &[],
1829            ),
1830        }
1831    }
1832
1833    async fn execute(&self, input: serde_json::Value) -> ToolResult {
1834        let auth =
1835            match auth_context_from_input(&input) {
1836                Some(v) => v,
1837                None => return ToolResult::error(
1838                    "subagents_list requires caller auth context; run from an active chat session"
1839                        .into(),
1840                ),
1841            };
1842        let chat_id = input
1843            .get("chat_id")
1844            .and_then(|v| v.as_i64())
1845            .unwrap_or(auth.caller_chat_id);
1846        if let Err(e) = authorize_chat_access(&input, chat_id) {
1847            return ToolResult::error(e);
1848        }
1849        let limit = input
1850            .get("limit")
1851            .and_then(|v| v.as_u64())
1852            .unwrap_or(20)
1853            .clamp(1, 100) as usize;
1854
1855        let rows = match call_blocking(self.db.clone(), move |db| {
1856            db.list_subagent_runs(chat_id, limit)
1857        })
1858        .await
1859        {
1860            Ok(v) => v,
1861            Err(e) => return ToolResult::error(format!("Failed listing subagent runs: {e}")),
1862        };
1863        let payload: Vec<serde_json::Value> = rows
1864            .into_iter()
1865            .map(|r| {
1866                json!({
1867                    "run_id": r.run_id,
1868                    "label": r.label,
1869                    "parent_run_id": r.parent_run_id,
1870                    "depth": r.depth,
1871                    "token_budget": r.token_budget,
1872                    "status": r.status,
1873                    "created_at": r.created_at,
1874                    "started_at": r.started_at,
1875                    "finished_at": r.finished_at,
1876                    "cancel_requested": r.cancel_requested,
1877                    "task": r.task,
1878                    "progress": r.progress_text,
1879                    "last_progress_at": r.last_progress_at,
1880                    "input_tokens": r.input_tokens,
1881                    "output_tokens": r.output_tokens,
1882                    "artifact_json": r.artifact_json,
1883                })
1884            })
1885            .collect();
1886
1887        ToolResult::success(json!({"chat_id": chat_id, "runs": payload}).to_string())
1888    }
1889}
1890
1891/// Resolve a run reference (exact run_id or human-friendly label) to a run_id
1892/// within the given chat. Shared by subagents_info / subagents_kill.
1893async fn resolve_subagent_ref(
1894    db: &Arc<Database>,
1895    chat_id: i64,
1896    run_ref: &str,
1897) -> Result<Option<String>, String> {
1898    let run_ref_owned = run_ref.to_string();
1899    call_blocking(db.clone(), move |db| {
1900        db.resolve_subagent_run_id(chat_id, &run_ref_owned)
1901    })
1902    .await
1903    .map_err(|e| format!("Failed resolving subagent reference: {e}"))
1904}
1905
1906pub struct SubagentsInfoTool {
1907    db: Arc<Database>,
1908}
1909
1910impl SubagentsInfoTool {
1911    pub fn new(db: Arc<Database>) -> Self {
1912        Self { db }
1913    }
1914}
1915
1916#[async_trait]
1917impl Tool for SubagentsInfoTool {
1918    fn name(&self) -> &str {
1919        "subagents_info"
1920    }
1921
1922    fn definition(&self) -> ToolDefinition {
1923        ToolDefinition {
1924            name: "subagents_info".into(),
1925            description: "Get detailed information for one subagent run, by run id or task label."
1926                .into(),
1927            input_schema: schema_object(
1928                json!({
1929                    "run_id": {"type": "string", "description": "Run id or the task label given at spawn."},
1930                    "chat_id": {"type": "integer"}
1931                }),
1932                &["run_id"],
1933            ),
1934        }
1935    }
1936
1937    async fn execute(&self, input: serde_json::Value) -> ToolResult {
1938        let auth =
1939            match auth_context_from_input(&input) {
1940                Some(v) => v,
1941                None => return ToolResult::error(
1942                    "subagents_info requires caller auth context; run from an active chat session"
1943                        .into(),
1944                ),
1945            };
1946        let chat_id = input
1947            .get("chat_id")
1948            .and_then(|v| v.as_i64())
1949            .unwrap_or(auth.caller_chat_id);
1950        if let Err(e) = authorize_chat_access(&input, chat_id) {
1951            return ToolResult::error(e);
1952        }
1953        let run_ref = match input.get("run_id").and_then(|v| v.as_str()) {
1954            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
1955            _ => return ToolResult::error("Missing required parameter: run_id".into()),
1956        };
1957        let run_id = match resolve_subagent_ref(&self.db, chat_id, &run_ref).await {
1958            Ok(Some(v)) => v,
1959            Ok(None) => return ToolResult::error(format!("No subagent run matching '{run_ref}'")),
1960            Err(e) => return ToolResult::error(e),
1961        };
1962
1963        let run = match call_blocking(self.db.clone(), move |db| {
1964            db.get_subagent_run(&run_id, chat_id)
1965        })
1966        .await
1967        {
1968            Ok(Some(v)) => v,
1969            Ok(None) => return ToolResult::error("Subagent run not found".into()),
1970            Err(e) => return ToolResult::error(format!("Failed reading subagent run: {e}")),
1971        };
1972
1973        ToolResult::success(
1974            json!({
1975                "run_id": run.run_id,
1976                "label": run.label,
1977                "parent_run_id": run.parent_run_id,
1978                "depth": run.depth,
1979                "chat_id": run.chat_id,
1980                "caller_channel": run.caller_channel,
1981                "task": run.task,
1982                "context": run.context,
1983                "status": run.status,
1984                "created_at": run.created_at,
1985                "started_at": run.started_at,
1986                "finished_at": run.finished_at,
1987                "cancel_requested": run.cancel_requested,
1988                "progress": run.progress_text,
1989                "last_progress_at": run.last_progress_at,
1990                "error_text": run.error_text,
1991                "result_text": run.result_text,
1992                "input_tokens": run.input_tokens,
1993                "output_tokens": run.output_tokens,
1994                "total_tokens": run.total_tokens,
1995                "provider": run.provider,
1996                "model": run.model,
1997                "token_budget": run.token_budget,
1998                "artifact_json": run.artifact_json,
1999            })
2000            .to_string(),
2001        )
2002    }
2003}
2004
2005pub struct SubagentsKillTool {
2006    config: Config,
2007    db: Arc<Database>,
2008}
2009
2010impl SubagentsKillTool {
2011    pub fn new(config: &Config, db: Arc<Database>) -> Self {
2012        Self {
2013            config: config.clone(),
2014            db,
2015        }
2016    }
2017}
2018
2019#[async_trait]
2020impl Tool for SubagentsKillTool {
2021    fn name(&self) -> &str {
2022        "subagents_kill"
2023    }
2024
2025    fn definition(&self) -> ToolDefinition {
2026        ToolDefinition {
2027            name: "subagents_kill".into(),
2028            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(),
2029            input_schema: schema_object(
2030                json!({
2031                    "run_id": {"type": "string", "description": "Run id, task label, or 'all'"},
2032                    "chat_id": {"type": "integer"}
2033                }),
2034                &["run_id"],
2035            ),
2036        }
2037    }
2038
2039    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2040        let auth =
2041            match auth_context_from_input(&input) {
2042                Some(v) => v,
2043                None => return ToolResult::error(
2044                    "subagents_kill requires caller auth context; run from an active chat session"
2045                        .into(),
2046                ),
2047            };
2048        let chat_id = input
2049            .get("chat_id")
2050            .and_then(|v| v.as_i64())
2051            .unwrap_or(auth.caller_chat_id);
2052        if let Err(e) = authorize_chat_access(&input, chat_id) {
2053            return ToolResult::error(e);
2054        }
2055        let run_ref = match input.get("run_id").and_then(|v| v.as_str()) {
2056            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2057            _ => return ToolResult::error("Missing required parameter: run_id".into()),
2058        };
2059
2060        let runtime = subagent_runtime(&self.config);
2061
2062        if run_ref.eq_ignore_ascii_case("all") {
2063            let rows = match call_blocking(self.db.clone(), move |db| {
2064                db.list_subagent_runs(chat_id, 200)
2065            })
2066            .await
2067            {
2068                Ok(v) => v,
2069                Err(e) => return ToolResult::error(format!("Failed listing subagent runs: {e}")),
2070            };
2071            let mut cancelled = 0usize;
2072            for row in rows {
2073                if matches!(row.status.as_str(), "accepted" | "queued" | "running") {
2074                    let rid = row.run_id.clone();
2075                    let requested = call_blocking(self.db.clone(), move |db| {
2076                        db.request_subagent_cancel(&rid, chat_id)
2077                    })
2078                    .await
2079                    .unwrap_or(false);
2080                    if requested {
2081                        runtime.cancel_run(&row.run_id);
2082                        log_subagent_event(
2083                            self.db.clone(),
2084                            &row.run_id,
2085                            "cancel_requested",
2086                            Some("kill_all".to_string()),
2087                        )
2088                        .await;
2089                        cancelled += 1;
2090                    }
2091                }
2092            }
2093            return ToolResult::success(
2094                json!({"status": "ok", "cancelled": cancelled, "chat_id": chat_id}).to_string(),
2095            );
2096        }
2097
2098        let run_id = match resolve_subagent_ref(&self.db, chat_id, &run_ref).await {
2099            Ok(Some(v)) => v,
2100            Ok(None) => return ToolResult::error(format!("No subagent run matching '{run_ref}'")),
2101            Err(e) => return ToolResult::error(e),
2102        };
2103
2104        let run_id_for_db = run_id.clone();
2105        let requested = match call_blocking(self.db.clone(), move |db| {
2106            db.request_subagent_cancel(&run_id_for_db, chat_id)
2107        })
2108        .await
2109        {
2110            Ok(v) => v,
2111            Err(e) => {
2112                return ToolResult::error(format!("Failed requesting cancellation: {e}"));
2113            }
2114        };
2115
2116        if !requested {
2117            return ToolResult::error("Subagent run not found or already finished".into());
2118        }
2119        runtime.cancel_run(&run_id);
2120        log_subagent_event(
2121            self.db.clone(),
2122            &run_id,
2123            "cancel_requested",
2124            Some("kill_one".to_string()),
2125        )
2126        .await;
2127        ToolResult::success(json!({"status": "ok", "run_id": run_id}).to_string())
2128    }
2129}
2130
2131pub struct SubagentsRetryAnnouncesTool {
2132    config: Config,
2133    db: Arc<Database>,
2134    channel_registry: Arc<ChannelRegistry>,
2135}
2136
2137pub struct SubagentsFocusTool {
2138    db: Arc<Database>,
2139}
2140
2141impl SubagentsFocusTool {
2142    pub fn new(db: Arc<Database>) -> Self {
2143        Self { db }
2144    }
2145}
2146
2147#[async_trait]
2148impl Tool for SubagentsFocusTool {
2149    fn name(&self) -> &str {
2150        "subagents_focus"
2151    }
2152
2153    fn definition(&self) -> ToolDefinition {
2154        ToolDefinition {
2155            name: "subagents_focus".into(),
2156            description: "Bind the current chat to a subagent run for follow-up actions.".into(),
2157            input_schema: schema_object(
2158                json!({
2159                    "run_id": {"type":"string"},
2160                    "chat_id": {"type":"integer"}
2161                }),
2162                &["run_id"],
2163            ),
2164        }
2165    }
2166
2167    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2168        let auth = match auth_context_from_input(&input) {
2169            Some(v) => v,
2170            None => {
2171                return ToolResult::error("subagents_focus requires caller auth context".into())
2172            }
2173        };
2174        let chat_id = input
2175            .get("chat_id")
2176            .and_then(|v| v.as_i64())
2177            .unwrap_or(auth.caller_chat_id);
2178        if let Err(e) = authorize_chat_access(&input, chat_id) {
2179            return ToolResult::error(e);
2180        }
2181        let run_id = match input.get("run_id").and_then(|v| v.as_str()) {
2182            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2183            _ => return ToolResult::error("Missing required parameter: run_id".into()),
2184        };
2185        let run_id_for_check = run_id.clone();
2186        let exists = match call_blocking(self.db.clone(), move |db| {
2187            db.get_subagent_run(&run_id_for_check, chat_id)
2188        })
2189        .await
2190        {
2191            Ok(v) => v.is_some(),
2192            Err(e) => return ToolResult::error(format!("Failed reading subagent run: {e}")),
2193        };
2194        if !exists {
2195            return ToolResult::error("Subagent run not found".into());
2196        }
2197        let run_id_for_set = run_id.clone();
2198        if let Err(e) = call_blocking(self.db.clone(), move |db| {
2199            db.set_subagent_focus(chat_id, &run_id_for_set)
2200        })
2201        .await
2202        {
2203            return ToolResult::error(format!("Failed setting subagent focus: {e}"));
2204        }
2205        ToolResult::success(json!({"status":"ok","chat_id":chat_id,"run_id":run_id}).to_string())
2206    }
2207}
2208
2209pub struct SubagentsUnfocusTool {
2210    db: Arc<Database>,
2211}
2212
2213impl SubagentsUnfocusTool {
2214    pub fn new(db: Arc<Database>) -> Self {
2215        Self { db }
2216    }
2217}
2218
2219#[async_trait]
2220impl Tool for SubagentsUnfocusTool {
2221    fn name(&self) -> &str {
2222        "subagents_unfocus"
2223    }
2224
2225    fn definition(&self) -> ToolDefinition {
2226        ToolDefinition {
2227            name: "subagents_unfocus".into(),
2228            description: "Clear focused subagent binding for the current chat.".into(),
2229            input_schema: schema_object(
2230                json!({
2231                    "chat_id": {"type":"integer"}
2232                }),
2233                &[],
2234            ),
2235        }
2236    }
2237
2238    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2239        let auth = match auth_context_from_input(&input) {
2240            Some(v) => v,
2241            None => {
2242                return ToolResult::error("subagents_unfocus requires caller auth context".into())
2243            }
2244        };
2245        let chat_id = input
2246            .get("chat_id")
2247            .and_then(|v| v.as_i64())
2248            .unwrap_or(auth.caller_chat_id);
2249        if let Err(e) = authorize_chat_access(&input, chat_id) {
2250            return ToolResult::error(e);
2251        }
2252        if let Err(e) =
2253            call_blocking(self.db.clone(), move |db| db.clear_subagent_focus(chat_id)).await
2254        {
2255            return ToolResult::error(format!("Failed clearing subagent focus: {e}"));
2256        }
2257        ToolResult::success(json!({"status":"ok","chat_id":chat_id}).to_string())
2258    }
2259}
2260
2261pub struct SubagentsFocusedTool {
2262    db: Arc<Database>,
2263}
2264
2265impl SubagentsFocusedTool {
2266    pub fn new(db: Arc<Database>) -> Self {
2267        Self { db }
2268    }
2269}
2270
2271#[async_trait]
2272impl Tool for SubagentsFocusedTool {
2273    fn name(&self) -> &str {
2274        "subagents_focused"
2275    }
2276
2277    fn definition(&self) -> ToolDefinition {
2278        ToolDefinition {
2279            name: "subagents_focused".into(),
2280            description: "Show focused subagent binding for current chat.".into(),
2281            input_schema: schema_object(
2282                json!({
2283                    "chat_id": {"type":"integer"}
2284                }),
2285                &[],
2286            ),
2287        }
2288    }
2289
2290    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2291        let auth = match auth_context_from_input(&input) {
2292            Some(v) => v,
2293            None => {
2294                return ToolResult::error("subagents_focused requires caller auth context".into())
2295            }
2296        };
2297        let chat_id = input
2298            .get("chat_id")
2299            .and_then(|v| v.as_i64())
2300            .unwrap_or(auth.caller_chat_id);
2301        if let Err(e) = authorize_chat_access(&input, chat_id) {
2302            return ToolResult::error(e);
2303        }
2304        let focused =
2305            match call_blocking(self.db.clone(), move |db| db.get_subagent_focus(chat_id)).await {
2306                Ok(v) => v,
2307                Err(e) => return ToolResult::error(format!("Failed loading subagent focus: {e}")),
2308            };
2309        ToolResult::success(json!({"chat_id":chat_id,"run_id":focused}).to_string())
2310    }
2311}
2312
2313pub struct SubagentsSendTool {
2314    config: Config,
2315    db: Arc<Database>,
2316    channel_registry: Arc<ChannelRegistry>,
2317}
2318
2319impl SubagentsSendTool {
2320    pub fn new(config: &Config, db: Arc<Database>, channel_registry: Arc<ChannelRegistry>) -> Self {
2321        Self {
2322            config: config.clone(),
2323            db,
2324            channel_registry,
2325        }
2326    }
2327}
2328
2329#[async_trait]
2330impl Tool for SubagentsSendTool {
2331    fn name(&self) -> &str {
2332        "subagents_send"
2333    }
2334
2335    fn definition(&self) -> ToolDefinition {
2336        ToolDefinition {
2337            name: "subagents_send".into(),
2338            description:
2339                "Send follow-up work to focused subagent by spawning a child continuation run."
2340                    .into(),
2341            input_schema: schema_object(
2342                json!({
2343                    "message": {"type":"string"},
2344                    "chat_id": {"type":"integer"}
2345                }),
2346                &["message"],
2347            ),
2348        }
2349    }
2350
2351    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2352        let auth = match auth_context_from_input(&input) {
2353            Some(v) => v,
2354            None => return ToolResult::error("subagents_send requires caller auth context".into()),
2355        };
2356        let chat_id = input
2357            .get("chat_id")
2358            .and_then(|v| v.as_i64())
2359            .unwrap_or(auth.caller_chat_id);
2360        if let Err(e) = authorize_chat_access(&input, chat_id) {
2361            return ToolResult::error(e);
2362        }
2363        let message = match input.get("message").and_then(|v| v.as_str()) {
2364            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2365            _ => return ToolResult::error("Missing required parameter: message".into()),
2366        };
2367        let focused_run =
2368            match call_blocking(self.db.clone(), move |db| db.get_subagent_focus(chat_id)).await {
2369                Ok(Some(v)) => v,
2370                Ok(None) => return ToolResult::error("No focused subagent for this chat".into()),
2371                Err(e) => return ToolResult::error(format!("Failed loading subagent focus: {e}")),
2372            };
2373        let focused_run_for_load = focused_run.clone();
2374        let parent = match call_blocking(self.db.clone(), move |db| {
2375            db.get_subagent_run(&focused_run_for_load, chat_id)
2376        })
2377        .await
2378        {
2379            Ok(Some(v)) => v,
2380            Ok(None) => return ToolResult::error("Focused subagent run not found".into()),
2381            Err(e) => return ToolResult::error(format!("Failed loading focused subagent: {e}")),
2382        };
2383
2384        let spawn_tool =
2385            SessionsSpawnTool::new(&self.config, self.db.clone(), self.channel_registry.clone());
2386        let remaining_budget = (parent.token_budget - parent.total_tokens).max(0);
2387        let parent_runtime = if parent.provider.starts_with("acp") {
2388            "acp"
2389        } else {
2390            "native"
2391        };
2392        let spawn_input = json!({
2393            "task": format!("Continuation request: {message}"),
2394            "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),
2395            "__microclaw_auth": {
2396                "caller_channel": auth.caller_channel,
2397                "caller_chat_id": chat_id,
2398                "control_chat_ids": auth.control_chat_ids,
2399                "env_files": auth.env_files,
2400            },
2401            "__subagent_runtime": {
2402                "run_id": parent.run_id,
2403                "depth": parent.depth,
2404                "runtime": parent_runtime,
2405                "runtime_target": crate::acp_subagent::acp_runtime_target_from_provider(&parent.provider),
2406                "token_budget_remaining": remaining_budget,
2407            }
2408        });
2409        spawn_tool.execute(spawn_input).await
2410    }
2411}
2412
2413pub struct SubagentsLogTool {
2414    db: Arc<Database>,
2415}
2416
2417/// One orchestrate work package: a task plus its optional completion contract.
2418struct OrchestratePackage {
2419    task: String,
2420    exit_criteria: Vec<crate::completion_contract::ExitCriterion>,
2421}
2422
2423/// Marker prefix a failed contract leaves at the head of result_text
2424/// (produced by completion_contract::render_report).
2425const CONTRACT_FAILED_MARKER: &str = "[completion contract] FAILED";
2426
2427pub struct SubagentsOrchestrateTool {
2428    config: Config,
2429    db: Arc<Database>,
2430    channel_registry: Arc<ChannelRegistry>,
2431}
2432
2433impl SubagentsOrchestrateTool {
2434    pub fn new(config: &Config, db: Arc<Database>, channel_registry: Arc<ChannelRegistry>) -> Self {
2435        Self {
2436            config: config.clone(),
2437            db,
2438            channel_registry,
2439        }
2440    }
2441
2442    fn merge_run_artifacts(
2443        runs: &[crate::internal::storage::db::SubagentRunRecord],
2444    ) -> serde_json::Value {
2445        let mut summaries = Vec::new();
2446        let mut findings = BTreeSet::new();
2447        let mut next_actions = BTreeSet::new();
2448        let mut artifacts = Vec::new();
2449        for run in runs {
2450            let Some(raw) = run.artifact_json.as_deref() else {
2451                continue;
2452            };
2453            let Ok(v) = serde_json::from_str::<serde_json::Value>(raw) else {
2454                continue;
2455            };
2456            if let Some(s) = v.get("summary").and_then(|x| x.as_str()) {
2457                if !s.trim().is_empty() {
2458                    summaries.push(s.trim().to_string());
2459                }
2460            }
2461            if let Some(arr) = v.get("findings").and_then(|x| x.as_array()) {
2462                for f in arr.iter().filter_map(|x| x.as_str()) {
2463                    if !f.trim().is_empty() {
2464                        findings.insert(f.trim().to_string());
2465                    }
2466                }
2467            }
2468            if let Some(arr) = v.get("next_actions").and_then(|x| x.as_array()) {
2469                for n in arr.iter().filter_map(|x| x.as_str()) {
2470                    if !n.trim().is_empty() {
2471                        next_actions.insert(n.trim().to_string());
2472                    }
2473                }
2474            }
2475            if let Some(arr) = v.get("artifacts").and_then(|x| x.as_array()) {
2476                artifacts.extend(arr.iter().cloned());
2477            }
2478        }
2479        json!({
2480            "protocol": "orchestrate_merge_v1",
2481            "summary": summaries,
2482            "findings": findings.into_iter().collect::<Vec<_>>(),
2483            "next_actions": next_actions.into_iter().collect::<Vec<_>>(),
2484            "artifacts": artifacts,
2485        })
2486    }
2487}
2488
2489#[async_trait]
2490impl Tool for SubagentsOrchestrateTool {
2491    fn name(&self) -> &str {
2492        "subagents_orchestrate"
2493    }
2494
2495    fn definition(&self) -> ToolDefinition {
2496        ToolDefinition {
2497            name: "subagents_orchestrate".into(),
2498            description: "Depth=2 orchestration template: spawn multiple worker runs and optionally wait+merge structured artifacts.".into(),
2499            input_schema: schema_object(
2500                json!({
2501                    "goal": {"type":"string"},
2502                    "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)."},
2503                    "chat_id": {"type":"integer"},
2504                    "wait": {"type":"boolean"},
2505                    "wait_timeout_secs": {"type":"integer", "minimum":1, "maximum":1200},
2506                    "token_budget_total": {"type":"integer", "minimum":2000}
2507                }),
2508                &["goal", "work_packages"],
2509            ),
2510        }
2511    }
2512
2513    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2514        let auth = match auth_context_from_input(&input) {
2515            Some(v) => v,
2516            None => {
2517                return ToolResult::error(
2518                    "subagents_orchestrate requires caller auth context".into(),
2519                )
2520            }
2521        };
2522        let chat_id = input
2523            .get("chat_id")
2524            .and_then(|v| v.as_i64())
2525            .unwrap_or(auth.caller_chat_id);
2526        if let Err(e) = authorize_chat_access(&input, chat_id) {
2527            return ToolResult::error(e);
2528        }
2529        let goal = match input.get("goal").and_then(|v| v.as_str()) {
2530            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2531            _ => return ToolResult::error("Missing required parameter: goal".into()),
2532        };
2533        let raw_packages = input
2534            .get("work_packages")
2535            .and_then(|v| v.as_array())
2536            .cloned()
2537            .unwrap_or_default();
2538        let mut packages: Vec<OrchestratePackage> = Vec::new();
2539        for (i, v) in raw_packages.iter().enumerate() {
2540            if let Some(task) = v.as_str() {
2541                if !task.trim().is_empty() {
2542                    packages.push(OrchestratePackage {
2543                        task: task.trim().to_string(),
2544                        exit_criteria: Vec::new(),
2545                    });
2546                }
2547                continue;
2548            }
2549            if v.is_object() {
2550                let task = v
2551                    .get("task")
2552                    .and_then(|t| t.as_str())
2553                    .map(str::trim)
2554                    .unwrap_or_default()
2555                    .to_string();
2556                if task.is_empty() {
2557                    return ToolResult::error(format!(
2558                        "work_packages[{i}] object is missing a non-empty `task`"
2559                    ));
2560                }
2561                let exit_criteria =
2562                    match crate::completion_contract::parse_exit_criteria(v.get("exit_criteria")) {
2563                        Ok(c) => c,
2564                        Err(e) => {
2565                            return ToolResult::error(format!("work_packages[{i}]: {e}"));
2566                        }
2567                    };
2568                packages.push(OrchestratePackage {
2569                    task,
2570                    exit_criteria,
2571                });
2572                continue;
2573            }
2574            return ToolResult::error(format!(
2575                "work_packages[{i}] must be a string or an object {{task, exit_criteria?}}"
2576            ));
2577        }
2578        if packages.is_empty() {
2579            return ToolResult::error("work_packages must include at least one item".into());
2580        }
2581        let max_workers = self
2582            .config
2583            .subagents
2584            .orchestrate_max_workers
2585            .min(self.config.subagents.max_children_per_run);
2586        let wait = input.get("wait").and_then(|v| v.as_bool()).unwrap_or(false);
2587        let wait_timeout_secs = input
2588            .get("wait_timeout_secs")
2589            .and_then(|v| v.as_u64())
2590            .unwrap_or(120)
2591            .clamp(1, 1200);
2592        let total_budget = input
2593            .get("token_budget_total")
2594            .and_then(|v| v.as_i64())
2595            .filter(|v| *v > 0)
2596            .unwrap_or(self.config.subagents.max_tokens_per_run);
2597        let parent_run_id = input
2598            .get("__subagent_runtime")
2599            .and_then(|v| v.get("run_id"))
2600            .and_then(|v| v.as_str())
2601            .map(str::to_string);
2602        let parent_meta = subagent_runtime_meta_from_input(&input);
2603        let parent_remaining = parent_meta.as_ref().and_then(|m| m.token_budget_remaining);
2604        let total_budget = if let Some(remaining) = parent_remaining {
2605            total_budget.min(remaining.max(0))
2606        } else {
2607            total_budget
2608        };
2609        if total_budget < 2_000 {
2610            return ToolResult::error(format!(
2611                "subagent budget exhausted for orchestration: remaining {} < 2000",
2612                total_budget
2613            ));
2614        }
2615        let max_workers_by_budget = (total_budget / 2_000).max(1) as usize;
2616        let allowed_workers = max_workers.min(max_workers_by_budget).max(1);
2617        if packages.len() > allowed_workers {
2618            packages.truncate(allowed_workers);
2619        }
2620        let each_budget = (total_budget / packages.len() as i64).clamp(2_000, total_budget);
2621
2622        let spawn_tool =
2623            SessionsSpawnTool::new(&self.config, self.db.clone(), self.channel_registry.clone());
2624        let mut spawned = Vec::new();
2625        for (idx, pkg) in packages.iter().enumerate() {
2626            let mut spawn_input = json!({
2627                "task": format!("Work package {}: {}", idx + 1, pkg.task),
2628                "context": format!(
2629                    "Orchestration goal: {goal}\nOutput strictly in protocol subagent_artifact_v1 with keys summary/findings/artifacts/next_actions/final_answer."
2630                ),
2631                "chat_id": chat_id,
2632                "token_budget": each_budget,
2633                "__microclaw_auth": {
2634                    "caller_channel": auth.caller_channel.clone(),
2635                    "caller_chat_id": chat_id,
2636                    "control_chat_ids": auth.control_chat_ids.clone(),
2637                    "env_files": auth.env_files.clone(),
2638                }
2639            });
2640            if !pkg.exit_criteria.is_empty() {
2641                if let Some(obj) = spawn_input.as_object_mut() {
2642                    obj.insert(
2643                        "exit_criteria".to_string(),
2644                        serde_json::to_value(&pkg.exit_criteria).unwrap_or_default(),
2645                    );
2646                }
2647            }
2648            let spawn_input = if let (Some(meta), Some(parent_run_id)) =
2649                (parent_meta.as_ref(), parent_run_id.as_deref())
2650            {
2651                let mut obj = spawn_input
2652                    .as_object()
2653                    .cloned()
2654                    .unwrap_or_else(serde_json::Map::new);
2655                obj.insert(
2656                    "__subagent_runtime".to_string(),
2657                    json!({
2658                        "run_id": parent_run_id,
2659                        "depth": meta.depth,
2660                        "runtime": meta.runtime.as_deref().unwrap_or("native"),
2661                        "runtime_target": meta.runtime_target.clone(),
2662                        "token_budget_remaining": each_budget,
2663                    }),
2664                );
2665                serde_json::Value::Object(obj)
2666            } else {
2667                spawn_input
2668            };
2669            let res = spawn_tool.execute(spawn_input).await;
2670            if res.is_error {
2671                return res;
2672            }
2673            let parsed = match serde_json::from_str::<serde_json::Value>(&res.content) {
2674                Ok(v) => v,
2675                Err(e) => return ToolResult::error(format!("Invalid sessions_spawn output: {e}")),
2676            };
2677            let run_id = match parsed.get("run_id").and_then(|v| v.as_str()) {
2678                Some(v) => v.to_string(),
2679                None => return ToolResult::error("sessions_spawn did not return run_id".into()),
2680            };
2681            spawned.push(run_id);
2682        }
2683
2684        if !wait {
2685            return ToolResult::success(
2686                json!({
2687                    "status": "accepted",
2688                    "chat_id": chat_id,
2689                    "goal": goal,
2690                    "workers": spawned.len(),
2691                    "run_ids": spawned,
2692                    "token_budget_total": total_budget,
2693                    "token_budget_each": each_budget,
2694                })
2695                .to_string(),
2696            );
2697        }
2698
2699        let deadline =
2700            std::time::Instant::now() + std::time::Duration::from_secs(wait_timeout_secs);
2701        let mut runs = Vec::new();
2702        let mut wait_timed_out = false;
2703        while std::time::Instant::now() < deadline {
2704            let ids = spawned.clone();
2705            let rows = match call_blocking(self.db.clone(), move |db| {
2706                let mut out = Vec::new();
2707                for run_id in ids {
2708                    if let Some(row) = db.get_subagent_run(&run_id, chat_id)? {
2709                        out.push(row);
2710                    }
2711                }
2712                Ok::<_, microclaw_core::error::MicroClawError>(out)
2713            })
2714            .await
2715            {
2716                Ok(v) => v,
2717                Err(e) => return ToolResult::error(format!("Failed loading runs: {e}")),
2718            };
2719            let done = rows
2720                .iter()
2721                .all(|r| !matches!(r.status.as_str(), "accepted" | "queued" | "running"));
2722            runs = rows;
2723            if done {
2724                break;
2725            }
2726            tokio::time::sleep(std::time::Duration::from_secs(2)).await;
2727        }
2728        if runs
2729            .iter()
2730            .any(|r| matches!(r.status.as_str(), "accepted" | "queued" | "running"))
2731        {
2732            wait_timed_out = true;
2733        }
2734
2735        // Contract-aware fan-in retry: a completed worker whose result carries
2736        // the FAILED contract marker gets exactly ONE replacement run, spawned
2737        // with the failure evidence as extra context. (The in-run bounded
2738        // retry has already happened inside the worker, so this catches the
2739        // cases where the worker gave up.)
2740        let mut retried: Vec<serde_json::Value> = Vec::new();
2741        if !wait_timed_out {
2742            let mut replacements: Vec<(usize, String)> = Vec::new(); // (runs idx, new run_id)
2743            for (idx, run) in runs.iter().enumerate() {
2744                if run.status != "completed" {
2745                    continue;
2746                }
2747                let Some(result_text) = run.result_text.as_deref() else {
2748                    continue;
2749                };
2750                if !result_text.trim_start().starts_with(CONTRACT_FAILED_MARKER) {
2751                    continue;
2752                }
2753                // Recover the package (spawn order matches `packages`).
2754                let Some(pkg_idx) = spawned.iter().position(|id| *id == run.run_id) else {
2755                    continue;
2756                };
2757                let Some(pkg) = packages.get(pkg_idx) else {
2758                    continue;
2759                };
2760                let evidence_end = microclaw_core::text::floor_char_boundary(result_text, 600);
2761                let mut spawn_input = json!({
2762                    "task": format!("Work package {} (retry): {}", pkg_idx + 1, pkg.task),
2763                    "context": format!(
2764                        "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.",
2765                        &result_text[..evidence_end]
2766                    ),
2767                    "chat_id": chat_id,
2768                    "token_budget": each_budget,
2769                    "exit_criteria": serde_json::to_value(&pkg.exit_criteria).unwrap_or_default(),
2770                    "__microclaw_auth": {
2771                        "caller_channel": auth.caller_channel.clone(),
2772                        "caller_chat_id": chat_id,
2773                        "control_chat_ids": auth.control_chat_ids.clone(),
2774                        "env_files": auth.env_files.clone(),
2775                    }
2776                });
2777                if let (Some(meta), Some(parent_run_id)) =
2778                    (parent_meta.as_ref(), parent_run_id.as_deref())
2779                {
2780                    if let Some(obj) = spawn_input.as_object_mut() {
2781                        obj.insert(
2782                            "__subagent_runtime".to_string(),
2783                            json!({
2784                                "run_id": parent_run_id,
2785                                "depth": meta.depth,
2786                                "runtime": meta.runtime.as_deref().unwrap_or("native"),
2787                                "runtime_target": meta.runtime_target.clone(),
2788                                "token_budget_remaining": each_budget,
2789                            }),
2790                        );
2791                    }
2792                }
2793                let res = spawn_tool.execute(spawn_input).await;
2794                if res.is_error {
2795                    // Budget/depth exhausted: keep the failed result as-is.
2796                    continue;
2797                }
2798                let new_run_id = serde_json::from_str::<serde_json::Value>(&res.content)
2799                    .ok()
2800                    .and_then(|v| v.get("run_id").and_then(|r| r.as_str()).map(str::to_string));
2801                if let Some(new_run_id) = new_run_id {
2802                    retried.push(json!({
2803                        "package": pkg_idx + 1,
2804                        "failed_run_id": run.run_id.clone(),
2805                        "retry_run_id": new_run_id.clone(),
2806                    }));
2807                    replacements.push((idx, new_run_id));
2808                }
2809            }
2810
2811            if !replacements.is_empty() {
2812                // Wait for the replacement runs within the remaining deadline.
2813                let retry_ids: Vec<String> =
2814                    replacements.iter().map(|(_, id)| id.clone()).collect();
2815                loop {
2816                    let ids = retry_ids.clone();
2817                    let rows = match call_blocking(self.db.clone(), move |db| {
2818                        let mut out = Vec::new();
2819                        for run_id in ids {
2820                            if let Some(row) = db.get_subagent_run(&run_id, chat_id)? {
2821                                out.push(row);
2822                            }
2823                        }
2824                        Ok::<_, microclaw_core::error::MicroClawError>(out)
2825                    })
2826                    .await
2827                    {
2828                        Ok(v) => v,
2829                        Err(e) => return ToolResult::error(format!("Failed loading runs: {e}")),
2830                    };
2831                    let done = rows
2832                        .iter()
2833                        .all(|r| !matches!(r.status.as_str(), "accepted" | "queued" | "running"));
2834                    if done {
2835                        // Swap the finished replacements into the merge set.
2836                        for (idx, retry_id) in &replacements {
2837                            if let Some(row) = rows.iter().find(|r| r.run_id == *retry_id) {
2838                                runs[*idx] = row.clone();
2839                            }
2840                        }
2841                        break;
2842                    }
2843                    if std::time::Instant::now() >= deadline {
2844                        wait_timed_out = true;
2845                        break;
2846                    }
2847                    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
2848                }
2849            }
2850        }
2851
2852        let merged = Self::merge_run_artifacts(&runs);
2853        ToolResult::success(
2854            json!({
2855                "status": if wait_timed_out { "timeout_partial" } else { "merged" },
2856                "chat_id": chat_id,
2857                "goal": goal,
2858                "workers": spawned.len(),
2859                "run_ids": spawned,
2860                "retried": retried,
2861                "runs": runs.into_iter().map(|r| json!({
2862                    "run_id": r.run_id,
2863                    "status": r.status,
2864                    "depth": r.depth,
2865                    "token_budget": r.token_budget,
2866                    "total_tokens": r.total_tokens,
2867                    "artifact_json": r.artifact_json,
2868                })).collect::<Vec<_>>(),
2869                "merged": merged,
2870            })
2871            .to_string(),
2872        )
2873    }
2874}
2875
2876impl SubagentsLogTool {
2877    pub fn new(db: Arc<Database>) -> Self {
2878        Self { db }
2879    }
2880}
2881
2882#[async_trait]
2883impl Tool for SubagentsLogTool {
2884    fn name(&self) -> &str {
2885        "subagents_log"
2886    }
2887
2888    fn definition(&self) -> ToolDefinition {
2889        ToolDefinition {
2890            name: "subagents_log".into(),
2891            description: "Get timeline events for one subagent run.".into(),
2892            input_schema: schema_object(
2893                json!({
2894                    "run_id": {"type":"string"},
2895                    "chat_id": {"type":"integer"},
2896                    "limit": {"type":"integer", "minimum":1, "maximum":200}
2897                }),
2898                &["run_id"],
2899            ),
2900        }
2901    }
2902
2903    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2904        let auth = match auth_context_from_input(&input) {
2905            Some(v) => v,
2906            None => return ToolResult::error("subagents_log requires caller auth context".into()),
2907        };
2908        let chat_id = input
2909            .get("chat_id")
2910            .and_then(|v| v.as_i64())
2911            .unwrap_or(auth.caller_chat_id);
2912        if let Err(e) = authorize_chat_access(&input, chat_id) {
2913            return ToolResult::error(e);
2914        }
2915        let run_id = match input.get("run_id").and_then(|v| v.as_str()) {
2916            Some(v) if !v.trim().is_empty() => v.trim().to_string(),
2917            _ => return ToolResult::error("Missing required parameter: run_id".into()),
2918        };
2919        let run_id_for_check = run_id.clone();
2920        let run_exists = match call_blocking(self.db.clone(), move |db| {
2921            db.get_subagent_run(&run_id_for_check, chat_id)
2922        })
2923        .await
2924        {
2925            Ok(v) => v.is_some(),
2926            Err(e) => return ToolResult::error(format!("Failed reading subagent run: {e}")),
2927        };
2928        if !run_exists {
2929            return ToolResult::error("Subagent run not found".into());
2930        }
2931        let limit = input
2932            .get("limit")
2933            .and_then(|v| v.as_u64())
2934            .unwrap_or(50)
2935            .clamp(1, 200) as usize;
2936        let run_id_for_events = run_id.clone();
2937        let events = match call_blocking(self.db.clone(), move |db| {
2938            db.list_subagent_events(&run_id_for_events, limit)
2939        })
2940        .await
2941        {
2942            Ok(v) => v,
2943            Err(e) => return ToolResult::error(format!("Failed listing subagent events: {e}")),
2944        };
2945        let payload: Vec<serde_json::Value> = events
2946            .into_iter()
2947            .map(|e| {
2948                json!({
2949                    "id": e.id,
2950                    "run_id": e.run_id,
2951                    "event_type": e.event_type,
2952                    "detail": e.detail,
2953                    "created_at": e.created_at
2954                })
2955            })
2956            .collect();
2957        ToolResult::success(json!({"run_id": run_id, "events": payload}).to_string())
2958    }
2959}
2960
2961impl SubagentsRetryAnnouncesTool {
2962    pub fn new(config: &Config, db: Arc<Database>, channel_registry: Arc<ChannelRegistry>) -> Self {
2963        Self {
2964            config: config.clone(),
2965            db,
2966            channel_registry,
2967        }
2968    }
2969}
2970
2971#[async_trait]
2972impl Tool for SubagentsRetryAnnouncesTool {
2973    fn name(&self) -> &str {
2974        "subagents_retry_announces"
2975    }
2976
2977    fn definition(&self) -> ToolDefinition {
2978        ToolDefinition {
2979            name: "subagents_retry_announces".into(),
2980            description:
2981                "Manually flush pending subagent completion announcements (control chats only)."
2982                    .into(),
2983            input_schema: schema_object(
2984                json!({
2985                    "batch": {"type": "integer", "minimum": 1, "maximum": 200}
2986                }),
2987                &[],
2988            ),
2989        }
2990    }
2991
2992    async fn execute(&self, input: serde_json::Value) -> ToolResult {
2993        let auth = match auth_context_from_input(&input) {
2994            Some(v) => v,
2995            None => {
2996                return ToolResult::error(
2997                    "subagents_retry_announces requires caller auth context".into(),
2998                )
2999            }
3000        };
3001        if !auth.is_control_chat() {
3002            return ToolResult::error(
3003                "Permission denied: subagents_retry_announces requires control chat".into(),
3004            );
3005        }
3006        let batch = input
3007            .get("batch")
3008            .and_then(|v| v.as_u64())
3009            .unwrap_or(50)
3010            .clamp(1, 200) as usize;
3011        let _ = flush_pending_announces_once(
3012            &self.config,
3013            self.channel_registry.clone(),
3014            self.db.clone(),
3015            batch,
3016        )
3017        .await;
3018        ToolResult::success(json!({"status":"ok","batch":batch}).to_string())
3019    }
3020}
3021
3022#[cfg(test)]
3023mod tests {
3024    use super::*;
3025    use crate::config::WorkingDirIsolation;
3026
3027    fn test_config() -> Config {
3028        let mut cfg = Config::test_defaults();
3029        cfg.model = "claude-test".into();
3030        cfg.max_tokens = 2048;
3031        cfg.data_dir = "/tmp".into();
3032        cfg.working_dir = "/tmp".into();
3033        cfg.working_dir_isolation = WorkingDirIsolation::Shared;
3034        cfg.web_enabled = false;
3035        cfg
3036    }
3037
3038    fn test_db() -> Arc<Database> {
3039        let dir = std::env::temp_dir().join(format!(
3040            "microclaw_subagents_tool_test_{}",
3041            uuid::Uuid::new_v4()
3042        ));
3043        std::fs::create_dir_all(&dir).unwrap();
3044        Arc::new(Database::new(dir.to_str().unwrap()).unwrap())
3045    }
3046
3047    #[tokio::test]
3048    async fn test_sessions_spawn_requires_task() {
3049        let tool =
3050            SessionsSpawnTool::new(&test_config(), test_db(), Arc::new(ChannelRegistry::new()));
3051        let result = tool
3052            .execute(json!({"__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}}))
3053            .await;
3054        assert!(result.is_error);
3055        assert!(result.content.contains("task"));
3056    }
3057
3058    #[tokio::test]
3059    async fn test_sessions_spawn_rejects_unknown_runtime() {
3060        let tool =
3061            SessionsSpawnTool::new(&test_config(), test_db(), Arc::new(ChannelRegistry::new()));
3062        let result = tool
3063            .execute(json!({
3064                "task": "run",
3065                "runtime": "mystery",
3066                "__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}
3067            }))
3068            .await;
3069        assert!(result.is_error);
3070        assert!(result.content.contains("Unsupported subagent runtime"));
3071    }
3072
3073    #[tokio::test]
3074    async fn test_sessions_spawn_rejects_disabled_acp_runtime() {
3075        let tool =
3076            SessionsSpawnTool::new(&test_config(), test_db(), Arc::new(ChannelRegistry::new()));
3077        let result = tool
3078            .execute(json!({
3079                "task": "run",
3080                "runtime": "acp",
3081                "__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}
3082            }))
3083            .await;
3084        assert!(result.is_error);
3085        assert!(result.content.contains("ACP runtime is disabled"));
3086    }
3087
3088    #[tokio::test]
3089    async fn test_sessions_spawn_rejects_unknown_acp_target() {
3090        let mut cfg = test_config();
3091        cfg.subagents.acp.default_target.enabled = true;
3092        cfg.subagents.acp.default_target.command = "codex".into();
3093        let tool = SessionsSpawnTool::new(&cfg, test_db(), Arc::new(ChannelRegistry::new()));
3094        let result = tool
3095            .execute(json!({
3096                "task": "run",
3097                "runtime": "acp",
3098                "runtime_target": "missing",
3099                "__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}
3100            }))
3101            .await;
3102        assert!(result.is_error);
3103        assert!(result.content.contains("Unknown ACP runtime target"));
3104    }
3105
3106    #[tokio::test]
3107    async fn test_sessions_spawn_inherits_acp_runtime_target_from_parent_meta() {
3108        let mut cfg = test_config();
3109        cfg.subagents.acp.default_target.enabled = true;
3110        cfg.subagents.acp.targets.insert(
3111            "worker".into(),
3112            crate::config::SubagentAcpTargetConfig {
3113                enabled: true,
3114                command: "codex".into(),
3115                ..crate::config::SubagentAcpTargetConfig::default()
3116            },
3117        );
3118        let tool = SessionsSpawnTool::new(&cfg, test_db(), Arc::new(ChannelRegistry::new()));
3119        let result = tool
3120            .execute(json!({
3121                "task": "run",
3122                "__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1},
3123                "__subagent_runtime": {
3124                    "run_id": "parent",
3125                    "depth": 0,
3126                    "runtime": "acp",
3127                    "runtime_target": "worker",
3128                    "token_budget_remaining": 8000
3129                }
3130            }))
3131            .await;
3132        assert!(!result.is_error);
3133        let parsed: serde_json::Value = serde_json::from_str(&result.content).unwrap();
3134        assert_eq!(parsed.get("runtime").and_then(|v| v.as_str()), Some("acp"));
3135        assert_eq!(
3136            parsed.get("runtime_target").and_then(|v| v.as_str()),
3137            Some("worker")
3138        );
3139    }
3140
3141    #[tokio::test]
3142    async fn sessions_spawn_offers_project_agents_and_uses_the_subagent_model() {
3143        let agents = tempfile::tempdir().unwrap();
3144        std::fs::write(
3145            agents.path().join("reviewer.md"),
3146            "---\ndescription: Reviews diffs\nmodel: agent-model\ntools: read, grep\n---\nYou review code.",
3147        )
3148        .unwrap();
3149        let mut cfg = test_config();
3150        cfg.project_agents_dir = Some(agents.path().to_string_lossy().into_owned());
3151        cfg.aux_models.subagent = Some("cheap-model".into());
3152        let db = test_db();
3153        let tool = SessionsSpawnTool::new(&cfg, db.clone(), Arc::new(ChannelRegistry::new()));
3154        let definition = tool.definition();
3155        assert!(definition.description.contains("reviewer (Reviews diffs)"));
3156        assert_eq!(
3157            definition.input_schema["properties"]["agent"]["enum"],
3158            json!(["reviewer"])
3159        );
3160
3161        let unknown = tool
3162            .execute(json!({
3163                "task": "look",
3164                "agent": "nobody",
3165                "__microclaw_auth": {"caller_channel":"code", "caller_chat_id": 1}
3166            }))
3167            .await;
3168        assert!(unknown.is_error);
3169        assert!(
3170            unknown.content.contains("available: reviewer"),
3171            "{}",
3172            unknown.content
3173        );
3174
3175        let model_of = |result: &ToolResult| {
3176            let parsed: serde_json::Value = serde_json::from_str(&result.content).unwrap();
3177            let run_id = parsed["run_id"].as_str().unwrap().to_string();
3178            db.get_subagent_run(&run_id, 1).unwrap().unwrap().model
3179        };
3180        let plain = tool
3181            .execute(json!({
3182                "task": "look",
3183                "__microclaw_auth": {"caller_channel":"code", "caller_chat_id": 1}
3184            }))
3185            .await;
3186        assert!(!plain.is_error, "{}", plain.content);
3187        assert_eq!(model_of(&plain), "cheap-model");
3188        let as_agent = tool
3189            .execute(json!({
3190                "task": "review",
3191                "agent": "reviewer",
3192                "__microclaw_auth": {"caller_channel":"code", "caller_chat_id": 1}
3193            }))
3194            .await;
3195        assert!(!as_agent.is_error, "{}", as_agent.content);
3196        assert_eq!(model_of(&as_agent), "agent-model");
3197        let parsed: serde_json::Value = serde_json::from_str(&as_agent.content).unwrap();
3198        assert_eq!(parsed["label"], json!("reviewer"));
3199    }
3200
3201    #[tokio::test]
3202    async fn test_subagents_info_requires_run_id() {
3203        let tool = SubagentsInfoTool::new(test_db());
3204        let result = tool
3205            .execute(json!({"__microclaw_auth": {"caller_channel":"web", "caller_chat_id": 1}}))
3206            .await;
3207        assert!(result.is_error);
3208        assert!(result.content.contains("run_id"));
3209    }
3210
3211    #[test]
3212    fn test_normalize_strips_leaked_thinking() {
3213        // A sub-agent that emits only chain-of-thought (no JSON) must not leak
3214        // the <think> block into the announced answer.
3215        let raw = "<think>The write_memory tool is not available - I see read_memory \
3216                   but not write_memory. Let me inform the user.</think>";
3217        let (answer, envelope) = normalize_subagent_artifact_payload(raw);
3218        assert!(!answer.contains("<think>"));
3219        assert!(!answer.contains("write_memory"));
3220        assert!(!envelope.contains("<think>"));
3221    }
3222
3223    #[test]
3224    fn contract_failed_marker_matches_report_rendering() {
3225        // The fan-in retry detects failed contracts by this marker; it must
3226        // stay in sync with completion_contract::render_report.
3227        let report = crate::completion_contract::render_report(&[
3228            crate::completion_contract::CriterionOutcome {
3229                description: "file `x` exists".into(),
3230                passed: false,
3231                evidence: "missing".into(),
3232            },
3233        ]);
3234        assert!(report.starts_with(CONTRACT_FAILED_MARKER));
3235        // And the VERIFIED path must NOT match the failure marker.
3236        let ok_report = crate::completion_contract::render_report(&[
3237            crate::completion_contract::CriterionOutcome {
3238                description: "file `x` exists".into(),
3239                passed: true,
3240                evidence: "ok".into(),
3241            },
3242        ]);
3243        assert!(!ok_report.starts_with(CONTRACT_FAILED_MARKER));
3244    }
3245
3246    #[test]
3247    fn test_submit_result_tool_definition_shape() {
3248        let def = submit_result_tool_definition();
3249        assert_eq!(def.name, SUBMIT_RESULT_TOOL);
3250        let props = def.input_schema.get("properties").unwrap();
3251        for key in [
3252            "summary",
3253            "findings",
3254            "artifacts",
3255            "next_actions",
3256            "final_answer",
3257        ] {
3258            assert!(props.get(key).is_some(), "missing schema property {key}");
3259        }
3260        let required = def
3261            .input_schema
3262            .get("required")
3263            .unwrap()
3264            .as_array()
3265            .unwrap();
3266        assert!(required.iter().any(|v| v == "final_answer"));
3267        // A submit_result payload normalizes into the announced answer.
3268        let payload = json!({"summary": "s", "final_answer": "the answer"}).to_string();
3269        let (answer, _envelope) = normalize_subagent_artifact_payload(&payload);
3270        assert_eq!(answer, "the answer");
3271    }
3272
3273    #[test]
3274    fn test_subagent_output_is_structured() {
3275        // Prose / leaked reasoning is NOT structured (would trigger a repair).
3276        assert!(!subagent_output_is_structured(
3277            "<think>no write_memory tool</think> I can't save this."
3278        ));
3279        assert!(!subagent_output_is_structured(
3280            "Done, everything looks good."
3281        ));
3282        // A contract object (even after a thinking block) IS structured.
3283        assert!(subagent_output_is_structured(
3284            "<think>ok</think>{\"summary\":\"s\",\"final_answer\":\"done\"}"
3285        ));
3286        // An object with only empty contract fields is not structured.
3287        assert!(!subagent_output_is_structured(
3288            "{\"summary\":\"\",\"final_answer\":\"\"}"
3289        ));
3290    }
3291
3292    #[test]
3293    fn test_normalize_recovers_json_after_thinking() {
3294        // Reasoning block followed by the contract JSON: the JSON must win, not
3295        // the raw text fallback.
3296        let raw = "<think>let me structure this</think>\n\
3297                   {\"summary\":\"done\",\"findings\":[\"a\"],\"artifacts\":[],\
3298                   \"next_actions\":[],\"final_answer\":\"All set.\"}";
3299        let (answer, _envelope) = normalize_subagent_artifact_payload(raw);
3300        assert_eq!(answer, "All set.");
3301    }
3302
3303    #[test]
3304    fn test_compute_child_token_budget_respects_parent_remaining() {
3305        let budget = compute_child_token_budget(Some(5000), Some(3000), 120000).unwrap();
3306        assert_eq!(budget, 3000);
3307    }
3308
3309    #[test]
3310    fn test_compute_child_token_budget_rejects_exhausted_parent() {
3311        let err = compute_child_token_budget(None, Some(1500), 120000).unwrap_err();
3312        assert!(err.contains("budget exhausted"));
3313    }
3314
3315    #[test]
3316    fn process_lifetime_executor_outlives_foreground_runtime() {
3317        let (tx, rx) = std::sync::mpsc::channel();
3318        {
3319            let foreground = tokio::runtime::Runtime::new().unwrap();
3320            foreground.block_on(async {
3321                TASK_RUNTIME.spawn(async move {
3322                    tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3323                    tx.send("finished").unwrap();
3324                });
3325            });
3326        }
3327        assert_eq!(
3328            rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(),
3329            "finished"
3330        );
3331    }
3332}