mentra 0.13.0

An agent runtime for tool-using LLM applications
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
//! Tool orchestration pipeline for scheduling, authorization, execution, and result ordering.

use std::{collections::BTreeMap, future::Future, path::PathBuf, sync::Arc, time::Duration};

use tokio::task::JoinSet;

use crate::{
    ContentBlock,
    agent::{Agent, AgentEvent, AgentStatus},
    error::RuntimeError,
    runtime::control::{HookDecision, PreExecutionContext},
    runtime::{RunOptions, RuntimeHookEvent},
    tool::{
        ExecutableTool, ParallelToolContext, RuntimeToolDescriptor, ToolAuthorizationOutcome,
        ToolAuthorizationRequest, ToolCall, ToolCapability, ToolContext, ToolExecutionCategory,
    },
};

use super::{
    paging::{READ_TOOL_RESULT_TOOL, ToolResultPager},
    truncation::{SpillBehavior, ToolOutputLimiter},
};

const PARALLEL_JOIN_POLL_INTERVAL: Duration = Duration::from_millis(10);

pub(crate) struct ToolExecutionOutcome {
    pub(crate) results: Vec<ContentBlock>,
    pub(crate) successful_task: bool,
    pub(crate) end_turn: bool,
    /// Per-call opaque metadata collected from this round's executions,
    /// keyed by `tool_use_id` — the runner attaches this to the appended
    /// transcript item so it survives persistence and replay, never
    /// projected to a provider (ADR-0001 §4).
    pub(crate) details: BTreeMap<String, serde_json::Value>,
}

pub(crate) struct ToolRuntime {
    runtime: crate::runtime::handle::RuntimeHandle,
    agent_id: String,
    tool_calls: usize,
    working_directory: Option<PathBuf>,
    output_limiter: ToolOutputLimiter,
    /// `Some` only when this agent enables tool-result paging; `None` leaves
    /// every result exactly as the limiter produced it.
    pager: Option<ToolResultPager>,
}

#[derive(Clone)]
enum ToolCallBatch {
    Exclusive(ToolCall),
    Parallel(Vec<ToolCall>),
}

struct ToolCallSchedule {
    batches: Vec<ToolCallBatch>,
}

struct CompletedToolExecution {
    result: ContentBlock,
    task_succeeded: bool,
    /// Ends the current round: true when this execution consumed
    /// [`crate::tool::ToolContext::request_idle`] (exclusive lane) or its
    /// [`crate::tool::ToolOutput::terminate`] successor. Controls whether
    /// `TurnRunner::run` issues another model round.
    should_end_turn: bool,
    /// True only when `should_end_turn` came from `ToolOutput::terminate`
    /// specifically (never from the pre-existing idle-request signal).
    /// Distinct from `should_end_turn` because it additionally drives
    /// skipping not-yet-executed batches later in the same round — a new
    /// behavior scoped to genuine termination, not to idle requests, so
    /// existing `request_idle` callers see unchanged behavior.
    terminated: bool,
    tool_name: String,
    /// This execution's opaque `ToolOutput::details`, if any — collected by
    /// [`ToolRuntime::execute_calls`] into [`ToolExecutionOutcome::details`].
    details: Option<serde_json::Value>,
}

/// How a single execution affects the current round — bundled so
/// [`ToolRuntime::completed_execution`] stays within a reasonable argument
/// count. `Default` is "continues": neither ends the round nor terminates.
#[derive(Debug, Clone, Copy, Default)]
struct RoundEffect {
    should_end_turn: bool,
    terminated: bool,
}

