a3s-code-core 5.3.1

A3S Code Core - Embeddable AI agent library with tool execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! Task tools for delegated child runs.
//!
//! The Task tool allows the main agent to delegate specialized work to focused
//! child runs. Each child run gets bounded context and the permissions declared
//! by its agent definition.
//!
//! ## Usage
//!
//! ```json
//! {
//!   "agent": "explore",
//!   "description": "Find authentication code",
//!   "prompt": "Search for files related to user authentication..."
//! }
//! ```

use crate::agent::{AgentConfig, AgentEvent, AgentLoop};
use crate::llm::structured::{
    generate_blocking, parse_validated_output, StructuredMode, StructuredRequest,
};
use crate::llm::{LlmClient, ToolDefinition};
use crate::mcp::manager::McpManager;
use crate::orchestration::{AgentExecutor, AgentStepSpec, StepOutcome, ToolSourceAnchor};
use crate::subagent::{AgentDefinition, AgentRegistry};
use crate::tools::types::{Tool, ToolContext, ToolOutput};
use anyhow::{Context, Result};
use async_trait::async_trait;
use futures::FutureExt;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::panic::AssertUnwindSafe;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;

const TASK_OUTPUT_CONTEXT_LIMIT: usize = 4_000;
const TASK_OUTPUT_CONTEXT_HEAD: usize = 3_000;
const TASK_OUTPUT_CONTEXT_TAIL: usize = 800;
const MAX_TASK_SOURCE_ANCHORS: usize = 64;
const MAX_TASK_SOURCE_CANDIDATES: usize = MAX_TASK_SOURCE_ANCHORS * 4;
const MAX_TASK_SOURCE_TOOL_BYTES: usize = 64;
const MAX_TASK_SOURCE_VALUE_BYTES: usize = 4 * 1024;
const MAX_PARALLEL_TASK_SOURCE_ANCHORS: usize = MAX_TASK_SOURCE_ANCHORS;
const TASK_TOOL_DESCRIPTION: &str = "Delegate a bounded task to a specialized child run. Choose the canonical worker name from the live agent catalog. Custom agents from agent_dirs and .a3s/agents are supported; .claude/agents is read for compatibility.";
const PARALLEL_TASK_TOOL_DESCRIPTION: &str = "Fan out 2 or more INDEPENDENT subtasks as delegated child runs that execute concurrently; results are returned when all complete. By default any failed child makes the tool fail; evidence-gathering callers may set allow_partial_failure=true to continue when at least one child succeeds. Transient provider failures may be retried once only for explicitly read-only branches; successful and potentially mutating branches are never replayed. Use this only when the work genuinely splits into branches that can be investigated or implemented separately. Do not use it for trivial, conversational, single-step, or dependent work. Choose canonical worker names from the live agent catalog.";

/// Task tool parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskParams {
    /// Agent type to use (explore, general, plan, verification, review, etc.)
    pub agent: String,
    /// Short description of the task (for display)
    pub description: String,
    /// Detailed prompt for the agent
    pub prompt: String,
    /// Optional: run in background (default: false)
    #[serde(default)]
    pub background: bool,
    /// Optional: maximum steps for this task
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_steps: Option<usize>,
    /// Optional: JSON schema the child result must satisfy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<serde_json::Value>,
}

/// Task tool result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskResult {
    /// Task output from the delegated child run.
    pub output: String,
    /// Child session ID
    pub session_id: String,
    /// Agent type used
    pub agent: String,
    /// Whether the task succeeded
    pub success: bool,
    /// Task ID for tracking
    pub task_id: String,
    /// Structured child output validated against an optional output schema.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub structured: Option<serde_json::Value>,
    /// Source locations observed by successful built-in child tool calls.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_anchors: Vec<ToolSourceAnchor>,
}

mod result_projection;
use result_projection::*;

mod parallel_execution;

const MAX_PARALLEL_TASKS_PER_CALL: usize = 32;

/// Task executor for delegated child runs.
pub struct TaskExecutor {
    /// Agent registry for looking up agent definitions
    registry: Arc<AgentRegistry>,
    /// LLM client used to power child agent loops
    llm_client: Arc<dyn LlmClient>,
    /// Workspace path shared with child agents
    workspace: String,
    /// Ordered MCP managers for registering inherited tools in child sessions.
    mcp_managers: Vec<Arc<McpManager>>,
    /// Parent capabilities to inherit into child runs.
    parent_context: Option<crate::child_run::ChildRunContext>,
    /// Optional lifetime boundary inherited from the session that created this
    /// executor. Keeping it on the executor prevents cached workflow/executor
    /// handles from starting new child runs after their session is closed.
    parent_cancellation: Option<CancellationToken>,
    max_parallel_tasks: usize,
    /// Shared across every fan-out started by this executor. Per-call wave
    /// limits alone are insufficient when a dynamic workflow launches several
    /// `parallel_task` host steps concurrently.
    parallel_permits: Arc<tokio::sync::Semaphore>,
    /// Optional shared tracker — when present each task registers a
    /// `CancellationToken` so callers can cancel by `task_id`.
    subagent_tracker: Option<Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>>,
}