impl ToolRuntime {
    pub(crate) fn new(agent: &Agent) -> Self {
        let runtime = agent.runtime_handle();
        let policy = &runtime.execution.policy;
        let spill = if !policy.spill_full_tool_output {
            SpillBehavior::Disabled("spill-to-file is disabled by runtime policy")
        } else if !runtime.persistence.store.allows_disk_artifacts() {
            SpillBehavior::Disabled("the runtime store forbids durable artifacts")
        } else {
            SpillBehavior::Enabled(agent.config().compaction.transcript_dir.join("tool-output"))
        };
        let output_limiter = ToolOutputLimiter::new(
            policy.max_tool_result_bytes,
            policy.max_tool_result_lines,
            spill,
        );
        Self {
            runtime,
            agent_id: agent.id().to_string(),
            tool_calls: 0,
            working_directory: None,
            output_limiter,
            pager: agent.config().tool_result_paging.map(ToolResultPager::new),
        }
    }

    pub(crate) async fn execute_calls(
        &mut self,
        agent: &mut Agent,
        options: &RunOptions,
        calls: Vec<ToolCall>,
    ) -> Result<ToolExecutionOutcome, RuntimeError> {
        let mut results = Vec::new();
        let mut successful_task = false;
        let mut end_turn = false;
        let mut details = BTreeMap::new();

        let mut batches = ToolCallSchedule::new(self, agent, calls)
            .batches
            .into_iter();

        while let Some(batch) = batches.next() {
            options.check_limits()?;
            let execution_count = batch.execution_count();
            if self.tool_calls + execution_count > options.tool_budget() {
                return Err(RuntimeError::ToolBudgetExceeded(options.tool_budget()));
            }
            self.tool_calls += execution_count;

            let executions = match batch {
                ToolCallBatch::Exclusive(call) => vec![self.execute_one_tool(agent, call).await?],
                ToolCallBatch::Parallel(calls) => {
                    self.execute_parallel_batch(agent, options, calls).await?
                }
            };

            let mut terminator = None;
            for execution in executions {
                successful_task |= execution.task_succeeded;
                end_turn |= execution.should_end_turn;
                let result = self.page_result(agent, &execution.tool_name, execution.result);
                if execution.terminated {
                    terminator.get_or_insert(execution.tool_name);
                }
                if let (Some(value), ContentBlock::ToolResult { tool_use_id, .. }) =
                    (execution.details, &result)
                {
                    details.insert(tool_use_id.clone(), value);
                }
                results.push(result);
            }

            // A terminating call ends the round as the value of its own
            // execution; calls already scheduled for later batches in this
            // round are never executed. Each still gets an explicit
            // is_error result so the transcript always has one result block
            // per tool_use — never a silent drop.
            if let Some(terminator) = terminator {
                for remaining_batch in batches {
                    for call in remaining_batch.into_calls() {
                        let result = not_executed_result(&call, &terminator);
                        results.push(self.page_result(agent, &call.name, result));
                    }
                }
                break;
            }
        }

        Ok(ToolExecutionOutcome {
            results,
            successful_task,
            end_turn,
            details,
        })
    }

    /// Replaces an oversized text result with its first window, retaining the
    /// full text on the agent for `read_tool_result` to serve.
    ///
    /// This is the single point where a result becomes the *model's* view of
    /// itself: every `AgentEvent::ToolExecutionFinished` has already been
    /// emitted with the complete block by the time a result reaches here, so
    /// consumers reconstructing evidence from the event stream observe no
    /// change at all. Applied to every block that joins the round's committed
    /// message — including the fixed not-executed and not-found results — so
    /// no path into the transcript bypasses the bound.
    fn page_result(&self, agent: &Agent, tool_name: &str, result: ContentBlock) -> ContentBlock {
        let Some(pager) = self.pager else {
            return result;
        };
        // A window returned by `read_tool_result` is bounded by construction;
        // paging it again would nest a trailer inside a trailer.
        if tool_name == READ_TOOL_RESULT_TOOL {
            return result;
        }
        let ContentBlock::ToolResult {
            tool_use_id,
            content: mentra_provider::ToolResultContent::Text(text),
            is_error,
        } = result
        else {
            return result;
        };

        let Some(page) = pager.first_page(&tool_use_id, &text) else {
            return ContentBlock::ToolResult {
                tool_use_id,
                content: mentra_provider::ToolResultContent::Text(text),
                is_error,
            };
        };
        agent.record_paged_tool_result(&tool_use_id, &text);
        ContentBlock::ToolResult {
            tool_use_id,
            content: mentra_provider::ToolResultContent::Text(page),
            is_error,
        }
    }

    fn call_execution_category_for_agent(
        &self,
        call: &ToolCall,
        agent: Option<&Agent>,
    ) -> ToolExecutionCategory {
        if agent.is_some_and(|agent| !agent.can_use_tool(&call.name)) {
            return ToolExecutionCategory::ExclusiveLocalMutation;
        }

        let Some(tool) = self.runtime.get_tool(&call.name) else {
            return ToolExecutionCategory::ExclusiveLocalMutation;
        };
        let category = tool.execution_category(&call.input);
        let terminal = self
            .runtime
            .get_tool_descriptor(&call.name)
            .is_some_and(|descriptor| descriptor.terminal);

        // STATIC exclusivity: a terminal-marked tool is never scheduled in a
        // parallel batch, regardless of its declared execution_category —
        // coerce rather than panic, matching the existing fallback-to-exclusive
        // precedent above.
        if terminal && category.allows_parallel() {
            eprintln!(
                "warning: tool '{}' is marked terminal but declared a parallel \
                 execution category; coercing to exclusive scheduling",
                call.name
            );
            return ToolExecutionCategory::ExclusiveLocalMutation;
        }

        category
    }

    fn note_tool_started(
        &mut self,
        agent: &mut Agent,
        call: &ToolCall,
    ) -> Result<(), RuntimeError> {
        agent.set_status(AgentStatus::ExecutingTool {
            id: call.id.clone(),
            name: call.name.clone(),
        });
        agent.emit_event(AgentEvent::ToolExecutionStarted { call: call.clone() });
        agent.update_run_state("executing_tool", None)
    }

    fn emit_tool_runtime_started(&self, call: &ToolCall) -> Result<(), RuntimeError> {
        self.runtime
            .emit_hook(RuntimeHookEvent::ToolExecutionStarted {
                agent_id: self.agent_id.clone(),
                tool_name: call.name.clone(),
                tool_call_id: call.id.clone(),
            })
    }

    fn emit_tool_runtime_finished(
        &self,
        call: &ToolCall,
        result: &ContentBlock,
        details: Option<serde_json::Value>,
    ) {
        let is_error = matches!(result, ContentBlock::ToolResult { is_error: true, .. });
        let output_preview = match result {
            ContentBlock::ToolResult { content, .. } => content.to_display_string(),
            _ => String::new(),
        };
        let error = is_error.then_some(output_preview.clone());
        let _ = self
            .runtime
            .emit_hook(RuntimeHookEvent::ToolExecutionFinished {
                agent_id: self.agent_id.clone(),
                tool_name: call.name.clone(),
                tool_call_id: call.id.clone(),
                is_error,
                error,
                output_preview,
                details,
            });
    }

    fn emit_tool_authorization_started(
        &self,
        call: &ToolCall,
        preview: crate::tool::ToolAuthorizationPreview,
    ) -> Result<(), RuntimeError> {
        self.runtime
            .emit_hook(RuntimeHookEvent::ToolAuthorizationStarted {
                agent_id: self.agent_id.clone(),
                tool_name: call.name.clone(),
                tool_call_id: call.id.clone(),
                preview,
            })
    }

    fn emit_tool_authorization_finished(
        &self,
        call: &ToolCall,
        outcome: ToolAuthorizationOutcome,
        reason: Option<String>,
    ) -> Result<(), RuntimeError> {
        self.runtime
            .emit_hook(RuntimeHookEvent::ToolAuthorizationFinished {
                agent_id: self.agent_id.clone(),
                tool_name: call.name.clone(),
                tool_call_id: call.id.clone(),
                outcome,
                reason,
            })
    }