impl TaskExecutor {
    /// Create a new task executor
    pub fn new(
        registry: Arc<AgentRegistry>,
        llm_client: Arc<dyn LlmClient>,
        workspace: String,
    ) -> Self {
        Self {
            registry,
            llm_client,
            workspace,
            mcp_managers: Vec::new(),
            parent_context: None,
            parent_cancellation: None,
            max_parallel_tasks: crate::agent::DEFAULT_MAX_PARALLEL_TASKS,
            parallel_permits: Arc::new(tokio::sync::Semaphore::new(
                crate::agent::DEFAULT_MAX_PARALLEL_TASKS,
            )),
            subagent_tracker: None,
        }
    }

    /// Create a new task executor with MCP manager for tool inheritance
    pub fn with_mcp(
        registry: Arc<AgentRegistry>,
        llm_client: Arc<dyn LlmClient>,
        workspace: String,
        mcp_manager: Arc<McpManager>,
    ) -> Self {
        Self::with_mcp_managers(registry, llm_client, workspace, vec![mcp_manager])
    }

    /// Create a task executor with ordered MCP capability sources.
    pub fn with_mcp_managers(
        registry: Arc<AgentRegistry>,
        llm_client: Arc<dyn LlmClient>,
        workspace: String,
        mcp_managers: Vec<Arc<McpManager>>,
    ) -> Self {
        Self {
            registry,
            llm_client,
            workspace,
            mcp_managers,
            parent_context: None,
            parent_cancellation: None,
            max_parallel_tasks: crate::agent::DEFAULT_MAX_PARALLEL_TASKS,
            parallel_permits: Arc::new(tokio::sync::Semaphore::new(
                crate::agent::DEFAULT_MAX_PARALLEL_TASKS,
            )),
            subagent_tracker: None,
        }
    }

    /// Set parent session capabilities to inherit into child runs.
    pub fn with_parent_context(mut self, ctx: crate::child_run::ChildRunContext) -> Self {
        if let Some(max_parallel_tasks) = ctx.max_parallel_tasks {
            let max_parallel_tasks = max_parallel_tasks.max(1);
            self.max_parallel_tasks = max_parallel_tasks;
            self.parallel_permits = Arc::new(tokio::sync::Semaphore::new(max_parallel_tasks));
        }
        self.parent_context = Some(ctx);
        self
    }

    /// Bind every run started by this executor to a parent lifetime.
    ///
    /// A token that is already cancelled makes execution fail before emitting
    /// `SubagentStart` or performing MCP/LLM work. In-flight children derive
    /// their own token so cancellation still cascades without granting them the
    /// ability to cancel the parent.
    pub fn with_parent_cancellation(mut self, cancellation: CancellationToken) -> Self {
        self.parent_cancellation = Some(cancellation);
        self
    }

    pub fn with_max_parallel_tasks(mut self, max_parallel_tasks: usize) -> Self {
        let max_parallel_tasks = max_parallel_tasks.max(1);
        self.max_parallel_tasks = max_parallel_tasks;
        self.parallel_permits = Arc::new(tokio::sync::Semaphore::new(max_parallel_tasks));
        self
    }

    /// Share a tracker with this executor. When set, each task registers
    /// a `CancellationToken` against the tracker so the parent session
    /// can cancel by `task_id`.
    pub fn with_subagent_tracker(
        mut self,
        tracker: Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>,
    ) -> Self {
        self.subagent_tracker = Some(tracker);
        self
    }

    fn visible_agents(&self) -> Vec<AgentDefinition> {
        self.registry.list_visible()
    }

    /// Execute a task by spawning an isolated child AgentLoop.
    ///
    /// `parent_session_id` flows into the emitted `SubagentStart`/`SubagentEnd`
    /// events so dashboards can associate child runs with the parent session.
    pub async fn execute(
        &self,
        params: TaskParams,
        event_tx: Option<broadcast::Sender<AgentEvent>>,
        parent_session_id: Option<&str>,
    ) -> Result<TaskResult> {
        self.execute_with_parent_cancellation(
            params,
            event_tx,
            parent_session_id,
            self.parent_cancellation.as_ref(),
        )
        .await
    }