    fn emit_tool_authorization_blocked(
        &self,
        call: &ToolCall,
        outcome: ToolAuthorizationOutcome,
        reason: Option<String>,
    ) -> Result<(), RuntimeError> {
        self.runtime
            .emit_hook(RuntimeHookEvent::ToolAuthorizationBlocked {
                agent_id: self.agent_id.clone(),
                tool_name: call.name.clone(),
                tool_call_id: call.id.clone(),
                outcome,
                reason,
            })
    }

    fn run_pre_hooks(&self, call: &ToolCall) -> Result<HookDecision, RuntimeError> {
        let context = PreExecutionContext {
            agent_id: self.agent_id.clone(),
            tool_name: call.name.clone(),
            tool_call_id: call.id.clone(),
            input_json: serde_json::to_string(&call.input).unwrap_or_default(),
        };
        self.runtime.pre_hooks().run(&context)
    }

    fn emit_tool_execution_blocked(&self, call: &ToolCall, reason: &str) {
        let _ = self
            .runtime
            .emit_hook(RuntimeHookEvent::ToolExecutionBlocked {
                agent_id: self.agent_id.clone(),
                tool_name: call.name.clone(),
                tool_call_id: call.id.clone(),
                reason: reason.to_string(),
            });
    }

    fn unavailable_tool_result(&self, call: ToolCall) -> ContentBlock {
        ContentBlock::ToolResult {
            tool_use_id: call.id,
            content: format!("Tool '{}' is not available for this agent", call.name).into(),
            is_error: true,
        }
    }

    fn blocked_tool_result(&self, call: &ToolCall, error: RuntimeError) -> ContentBlock {
        ContentBlock::ToolResult {
            tool_use_id: call.id.clone(),
            content: format!("Tool execution blocked: {error}").into(),
            is_error: true,
        }
    }

    fn blocked_authorization_result(
        &self,
        call: &ToolCall,
        outcome: ToolAuthorizationOutcome,
        reason: Option<String>,
    ) -> ContentBlock {
        let content = match outcome {
            ToolAuthorizationOutcome::Allow => "Tool execution blocked by authorizer".to_string(),
            ToolAuthorizationOutcome::Prompt => reason
                .map(|reason| format!("Tool execution requires approval: {reason}"))
                .unwrap_or_else(|| "Tool execution requires approval".to_string()),
            ToolAuthorizationOutcome::Deny => reason
                .map(|reason| format!("Tool execution denied: {reason}"))
                .unwrap_or_else(|| "Tool execution denied by authorizer".to_string()),
        };

        ContentBlock::ToolResult {
            tool_use_id: call.id.clone(),
            content: content.into(),
            is_error: true,
        }
    }

    /// Splits a structured tool outcome into its provider-visible
    /// projection, opaque host metadata, and requested termination — the
    /// single boundary where `details` is separated from what a provider
    /// ever sees (only `content` reaches `ContentBlock::ToolResult`).
    async fn tool_output_block(
        &self,
        call: &ToolCall,
        output: Result<crate::tool::ToolOutput, String>,
    ) -> (ContentBlock, Option<serde_json::Value>, bool) {
        match output {
            Ok(output) => (
                ContentBlock::ToolResult {
                    tool_use_id: call.id.clone(),
                    content: self.output_limiter.apply(output.content).await,
                    is_error: false,
                },
                output.details,
                output.terminate,
            ),
            Err(content) => (
                ContentBlock::ToolResult {
                    tool_use_id: call.id.clone(),
                    content: self
                        .output_limiter
                        .apply(mentra_provider::ToolResultContent::Text(content))
                        .await,
                    is_error: true,
                },
                None,
                false,
            ),
        }
    }

    fn completed_execution(
        &self,
        agent: &Agent,
        call: &ToolCall,
        descriptor: &RuntimeToolDescriptor,
        result: ContentBlock,
        effect: RoundEffect,
        details: Option<serde_json::Value>,
    ) -> CompletedToolExecution {
        self.emit_tool_runtime_finished(call, &result, details.clone());
        agent.emit_event(AgentEvent::ToolExecutionFinished {
            result: result.clone(),
        });
        let task_succeeded = matches!(
            &result,
            ContentBlock::ToolResult {
                is_error: false,
                ..
            }
        ) && descriptor
            .capabilities
            .iter()
            .any(|capability| matches!(capability, ToolCapability::TaskMutation));

        CompletedToolExecution {
            result,
            task_succeeded,
            should_end_turn: effect.should_end_turn,
            terminated: effect.terminated,
            tool_name: call.name.clone(),
            details,
        }
    }

    fn working_directory(&mut self) -> std::path::PathBuf {
        if let Some(path) = &self.working_directory {
            return path.clone();
        }

        let path = self
            .runtime
            .resolve_working_directory(&self.agent_id, None)
            .unwrap_or_else(|_| self.runtime.default_working_directory(&self.agent_id));
        self.working_directory = Some(path.clone());
        path
    }

    fn parallel_tool_context(&mut self, agent: &Agent, call: &ToolCall) -> ParallelToolContext {
        ParallelToolContext {
            agent_id: self.agent_id.clone(),
            tool_call_id: call.id.clone(),
            tool_name: call.name.clone(),
            working_directory: self.working_directory(),
            runtime: self.runtime.clone(),
            subagent_template: agent.disposable_subagent_template(),
            agent_name: agent.name().to_string(),
            model: agent.model().to_string(),
            history_len: agent.history().len(),
            tasks: agent.tasks().to_vec(),
            event_tx: agent.event_sender(),
        }
    }

    fn registered_tool(
        &self,
        name: &str,
    ) -> Option<(Arc<dyn ExecutableTool>, RuntimeToolDescriptor)> {
        let tool = self.runtime.get_tool(name)?;
        let descriptor = self.runtime.get_tool_descriptor(name)?;
        Some((tool, descriptor))
    }

    async fn authorize_tool_call(
        &self,
        call: &ToolCall,
        tool: &Arc<dyn ExecutableTool>,
        ctx: &ParallelToolContext,
    ) -> Result<Option<ContentBlock>, RuntimeError> {
        let Some(authorizer) = self.runtime.execution.tool_authorizer.clone() else {
            return Ok(None);
        };

        let preview = match tool.authorization_preview(ctx, &call.input) {
            Ok(preview) => preview,
            Err(error) => {
                return Ok(Some(self.blocked_authorization_result(
                    call,
                    ToolAuthorizationOutcome::Deny,
                    Some(error),
                )));
            }
        };

        self.emit_tool_authorization_started(call, preview.clone())?;
        let request = ToolAuthorizationRequest {
            agent_id: self.agent_id.clone(),
            agent_name: ctx.agent_name().to_string(),
            model: ctx.model().to_string(),
            history_len: ctx.history_len(),
            tool_call_id: call.id.clone(),
            tool_name: call.name.clone(),
            preview,
        };

        let result = match authorizer.timeout() {
            Some(timeout) => {
                match tokio::time::timeout(timeout, authorizer.authorize(&request)).await {
                    Ok(result) => result,
                    Err(_) => {
                        return self.handle_authorization_block(
                            call,
                            ToolAuthorizationOutcome::Deny,
                            Some(format!(
                                "authorizer timed out after {}",
                                format_duration(timeout)
                            )),
                        );
                    }
                }
            }
            None => authorizer.authorize(&request).await,
        };

        match result {
            Ok(decision) => match decision.outcome {
                ToolAuthorizationOutcome::Allow => {
                    self.emit_tool_authorization_finished(call, decision.outcome, decision.reason)?;
                    Ok(None)
                }
                outcome => self.handle_authorization_block(call, outcome, decision.reason),
            },
            Err(error) => self.handle_authorization_block(
                call,
                ToolAuthorizationOutcome::Deny,
                Some(error.to_string()),
            ),
        }
    }

    fn handle_authorization_block(
        &self,
        call: &ToolCall,
        outcome: ToolAuthorizationOutcome,
        reason: Option<String>,
    ) -> Result<Option<ContentBlock>, RuntimeError> {
        self.emit_tool_authorization_finished(call, outcome, reason.clone())?;
        self.emit_tool_authorization_blocked(call, outcome, reason.clone())?;
        Ok(Some(
            self.blocked_authorization_result(call, outcome, reason),
        ))
    }