    async fn execute_with_parent_cancellation(
        &self,
        params: TaskParams,
        event_tx: Option<broadcast::Sender<AgentEvent>>,
        parent_session_id: Option<&str>,
        parent_cancellation: Option<&CancellationToken>,
    ) -> Result<TaskResult> {
        let task_id = format!("task-{}", uuid::Uuid::new_v4());
        self.execute_with_task_id_scoped(
            task_id,
            params,
            event_tx,
            parent_session_id,
            true,
            parent_cancellation,
        )
        .await
    }

    /// Execute a task using a caller-supplied task id. Used by `execute_background`
    /// so the synchronously-returned task id matches the one in lifecycle events.
    /// When `emit_start` is `false` the caller is responsible for emitting
    /// `SubagentStart` themselves (e.g. to avoid a race against a tracker query).
    pub async fn execute_with_task_id(
        &self,
        task_id: String,
        params: TaskParams,
        event_tx: Option<broadcast::Sender<AgentEvent>>,
        parent_session_id: Option<&str>,
        emit_start: bool,
    ) -> Result<TaskResult> {
        self.execute_with_task_id_scoped(
            task_id,
            params,
            event_tx,
            parent_session_id,
            emit_start,
            self.parent_cancellation.as_ref(),
        )
        .await
    }