    async fn execute_one_tool(
        &mut self,
        agent: &mut Agent,
        call: ToolCall,
    ) -> Result<CompletedToolExecution, RuntimeError> {
        self.note_tool_started(agent, &call)?;
        if !agent.can_use_tool(&call.name) {
            let result = self.unavailable_tool_result(call.clone());
            agent.emit_event(AgentEvent::ToolExecutionFinished {
                result: result.clone(),
            });
            return Ok(CompletedToolExecution {
                result,
                task_succeeded: false,
                should_end_turn: false,
                terminated: false,
                tool_name: call.name.clone(),
                details: None,
            });
        }

        Ok(self.execute_registered_tool(agent, call).await)
    }

    async fn execute_parallel_batch(
        &mut self,
        agent: &mut Agent,
        options: &RunOptions,
        calls: Vec<ToolCall>,
    ) -> Result<Vec<CompletedToolExecution>, RuntimeError> {
        let len = calls.len();
        let mut results = (0..len).map(|_| None).collect::<Vec<_>>();
        let mut join_set = JoinSet::new();

        for (index, call) in calls.iter().cloned().enumerate() {
            if let Err(error) = self.note_tool_started(agent, &call) {
                join_set.abort_all();
                return Err(error);
            }

            let Some((tool, descriptor)) = self.registered_tool(&call.name) else {
                let result = ContentBlock::ToolResult {
                    tool_use_id: call.id.clone(),
                    content: "Tool not found".into(),
                    is_error: true,
                };
                agent.emit_event(AgentEvent::ToolExecutionFinished {
                    result: result.clone(),
                });
                results[index] = Some(CompletedToolExecution {
                    result,
                    task_succeeded: false,
                    should_end_turn: false,
                    terminated: false,
                    tool_name: call.name.clone(),
                    details: None,
                });
                continue;
            };

            let ctx = self.parallel_tool_context(agent, &call);
            if let Some(result) = self.authorize_tool_call(&call, &tool, &ctx).await? {
                let execution = self.completed_execution(
                    agent,
                    &call,
                    &descriptor,
                    result,
                    RoundEffect::default(),
                    None,
                );
                results[index] = Some(execution);
                continue;
            }

            // Pre-execution hook check
            match self.run_pre_hooks(&call)? {
                HookDecision::Allow => {}
                HookDecision::Deny(reason) => {
                    self.emit_tool_execution_blocked(&call, &reason);
                    let result = ContentBlock::ToolResult {
                        tool_use_id: call.id.clone(),
                        content: format!("Blocked by pre-execution hook: {reason}").into(),
                        is_error: true,
                    };
                    let execution = self.completed_execution(
                        agent,
                        &call,
                        &descriptor,
                        result,
                        RoundEffect::default(),
                        None,
                    );
                    results[index] = Some(execution);
                    continue;
                }
            }

            if let Err(error) = self.emit_tool_runtime_started(&call) {
                let result = self.blocked_tool_result(&call, error);
                let execution = self.completed_execution(
                    agent,
                    &call,
                    &descriptor,
                    result,
                    RoundEffect::default(),
                    None,
                );
                results[index] = Some(execution);
                continue;
            }

            join_set.spawn(async move {
                let output = execute_tool_future(
                    &call.name,
                    descriptor.execution_timeout,
                    tool.execute_output(ctx, call.input.clone()),
                )
                .await;
                (index, call, descriptor, output)
            });
        }

        while !join_set.is_empty() {
            if let Err(error) = options.check_limits() {
                join_set.abort_all();
                return Err(error);
            }
            match tokio::time::timeout(PARALLEL_JOIN_POLL_INTERVAL, join_set.join_next()).await {
                Ok(Some(Ok((index, call, descriptor, output)))) => {
                    let (result, details, terminate) = self.tool_output_block(&call, output).await;
                    // RUNTIME defense: a parallel-lane execution can never end
                    // the run — a `terminate: true` surfacing here is a tool
                    // misuse (or a static-coercion gap), never honored as
                    // termination, and never a silent race with the rest of
                    // the batch.
                    let (result, details) = if terminate {
                        eprintln!(
                            "warning: tool '{}' requested termination from a parallel \
                             execution; rejecting as a misuse error, run continues",
                            call.name
                        );
                        (parallel_termination_rejected(&call), None)
                    } else {
                        (result, details)
                    };
                    results[index] = Some(self.completed_execution(
                        agent,
                        &call,
                        &descriptor,
                        result,
                        RoundEffect::default(),
                        details,
                    ));
                }
                Ok(Some(Err(error))) => {
                    join_set.abort_all();
                    return Err(RuntimeError::Store(format!(
                        "parallel tool task failed: {error}"
                    )));
                }
                Ok(None) => break,
                Err(_) => continue,
            }
        }

        if let Err(error) = options.check_limits() {
            join_set.abort_all();
            return Err(error);
        }

        let mut ordered = Vec::with_capacity(len);
        for result in results {
            ordered.push(result.ok_or_else(|| {
                RuntimeError::Store("parallel tool batch lost a result".to_string())
            })?);
        }

        Ok(ordered)
    }