    async fn execute_with_task_id_scoped(
        &self,
        task_id: String,
        params: TaskParams,
        event_tx: Option<broadcast::Sender<AgentEvent>>,
        parent_session_id: Option<&str>,
        emit_start: bool,
        parent_cancellation: Option<&CancellationToken>,
    ) -> Result<TaskResult> {
        if parent_cancellation.is_some_and(CancellationToken::is_cancelled) {
            anyhow::bail!("Operation cancelled by parent session");
        }

        let session_id = format!("task-run-{}", task_id);
        let started_ms = epoch_ms();
        let output_schema = params.output_schema.clone();

        let agent = self
            .registry
            .get(&params.agent)
            .context(format!("Unknown agent type: '{}'", params.agent))?;
        let tool_free = agent.tool_free;
        let tool_free_system = agent.prompt.clone();
        let inherited_security_provider = self
            .parent_context
            .as_ref()
            .and_then(|context| context.security_provider.clone());

        if emit_start {
            let event = AgentEvent::SubagentStart {
                task_id: task_id.clone(),
                session_id: session_id.clone(),
                parent_session_id: parent_session_id.unwrap_or_default().to_string(),
                agent: params.agent.clone(),
                description: params.description.clone(),
                started_ms,
            };
            let event = inherited_security_provider
                .as_deref()
                .map(|provider| crate::security::sanitize_agent_event(provider, &event))
                .unwrap_or(event);
            if let Some(ref tracker) = self.subagent_tracker {
                tracker.record_event(&event).await;
            }
            if let Some(ref tx) = event_tx {
                let _ = tx.send(event);
            }
        }

        // Build a child ToolExecutor. Task tools are intentionally omitted
        // here to prevent unlimited delegation nesting.
        let child_executor = if let Some(ref parent_ctx) = self.parent_context {
            if let Some(ref services) = parent_ctx.workspace_services {
                crate::tools::ToolExecutor::new_with_workspace_services_and_artifact_limits(
                    self.workspace.clone(),
                    Arc::clone(services),
                    crate::tools::ArtifactStoreLimits::default(),
                )
            } else {
                crate::tools::ToolExecutor::new(self.workspace.clone())
            }
        } else {
            crate::tools::ToolExecutor::new(self.workspace.clone())
        };

        // Register MCP tools so child agents can access MCP servers.
        for mcp in &self.mcp_managers {
            let all_tools = match parent_cancellation {
                Some(cancellation) => {
                    tokio::select! {
                        biased;
                        _ = cancellation.cancelled() => {
                            anyhow::bail!("Operation cancelled by parent session");
                        }
                        tools = mcp.get_all_tools() => tools,
                    }
                }
                None => mcp.get_all_tools().await,
            };
            let mut by_server: std::collections::HashMap<
                String,
                Vec<crate::mcp::protocol::McpTool>,
            > = std::collections::HashMap::new();
            for (server, tool) in all_tools {
                by_server.entry(server).or_default().push(tool);
            }
            for (server_name, tools) in by_server {
                let wrappers =
                    crate::mcp::tools::create_mcp_tools(&server_name, tools, Arc::clone(mcp));
                for wrapper in wrappers {
                    child_executor.register_dynamic_tool(wrapper);
                }
            }
        }

        let child_executor = Arc::new(child_executor);

        let mut child_config = AgentConfig {
            tools: child_executor.definitions(),
            ..AgentConfig::default()
        };
        agent.apply_to(&mut child_config);
        if let Some(ref parent_ctx) = self.parent_context {
            parent_ctx.apply_to(&mut child_config);
        }
        // A delegated task is already the output of a parent planning
        // decision. Running the generic pre-analysis/planning classifier again
        // adds an unrelated LLM round to every child and can consume the whole
        // fan-out deadline before any task tool runs.
        child_config.planning_mode = crate::prompts::PlanningMode::Disabled;
        if let Some(max_steps) = params.max_steps {
            child_config.max_tool_rounds = max_steps;
        }
        let child_security_provider = child_config.security_provider.clone();
        let source_security_provider = child_security_provider.clone();

        let cancel_token = parent_cancellation
            .map(CancellationToken::child_token)
            .unwrap_or_default();
        let mut tool_context = ToolContext::new(PathBuf::from(&self.workspace))
            .with_session_id(session_id.clone())
            .with_cancellation(cancel_token.clone());
        if let Some(ref parent_ctx) = self.parent_context {
            if let Some(ref services) = parent_ctx.workspace_services {
                tool_context = tool_context.with_workspace_services(Arc::clone(services));
            }
        }

        let source_context = tool_context.clone();
        let agent_loop = AgentLoop::new(
            Arc::clone(&self.llm_client),
            child_executor,
            tool_context,
            child_config,
        );

        // Always observe the child event stream so successful source tool calls
        // survive in TaskResult metadata even when nobody subscribed to live
        // progress. Forward the same events when a parent broadcast exists.
        let (mpsc_tx, mut mpsc_rx) = tokio::sync::mpsc::channel(100);
        let broadcast_tx = event_tx.clone();
        let progress_task_id = task_id.clone();
        let progress_session_id = session_id.clone();
        let child_event_forwarder = tokio::spawn(async move {
            let mut source_anchors = Vec::new();
            let mut seen_source_anchors = std::collections::HashSet::new();
            let mut scanned_source_candidates = 0usize;
            while let Some(event) = mpsc_rx.recv().await {
                let event = source_security_provider
                    .as_deref()
                    .map(|provider| crate::security::sanitize_agent_event(provider, &event))
                    .unwrap_or(event);
                collect_tool_source_anchors(
                    &event,
                    &source_context,
                    &mut source_anchors,
                    &mut seen_source_anchors,
                    &mut scanned_source_candidates,
                );
                if let Some(ref broadcast_tx) = broadcast_tx {
                    if let Some(progress) = synthesize_subagent_progress(
                        &event,
                        &progress_task_id,
                        &progress_session_id,
                    ) {
                        let _ = broadcast_tx.send(progress);
                    }
                    let _ = broadcast_tx.send(event);
                }
            }
            source_anchors
        });
        let child_event_tx = Some(mpsc_tx);
        let child_llm_event_tx = child_event_tx.clone();

        // Register a CancellationToken with the tracker (if shared) so the
        // parent session's `cancel_subagent_task` can interrupt this run.
        if let Some(ref tracker) = self.subagent_tracker {
            tracker
                .register_canceller(&task_id, cancel_token.clone())
                .await;
        }

        let structured_prompt = output_schema
            .as_ref()
            .filter(|_| !tool_free)
            .map(|schema| structured_task_prompt(&params.prompt, schema));
        let execution_prompt = structured_prompt.as_deref().unwrap_or(&params.prompt);

        let mut structured = None;
        let (mut output, mut success) = if tool_free && output_schema.is_some() {
            let llm_client = agent_loop.scoped_llm_client_for_parts(
                Some(&session_id),
                &child_llm_event_tx,
                &cancel_token,
            );
            match Self::generate_structured_task(
                &*llm_client,
                &params.prompt,
                tool_free_system.as_deref(),
                output_schema.clone().expect("schema checked above"),
                &cancel_token,
            )
            .await
            {
                Ok(object) => {
                    let output = serde_json::to_string_pretty(&object)
                        .unwrap_or_else(|_| object.to_string());
                    structured = Some(object);
                    (output, true)
                }
                Err(error) if cancel_token.is_cancelled() => {
                    (format!("Task cancelled by caller: {error}"), false)
                }
                Err(error) => (format!("Task failed: {error}"), false),
            }
        } else {
            match agent_loop
                .execute_with_session(
                    &[],
                    execution_prompt,
                    Some(&session_id),
                    child_event_tx.clone(),
                    Some(&cancel_token),
                )
                .await
            {
                Ok(_) if cancel_token.is_cancelled() => {
                    ("Task cancelled by caller".to_string(), false)
                }
                Ok(result) if result.text.trim().is_empty() => (
                    "Task failed: child agent returned no final output".to_string(),
                    false,
                ),
                Ok(result) if AgentLoop::is_synthetic_failure_output(&result.text) => {
                    (format!("Task failed: {}", result.text), false)
                }
                Ok(result) => (result.text, true),
                Err(e) if cancel_token.is_cancelled() => {
                    (format!("Task cancelled by caller: {}", e), false)
                }
                Err(e) => (format!("Task failed: {}", e), false),
            }
        };

        if success && !tool_free {
            if let Some(schema) = output_schema {
                if let Some(object) = parse_validated_output(&output, &schema) {
                    structured = Some(object);
                } else {
                    let llm_client = agent_loop.scoped_llm_client_for_parts(
                        Some(&session_id),
                        &child_llm_event_tx,
                        &cancel_token,
                    );
                    match Self::coerce_to_schema(&*llm_client, &output, schema, &cancel_token).await
                    {
                        Ok(object) => structured = Some(object),
                        Err(error) => {
                            success = false;
                            output = format!("{output}\n\n[structured output failed: {error}]");
                        }
                    }
                }
            }
        }
        if let Some(provider) = child_security_provider.as_deref() {
            output = provider.sanitize_output(&output);
            if let Some(value) = &mut structured {
                *value = sanitize_task_json(provider, value);
            }
        }

        // The child loop and optional structured-output pass are the only
        // producers. Close their sender and drain the bridge before emitting
        // SubagentEnd so callers never observe a terminal event followed by
        // stale child deltas or progress events.
        drop(child_event_tx);
        drop(child_llm_event_tx);
        let source_anchors = match child_event_forwarder.await {
            Ok(source_anchors) => source_anchors,
            Err(error) => {
                tracing::warn!(%error, task_id = %task_id, "subagent event bridge failed");
                Vec::new()
            }
        };

        let end_event = AgentEvent::SubagentEnd {
            task_id: task_id.clone(),
            session_id: session_id.clone(),
            agent: params.agent.clone(),
            output: output.clone(),
            success,
            finished_ms: epoch_ms(),
        };
        if let Some(ref tracker) = self.subagent_tracker {
            // The tracker is authoritative even when a background child
            // finishes after the parent run's event forwarder has closed.
            if success {
                tracker
                    .record_source_anchors(&task_id, &source_anchors)
                    .await;
            }
            tracker.record_event(&end_event).await;
            tracker.clear_canceller(&task_id).await;
        }
        if let Some(ref tx) = event_tx {
            let _ = tx.send(end_event);
        }

        Ok(TaskResult {
            output,
            session_id,
            agent: params.agent,
            success,
            task_id,
            structured,
            source_anchors,
        })
    }