    async fn execute_registered_tool(
        &mut self,
        agent: &mut Agent,
        call: ToolCall,
    ) -> CompletedToolExecution {
        let Some((tool, descriptor)) = self.registered_tool(&call.name) else {
            let result = ContentBlock::ToolResult {
                tool_use_id: call.id.clone(),
                content: "Tool not found".into(),
                is_error: true,
            };
            agent.emit_event(AgentEvent::ToolExecutionFinished {
                result: result.clone(),
            });
            return CompletedToolExecution {
                result,
                task_succeeded: false,
                should_end_turn: false,
                terminated: false,
                tool_name: call.name.clone(),
                details: None,
            };
        };

        let authorization_ctx = self.parallel_tool_context(agent, &call);
        match self
            .authorize_tool_call(&call, &tool, &authorization_ctx)
            .await
        {
            Ok(Some(result)) => {
                return self.completed_execution(
                    agent,
                    &call,
                    &descriptor,
                    result,
                    RoundEffect::default(),
                    None,
                );
            }
            Ok(None) => {}
            Err(error) => {
                let result = self.blocked_tool_result(&call, error);
                return self.completed_execution(
                    agent,
                    &call,
                    &descriptor,
                    result,
                    RoundEffect::default(),
                    None,
                );
            }
        }

        // Pre-execution hook check
        match self.run_pre_hooks(&call) {
            Ok(HookDecision::Allow) => {}
            Ok(HookDecision::Deny(reason)) => {
                self.emit_tool_execution_blocked(&call, &reason);
                let result = ContentBlock::ToolResult {
                    tool_use_id: call.id.clone(),
                    content: format!("Blocked by pre-execution hook: {reason}").into(),
                    is_error: true,
                };
                return self.completed_execution(
                    agent,
                    &call,
                    &descriptor,
                    result,
                    RoundEffect::default(),
                    None,
                );
            }
            Err(error) => {
                let result = self.blocked_tool_result(&call, error);
                return self.completed_execution(
                    agent,
                    &call,
                    &descriptor,
                    result,
                    RoundEffect::default(),
                    None,
                );
            }
        }

        if let Err(error) = self.emit_tool_runtime_started(&call) {
            let result = self.blocked_tool_result(&call, error);
            return self.completed_execution(
                agent,
                &call,
                &descriptor,
                result,
                RoundEffect::default(),
                None,
            );
        }

        let working_directory = authorization_ctx.working_directory.clone();
        let runtime = authorization_ctx.runtime.clone();
        let event_tx = agent.event_sender();
        let (result, details, terminate) = self
            .tool_output_block(
                &call,
                execute_tool_future(
                    &call.name,
                    descriptor.execution_timeout,
                    tool.execute_mut_output(
                        ToolContext {
                            agent_id: self.agent_id.clone(),
                            tool_call_id: call.id.clone(),
                            tool_name: call.name.clone(),
                            working_directory,
                            runtime,
                            agent,
                            event_tx,
                        },
                        call.input.clone(),
                    ),
                )
                .await,
            )
            .await;
        let effect = RoundEffect {
            should_end_turn: agent.take_idle_requested() || terminate,
            terminated: terminate,
        };
        self.completed_execution(agent, &call, &descriptor, result, effect, details)
    }
}