    /// Execute a task in the background.
    ///
    /// Returns immediately with the task ID; the same id is used in the emitted
    /// `SubagentStart`/`SubagentEnd` events so callers can correlate. Pre-emits
    /// `SubagentStart` synchronously when an event channel is available so a
    /// caller that queries the subagent task tracker right after this call
    /// observes the task in `Running` state without a race window.
    pub fn execute_background(
        self: Arc<Self>,
        params: TaskParams,
        event_tx: Option<broadcast::Sender<AgentEvent>>,
        parent_session_id: Option<String>,
    ) -> String {
        let parent_cancellation = self.parent_cancellation.clone();
        self.execute_background_with_parent_cancellation(
            params,
            event_tx,
            parent_session_id,
            parent_cancellation,
        )
    }

    fn execute_background_with_parent_cancellation(
        self: Arc<Self>,
        params: TaskParams,
        event_tx: Option<broadcast::Sender<AgentEvent>>,
        parent_session_id: Option<String>,
        parent_cancellation: Option<CancellationToken>,
    ) -> String {
        let task_id = format!("task-{}", uuid::Uuid::new_v4());
        let session_id = format!("task-run-{}", task_id);
        let failure_session_id = session_id.clone();
        let failure_agent = params.agent.clone();
        let start_event = AgentEvent::SubagentStart {
            task_id: task_id.clone(),
            session_id,
            parent_session_id: parent_session_id.clone().unwrap_or_default(),
            agent: params.agent.clone(),
            description: params.description.clone(),
            started_ms: epoch_ms(),
        };
        let security_provider = self
            .parent_context
            .as_ref()
            .and_then(|context| context.security_provider.clone());
        let start_event = security_provider
            .as_deref()
            .map(|provider| crate::security::sanitize_agent_event(provider, &start_event))
            .unwrap_or(start_event);

        if let Some(ref tx) = event_tx {
            let _ = tx.send(start_event.clone());
        }

        let task_id_for_spawn = task_id.clone();
        let task_id_for_log = task_id.clone();
        tokio::spawn(async move {
            if let Some(ref tracker) = self.subagent_tracker {
                tracker.record_event(&start_event).await;
            }
            let failure_event_tx = event_tx.clone();
            if let Err(error) = self
                .execute_with_task_id_scoped(
                    task_id_for_spawn,
                    params,
                    event_tx,
                    parent_session_id.as_deref(),
                    false,
                    parent_cancellation.as_ref(),
                )
                .await
            {
                let end_event = AgentEvent::SubagentEnd {
                    task_id: task_id_for_log.clone(),
                    session_id: failure_session_id,
                    agent: failure_agent,
                    output: format!("Task failed before child execution started: {error}"),
                    success: false,
                    finished_ms: epoch_ms(),
                };
                let end_event = security_provider
                    .as_deref()
                    .map(|provider| crate::security::sanitize_agent_event(provider, &end_event))
                    .unwrap_or(end_event);
                if let Some(ref tracker) = self.subagent_tracker {
                    tracker.record_event(&end_event).await;
                    tracker.clear_canceller(&task_id_for_log).await;
                }
                if let Some(tx) = failure_event_tx {
                    let _ = tx.send(end_event);
                }
                tracing::error!("Background task {} failed: {}", task_id_for_log, error);
            }
        });

        task_id
    }
}

fn structured_task_prompt(prompt: &str, schema: &serde_json::Value) -> String {
    let schema = serde_json::to_string_pretty(schema).unwrap_or_else(|_| schema.to_string());
    format!(
        "{prompt}\n\n\
         FINAL OUTPUT CONTRACT\n\
         Complete the requested investigation before answering. Your final response must contain \
         exactly one JSON value matching the JSON Schema below, with no Markdown fence or prose \
         outside the JSON. This contract applies to the final response only; use the available \
         tools as needed before finalizing.\n\n\
         {schema}"
    )
}

#[derive(Debug, Clone)]
struct AgentCatalogEntry {
    name: String,
    description: String,
}

fn agent_catalog_entries(agents: &[AgentDefinition]) -> Vec<AgentCatalogEntry> {
    let mut entries = agents
        .iter()
        .map(|agent| AgentCatalogEntry {
            name: agent.name.clone(),
            description: agent
                .description
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" "),
        })
        .collect::<Vec<_>>();
    entries.sort_by(|left, right| left.name.cmp(&right.name));
    entries
}

fn agent_catalog_text(agents: &[AgentDefinition]) -> String {
    agent_catalog_entries(agents)
        .into_iter()
        .map(|entry| format!("{}: {}", entry.name, entry.description))
        .collect::<Vec<_>>()
        .join("\n")
}

fn delegation_tool_description(base: &str, agents: &[AgentDefinition]) -> String {
    format!(
        "{base}\n\nAvailable agents (live catalog; use canonical names):\n{}",
        agent_catalog_text(agents)
    )
}

pub(super) fn task_agent_parameter_schema(agents: &[AgentDefinition]) -> serde_json::Value {
    let entries = agent_catalog_entries(agents);
    let examples = entries
        .iter()
        .map(|entry| serde_json::Value::String(entry.name.clone()))
        .collect::<Vec<_>>();
    let catalog = entries
        .into_iter()
        .map(|entry| format!("{}: {}", entry.name, entry.description))
        .collect::<Vec<_>>()
        .join("\n");
    serde_json::json!({
        "type": "string",
        "description": format!(
            "Required. Canonical agent type to use. Always provide this exact field name: 'agent'. Live agent catalog:\n{catalog}"
        ),
        "examples": examples
    })
}

/// Get the JSON schema for TaskParams using the built-in agent catalog.
pub fn task_params_schema() -> serde_json::Value {
    task_params_schema_for_agents(&AgentRegistry::new().list_visible())
}

fn task_params_schema_for_agents(agents: &[AgentDefinition]) -> serde_json::Value {
    serde_json::json!({
        "type": "object",
        "additionalProperties": false,
        "properties": {
            "agent": task_agent_parameter_schema(agents),
            "description": {
                "type": "string",
                "description": "Required. Short task label for display and tracking. Always provide this exact field name: 'description'."
            },
            "prompt": {
                "type": "string",
                "description": "Required. Detailed instruction for the delegated child run. Always provide this exact field name: 'prompt'."
            },
            "background": {
                "type": "boolean",
                "description": "Optional. Run the task in the background. Default: false.",
                "default": false
            },
            "max_steps": {
                "type": "integer",
                "description": "Optional. Maximum number of steps for this task."
            },
            "output_schema": {
                "type": "object",
                "description": "Optional. JSON Schema object the delegated result must satisfy. When provided, the child output is coerced into a validated structured object and returned in metadata."
            }
        },
        "required": ["agent", "description", "prompt"],
        "examples": [
            {
                "agent": "explore",
                "description": "Find Rust files",
                "prompt": "Search the workspace for Rust files and summarize the layout."
            },
            {
                "agent": "general",
                "description": "Investigate test failure",
                "prompt": "Inspect the failing tests and explain the root cause.",
                "max_steps": 6
            }
        ]
    })
}