impl ToolCallSchedule {
    fn new(runtime: &ToolRuntime, agent: &Agent, calls: Vec<ToolCall>) -> Self {
        let mut batches = Vec::new();
        let mut pending_parallel = Vec::new();

        for call in calls {
            match runtime.call_execution_category_for_agent(&call, Some(agent)) {
                ToolExecutionCategory::ReadOnlyParallel => pending_parallel.push(call),
                ToolExecutionCategory::ExclusiveLocalMutation
                | ToolExecutionCategory::ExclusivePersistentMutation
                | ToolExecutionCategory::BackgroundJob
                | ToolExecutionCategory::Delegation => {
                    if !pending_parallel.is_empty() {
                        batches.push(ToolCallBatch::Parallel(std::mem::take(
                            &mut pending_parallel,
                        )));
                    }
                    batches.push(ToolCallBatch::Exclusive(call));
                }
            }
        }

        if !pending_parallel.is_empty() {
            batches.push(ToolCallBatch::Parallel(pending_parallel));
        }

        Self { batches }
    }
}

impl ToolCallBatch {
    fn execution_count(&self) -> usize {
        match self {
            ToolCallBatch::Exclusive(_) => 1,
            ToolCallBatch::Parallel(calls) => calls.len(),
        }
    }

    /// Unwraps this batch into its constituent calls, in original call order.
    /// Used to build not-executed results for batches skipped by termination.
    fn into_calls(self) -> Vec<ToolCall> {
        match self {
            ToolCallBatch::Exclusive(call) => vec![call],
            ToolCallBatch::Parallel(calls) => calls,
        }
    }
}

/// Builds the is_error result for a call that was never executed because an
/// earlier call in the same round terminated the run.
fn not_executed_result(call: &ToolCall, terminated_by: &str) -> ContentBlock {
    ContentBlock::ToolResult {
        tool_use_id: call.id.clone(),
        content: format!("not executed: run terminated by '{terminated_by}'").into(),
        is_error: true,
    }
}

/// Builds the is_error result for a parallel-lane call that requested
/// termination — RUNTIME defense: never honored, always surfaced as misuse.
fn parallel_termination_rejected(call: &ToolCall) -> ContentBlock {
    ContentBlock::ToolResult {
        tool_use_id: call.id.clone(),
        content: format!(
            "not honored: tool '{}' requested termination from a parallel execution; \
             termination is only honored from an exclusive execution",
            call.name
        )
        .into(),
        is_error: true,
    }
}

async fn execute_tool_future<F, T>(
    tool_name: &str,
    execution_timeout: Option<Duration>,
    future: F,
) -> Result<T, String>
where
    F: Future<Output = Result<T, String>>,
{
    match execution_timeout {
        Some(timeout) => match tokio::time::timeout(timeout, future).await {
            Ok(result) => result,
            Err(_) => Err(format!(
                "Tool '{tool_name}' timed out after {}",
                format_duration(timeout)
            )),
        },
        None => future.await,
    }
}

fn format_duration(duration: Duration) -> String {
    if duration.as_secs() > 0 && duration.subsec_nanos() == 0 {
        format!("{}s", duration.as_secs())
    } else if duration.as_millis() > 0 {
        format!("{}ms", duration.as_millis())
    } else if duration.as_micros() > 0 {
        format!("{}us", duration.as_micros())
    } else {
        format!("{}ns", duration.as_nanos())
    }
}