/// TaskTool wraps TaskExecutor as a Tool for registration in ToolExecutor.
/// This allows the LLM to delegate tasks through the standard tool interface.
pub struct TaskTool {
    executor: Arc<TaskExecutor>,
}

impl TaskTool {
    /// Create a new TaskTool
    pub fn new(executor: Arc<TaskExecutor>) -> Self {
        Self { executor }
    }
}

#[async_trait]
impl Tool for TaskTool {
    fn name(&self) -> &str {
        "task"
    }

    fn description(&self) -> &str {
        TASK_TOOL_DESCRIPTION
    }

    fn parameters(&self) -> serde_json::Value {
        task_params_schema_for_agents(&self.executor.visible_agents())
    }

    fn definition(&self) -> ToolDefinition {
        let agents = self.executor.visible_agents();
        ToolDefinition {
            name: self.name().to_string(),
            description: delegation_tool_description(self.description(), &agents),
            parameters: task_params_schema_for_agents(&agents),
        }
    }

    async fn execute(&self, args: &serde_json::Value, ctx: &ToolContext) -> Result<ToolOutput> {
        let params: TaskParams =
            serde_json::from_value(args.clone()).context("Invalid task parameters")?;
        let parent_cancellation = ctx.cancellation_token();

        if params.background {
            let task_id = Arc::clone(&self.executor).execute_background_with_parent_cancellation(
                params,
                ctx.agent_event_tx.clone(),
                ctx.session_id.clone(),
                Some(parent_cancellation),
            );
            return Ok(ToolOutput::success(format!(
                "Task started in background. Task ID: {}",
                task_id
            )));
        }

        let result = self
            .executor
            .execute_with_parent_cancellation(
                params,
                ctx.agent_event_tx.clone(),
                ctx.session_id.as_deref(),
                Some(&parent_cancellation),
            )
            .await?;
        let (content, truncated) = format_task_result_for_context(&result);
        let metadata = serde_json::json!({
            "task_id": result.task_id,
            "session_id": result.session_id,
            "agent": result.agent,
            "success": result.success,
            "output_bytes": result.output.len(),
            "truncated_for_context": truncated,
            "artifact_id": task_artifact_id(&result),
            "artifact_uri": task_artifact_uri(&result),
            "structured": result.structured,
            "source_anchors": result.source_anchors,
        });

        if result.success {
            Ok(ToolOutput::success(content).with_metadata(metadata))
        } else {
            Ok(ToolOutput::error(content).with_metadata(metadata))
        }
    }
}

mod parallel_params;
pub use parallel_params::{parallel_task_params_schema, ParallelTaskParams};

/// ParallelTaskTool allows the LLM to fan out multiple delegated tasks concurrently.
///
/// All tasks execute in parallel and the tool returns when all complete.
pub struct ParallelTaskTool {
    executor: Arc<TaskExecutor>,
}

impl ParallelTaskTool {
    /// Create a new ParallelTaskTool
    pub fn new(executor: Arc<TaskExecutor>) -> Self {
        Self { executor }
    }
}

#[async_trait]
impl Tool for ParallelTaskTool {
    fn name(&self) -> &str {
        "parallel_task"
    }

    fn description(&self) -> &str {
        PARALLEL_TASK_TOOL_DESCRIPTION
    }

    fn parameters(&self) -> serde_json::Value {
        parallel_params::parallel_task_params_schema_for_agents(&self.executor.visible_agents())
    }

    fn definition(&self) -> ToolDefinition {
        let agents = self.executor.visible_agents();
        ToolDefinition {
            name: self.name().to_string(),
            description: delegation_tool_description(self.description(), &agents),
            parameters: parallel_params::parallel_task_params_schema_for_agents(&agents),
        }
    }

    async fn execute(&self, args: &serde_json::Value, ctx: &ToolContext) -> Result<ToolOutput> {
        let started_at = std::time::Instant::now();
        let params: ParallelTaskParams =
            serde_json::from_value(args.clone()).context("Invalid parallel task parameters")?;
        let parent_cancellation = ctx.cancellation_token();

        if params.tasks.is_empty() {
            return Ok(ToolOutput::error("No tasks provided".to_string()));
        }
        if params.tasks.len() > MAX_PARALLEL_TASKS_PER_CALL {
            return Ok(ToolOutput::error(format!(
                "parallel_task accepts at most {MAX_PARALLEL_TASKS_PER_CALL} tasks"
            )));
        }

        let task_count = params.tasks.len();
        let tasks = params.tasks.clone();

        let mut run = self
            .executor
            .execute_parallel_for_tool(
                tasks.clone(),
                ctx.agent_event_tx.clone(),
                parallel_execution::ParallelToolOptions {
                    parent_session_id: ctx.session_id.as_deref(),
                    timeout_ms: params.timeout_ms,
                    min_success_count: params.min_success_count,
                    allow_partial_failure: params.allow_partial_failure,
                    parent_cancellation: Some(&parent_cancellation),
                },
            )
            .await;
        let retry_summary = self
            .executor
            .retry_transient_parallel_failures(
                &tasks,
                parallel_execution::ParallelRetryOptions {
                    event_tx: ctx.agent_event_tx.clone(),
                    parent_session_id: ctx.session_id.as_deref(),
                    parent_cancellation: &parent_cancellation,
                    total_timeout_ms: params.timeout_ms,
                    started_at,
                },
                &mut run,
            )
            .await;
        let results = run.results;

        // Format results with compact per-task excerpts for parent context.
        let mut output = format!("Executed {} tasks in parallel:\n\n", task_count);
        let mut metadata_results = Vec::new();
        let source_anchor_counts = parallel_source_anchor_counts(&results);
        for (i, result) in results.iter().enumerate() {
            let status = if result.success { "[OK]" } else { "[ERR]" };
            let (formatted, truncated) = format_task_result_for_context(result);
            let (output_excerpt, _) = compact_task_output(&result.output);
            let source_anchors = &result.source_anchors[..source_anchor_counts[i]];
            metadata_results.push(serde_json::json!({
                "task_id": result.task_id,
                "session_id": result.session_id,
                "agent": result.agent,
                "success": result.success,
                "error_message": (!result.success).then(|| {
                    crate::text::truncate_utf8(&result.output, 1024).to_string()
                }),
                "output_excerpt": output_excerpt,
                "structured": result.structured,
                "source_anchors": source_anchors,
                "output_bytes": result.output.len(),
                "truncated_for_context": truncated,
                "artifact_id": task_artifact_id(result),
                "artifact_uri": task_artifact_uri(result),
                "retry_attempts": retry_summary.attempts_by_index.get(i).copied().unwrap_or_default(),
            }));
            output.push_str(&format!(
                "--- Task {} ({}) {} ---\n{}\n\n",
                i + 1,
                result.agent,
                status,
                formatted
            ));
        }

        let success_count = results.iter().filter(|result| result.success).count();
        let failed_count = results.len().saturating_sub(success_count);
        let all_success = failed_count == 0;
        let partial_failure = failed_count > 0 && success_count > 0;
        if retry_summary.recovered_task_count > 0 {
            output.push_str(&format!(
                "Recovered {} transient read-only child failure(s) by retrying only failed branches.\n",
                retry_summary.recovered_task_count
            ));
        }
        if params.allow_partial_failure && partial_failure {
            output.push_str(&format!(
                "Partial failure tolerated: {success_count} succeeded, {failed_count} failed.\n"
            ));
        }
        if run.timed_out {
            output.push_str(&format!(
                "Parallel task timed out after {} ms; returned completed child results and marked unfinished children failed.\n",
                run.timeout_ms.unwrap_or_default()
            ));
        } else if run.returned_early {
            output.push_str(&format!(
                "Parallel task returned after reaching min_success_count={}; unfinished children were marked failed.\n",
                run.min_success_count.unwrap_or_default()
            ));
        }

        let tool_success = all_success || (params.allow_partial_failure && success_count > 0);
        let mut output = if tool_success {
            ToolOutput::success(output)
        } else {
            ToolOutput::error(output)
        };
        if !tool_success && failed_count > 0 {
            output.error_kind = Some(crate::tools::ToolErrorKind::PartialFailure {
                failed: failed_count,
                total: results.len(),
            });
        }

        Ok(output.with_metadata(serde_json::json!({
            "task_count": task_count,
            "result_count": results.len(),
            "success_count": success_count,
            "failed_count": failed_count,
            "all_success": all_success,
            "partial_failure": partial_failure,
            "allow_partial_failure": params.allow_partial_failure,
            "timeout_ms": params.timeout_ms,
            "timed_out": run.timed_out,
            "min_success_count": params.min_success_count,
            "returned_early": run.returned_early,
            "retry_attempt_count": retry_summary.retry_attempt_count,
            "retried_task_count": retry_summary.retried_task_count,
            "recovered_task_count": retry_summary.recovered_task_count,
            "duration_ms": started_at.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
            "results": metadata_results,
        })))
    }
}

#[cfg(test)]
mod tests;