openheim 0.6.0

A fast, multi-provider LLM agent runtime written in Rust
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
//! Subagent delegation: a tool that lets the orchestrating agent hand off a
//! self-contained task to a subagent — either a named profile from
//! `~/.openheim/agents/` (see [`crate::subagents`]) or an ephemeral one the
//! orchestrator defines inline in the tool call itself (a `system_prompt` plus
//! optional model/tools overrides). Inline subagents exist only for the duration
//! of the call and are never persisted anywhere.
//!
//! Each call to `delegate_task` runs a fresh, isolated [`run_agent_with_history`]
//! turn — its own message history, its own system prompt (the profile's persona,
//! not the parent's `system.md`/skills), and optionally its own model/provider and
//! restricted tool set — and returns only the subagent's final answer. The
//! orchestrator never sees the subagent's intermediate steps, exactly like
//! Claude Code's `Task` subagents.

use std::path::PathBuf;
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::json;

use crate::config::{AgentConfig, AppConfig, client_for_config};
use crate::core::agent::run_agent_with_history;
use crate::core::client_io::NoClientIo;
use crate::core::llm::LlmClient;
use crate::core::models::{FunctionDefinition, Message, StopReason, Tool};
use crate::core::turn::TurnContext;
use crate::error::{Error, Result};
use crate::rag::PromptBuilder;
use crate::subagents::AgentProfile;

use super::scoped_executor::ScopedExecutor;
use super::{SandboxedExecutor, ToolExecutor};

/// Name under which [`DelegateTool`] is exposed to the orchestrating LLM.
pub const DELEGATE_TOOL_NAME: &str = "delegate_task";

/// Routes `delegate_task` calls to a named [`AgentProfile`], running each as an
/// isolated agent-loop turn.
///
/// `base_executor` is deliberately the executor as it exists *before*
/// `delegate_task` is added to it (see [`with_delegation`]): subagents are built
/// from this delegate-free view, so `delegate_task` is structurally absent from
/// their own tool list. This rules out recursive delegation by construction —
/// no depth counters or runtime checks are needed.
pub struct DelegateTool {
    base_executor: Arc<dyn ToolExecutor>,
    work_dir: PathBuf,
    allow_shell: bool,
    profiles: Vec<AgentProfile>,
    llm: Arc<dyn LlmClient>,
    app_config: AppConfig,
    base_config: AgentConfig,
}

impl DelegateTool {
    pub fn new(
        base_executor: Arc<dyn ToolExecutor>,
        work_dir: PathBuf,
        allow_shell: bool,
        profiles: Vec<AgentProfile>,
        llm: Arc<dyn LlmClient>,
        app_config: AppConfig,
        base_config: AgentConfig,
    ) -> Self {
        Self {
            base_executor,
            work_dir,
            allow_shell,
            profiles,
            llm,
            app_config,
            base_config,
        }
    }

    fn find_profile(&self, name: &str) -> Option<&AgentProfile> {
        self.profiles.iter().find(|p| p.name == name)
    }

    /// Resolves the [`AgentConfig`] and [`LlmClient`] a subagent run should use,
    /// honouring the profile's optional `model`/`provider`/`max_iterations`
    /// overrides. Reuses the parent's client when the resolved provider and model
    /// match — otherwise builds a fresh one, mirroring the pattern `acp_prompt`
    /// already uses for per-session model switches (see `src/acp/mod.rs`).
    fn resolve_runtime(&self, profile: &AgentProfile) -> Result<(AgentConfig, Arc<dyn LlmClient>)> {
        let config = match (&profile.provider, &profile.model) {
            (Some(provider), Some(model)) => {
                self.app_config.resolve_with_provider(provider, model)?
            }
            (None, Some(model)) => self.app_config.resolve(Some(model))?,
            _ => self.base_config.clone(),
        };
        let config = match profile.max_iterations {
            Some(max_iterations) => config.with_max_iterations(max_iterations),
            None => config,
        };

        let llm = client_for_config(&config, &self.base_config, &self.llm)?;

        Ok((config, llm))
    }

    /// Builds the tool executor a subagent run should use: the shared,
    /// delegate-free base executor, optionally narrowed to the profile's `tools`
    /// allowlist, wrapped in the same sandbox boundary (`work_dir`/`allow_shell`)
    /// as the parent so subagents cannot escalate privileges.
    fn build_executor(&self, profile: &AgentProfile) -> Arc<dyn ToolExecutor> {
        let scoped: Arc<dyn ToolExecutor> = match &profile.tools {
            Some(allowed) => Arc::new(ScopedExecutor::new(
                self.base_executor.clone(),
                allowed.clone(),
            )),
            None => self.base_executor.clone(),
        };
        Arc::new(SandboxedExecutor::new(
            scoped,
            self.work_dir.clone(),
            self.allow_shell,
            Arc::new(NoClientIo),
        ))
    }

    /// Not a [`ToolHandler`](super::ToolHandler): unlike ordinary tools,
    /// `delegate_task` needs the calling turn's [`TurnContext`] to spawn its
    /// subagent run (see [`Self::execute`]), so it's dispatched directly by
    /// [`WithDelegate`] rather than registered into a [`super::SystemToolExecutor`].
    pub fn definition(&self) -> Tool {
        let listing = if self.profiles.is_empty() {
            "\n(none configured — define one inline via `system_prompt`)".to_string()
        } else {
            let mut listing = String::new();
            for profile in &self.profiles {
                let description = if profile.description.is_empty() {
                    "(no description provided)"
                } else {
                    profile.description.as_str()
                };
                listing.push_str(&format!("\n- `{}`: {description}", profile.name));
            }
            listing
        };

        let description = format!(
            "Delegate a self-contained task to a specialized subagent that runs independently \
             with its own context, persona, and (optionally) its own model or restricted tool \
             set. The subagent CANNOT see this conversation, so `task` must be a complete, \
             standalone brief containing every detail it needs. Only its final answer is \
             returned to you — its intermediate steps are not visible.\n\
             \n\
             Pick a pre-configured subagent by `agent` name, OR define an ephemeral one \
             inline by providing `system_prompt` (with optional `tools`, `model`, \
             `provider`, `max_iterations`). Inline subagents exist only for this one call \
             and are not saved. Exactly one of `agent` or `system_prompt` is required.\n\
             \n\
             Available subagents:{listing}"
        );

        let mut agent_schema = json!({
            "type": "string",
            "description": "Name of a pre-configured subagent to delegate to. \
                            Mutually exclusive with `system_prompt`."
        });
        if !self.profiles.is_empty() {
            let names: Vec<String> = self.profiles.iter().map(|p| p.name.clone()).collect();
            agent_schema["enum"] = json!(names);
        }

        Tool {
            tool_type: "function".to_string(),
            function: FunctionDefinition {
                name: DELEGATE_TOOL_NAME.to_string(),
                description,
                parameters: json!({
                    "type": "object",
                    "properties": {
                        "agent": agent_schema,
                        "system_prompt": {
                            "type": "string",
                            "description": "System prompt for an ephemeral inline subagent — \
                                            its persona and instructions. Mutually exclusive \
                                            with `agent`."
                        },
                        "tools": {
                            "type": "array",
                            "items": { "type": "string" },
                            "description": "Inline subagent only: restrict it to this set of \
                                            tool names. Omitted = it inherits your full tool set."
                        },
                        "model": {
                            "type": "string",
                            "description": "Inline subagent only: run it on this model instead \
                                            of yours."
                        },
                        "provider": {
                            "type": "string",
                            "description": "Inline subagent only: provider for `model`. Only \
                                            used when `model` is also set."
                        },
                        "max_iterations": {
                            "type": "integer",
                            "description": "Inline subagent only: cap its agent-loop iterations."
                        },
                        "task": {
                            "type": "string",
                            "description": "A complete, self-contained description of the task. \
                                            Include all context the subagent needs — it cannot \
                                            see your conversation history."
                        }
                    },
                    "required": ["task"]
                }),
            },
        }
    }

    /// Runs the delegated subagent turn, reusing `turn`'s cancellation token
    /// and permission gate rather than manufacturing fresh ones: a
    /// `session/cancel` on the orchestrating turn must stop the subagent too,
    /// and there is no separate trust policy for subagent tool calls — they
    /// go through the same approval flow (e.g. `session/request_permission`)
    /// as the orchestrator's own.
    pub async fn execute(&self, args: &str, turn: &TurnContext<'_>) -> Result<String> {
        let v: serde_json::Value = serde_json::from_str(args)
            .map_err(|e| Error::ParseError(format!("invalid arguments: {e}")))?;

        let task = v["task"]
            .as_str()
            .ok_or_else(|| Error::ParseError("missing 'task' argument".to_string()))?;

        let profile = match (v["agent"].as_str(), v["system_prompt"].as_str()) {
            (Some(_), Some(_)) => {
                return Ok(
                    "Provide either 'agent' (a pre-configured subagent) or 'system_prompt' \
                     (an inline one), not both."
                        .to_string(),
                );
            }
            (Some(agent_name), None) => match self.find_profile(agent_name) {
                Some(profile) => profile.clone(),
                None => {
                    let available = self
                        .profiles
                        .iter()
                        .map(|p| p.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ");
                    return Ok(format!(
                        "Unknown subagent '{agent_name}'. Available subagents: {available}. \
                         Alternatively, define an inline subagent via 'system_prompt'."
                    ));
                }
            },
            (None, Some(system_prompt)) => inline_profile(system_prompt, &v)?,
            (None, None) => {
                return Ok(
                    "Missing subagent: provide 'agent' (a pre-configured subagent) or \
                     'system_prompt' (an inline one)."
                        .to_string(),
                );
            }
        };
        let profile = &profile;

        let (config, llm) = self.resolve_runtime(profile)?;
        let executor = self.build_executor(profile);

        let mut prompt_builder = PromptBuilder::new();
        prompt_builder.set_system(profile.system_prompt.clone());

        // Fresh, isolated history — the subagent only ever sees its own task.
        let mut messages = vec![Message::user(task.to_string())];

        let result = run_agent_with_history(
            llm,
            executor,
            &config,
            &mut messages,
            Some(&prompt_builder),
            &TurnContext {
                cancel: turn.cancel,
                permission_gate: turn.permission_gate,
            },
        )
        .await?;

        if result.stop_reason == StopReason::MaxIterations {
            Ok(format!(
                "{}\n\n[Note: subagent '{}' reached its iteration limit \
                 ({}) before finishing — this answer may be incomplete.]",
                result.final_response, profile.name, config.max_iterations
            ))
        } else {
            Ok(result.final_response)
        }
    }
}

/// Builds an ephemeral [`AgentProfile`] from `delegate_task`'s inline arguments.
///
/// The profile lives only for this one call — it is never written to
/// `~/.openheim/agents/` or registered anywhere. Because it flows through the
/// same [`DelegateTool::resolve_runtime`]/[`DelegateTool::build_executor`] path
/// as named profiles, inline subagents get the identical sandbox, permission
/// gate, and no-recursion guarantees.
fn inline_profile(system_prompt: &str, v: &serde_json::Value) -> Result<AgentProfile> {
    let tools = match &v["tools"] {
        serde_json::Value::Null => None,
        serde_json::Value::Array(items) => {
            let mut names = Vec::with_capacity(items.len());
            for item in items {
                let name = item.as_str().ok_or_else(|| {
                    Error::ParseError("'tools' must be an array of strings".to_string())
                })?;
                names.push(name.to_string());
            }
            Some(names)
        }
        _ => {
            return Err(Error::ParseError(
                "'tools' must be an array of strings".to_string(),
            ));
        }
    };

    Ok(AgentProfile {
        name: "inline".to_string(),
        description: String::new(),
        model: v["model"].as_str().map(str::to_string),
        provider: v["provider"].as_str().map(str::to_string),
        tools,
        max_iterations: v["max_iterations"].as_u64().map(|n| n as usize),
        system_prompt: system_prompt.to_string(),
    })
}

/// Composes a base [`ToolExecutor`] with [`DelegateTool`], surfacing
/// `delegate_task` to the LLM alongside the base tools.
///
/// `inner` is the executor *as it exists before* this wrapper — exactly the view
/// passed to [`DelegateTool::new`] as `base_executor` — so subagents are handed a
/// tool list that structurally never contains `delegate_task`.
struct WithDelegate {
    inner: Arc<dyn ToolExecutor>,
    delegate: Arc<DelegateTool>,
}

impl WithDelegate {
    fn new(inner: Arc<dyn ToolExecutor>, delegate: Arc<DelegateTool>) -> Self {
        Self { inner, delegate }
    }
}

#[async_trait]
impl ToolExecutor for WithDelegate {
    fn list_tools(&self) -> Vec<Tool> {
        let mut tools = self.inner.list_tools();
        tools.push(self.delegate.definition());
        tools
    }

    async fn execute(&self, name: &str, args_json: &str, turn: &TurnContext<'_>) -> Result<String> {
        if name == DELEGATE_TOOL_NAME {
            self.delegate.execute(args_json, turn).await
        } else {
            self.inner.execute(name, args_json, turn).await
        }
    }
}

/// Wraps `executor` with [`DelegateTool`] support. `delegate_task` is always
/// exposed — even with no configured profiles the orchestrator can define an
/// ephemeral subagent inline via `system_prompt`.
#[allow(clippy::too_many_arguments)]
pub fn with_delegation(
    executor: Arc<dyn ToolExecutor>,
    work_dir: PathBuf,
    allow_shell: bool,
    profiles: Vec<AgentProfile>,
    llm: Arc<dyn LlmClient>,
    app_config: AppConfig,
    base_config: AgentConfig,
) -> Arc<dyn ToolExecutor> {
    let delegate = Arc::new(DelegateTool::new(
        executor.clone(),
        work_dir,
        allow_shell,
        profiles,
        llm,
        app_config,
        base_config,
    ));
    Arc::new(WithDelegate::new(executor, delegate))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::models::{Choice, ContentBlock, FinishReason, Role};
    use crate::core::permission::{AllowAll, PermissionDecision, PermissionGate};
    use crate::tools::test_support::TurnHarness;
    use std::collections::BTreeMap;
    use std::sync::Mutex;
    use tokio_util::sync::CancellationToken;

    fn sample_app_config() -> AppConfig {
        AppConfig {
            default_provider: "mock".into(),
            max_iterations: 10,
            theme_color: None,
            providers: BTreeMap::new(),
            mcp_servers: BTreeMap::new(),
            default_skills: vec![],
            work_dir: None,
            allow_shell: false,
        }
    }

    fn sample_agent_config() -> AgentConfig {
        AgentConfig::new(
            "mock".into(),
            "https://example.com".into(),
            "key".into(),
            "mock-model".into(),
            5,
        )
    }

    fn sample_profile(name: &str, description: &str) -> AgentProfile {
        AgentProfile {
            name: name.into(),
            description: description.into(),
            model: None,
            provider: None,
            tools: None,
            max_iterations: None,
            system_prompt: "You are a test subagent.".into(),
        }
    }

    fn text_choice(content: &str) -> Choice {
        Choice {
            message: Message::assistant(content),
            finish_reason: Some(FinishReason::Stop),
        }
    }

    fn tool_call_choice() -> Choice {
        Choice {
            message: Message {
                role: Role::Assistant,
                content: vec![ContentBlock::ToolUse {
                    id: "call_1".into(),
                    name: "nonexistent".into(),
                    arguments: "{}".into(),
                }],
            },
            finish_reason: Some(FinishReason::ToolCalls),
        }
    }

    struct MockLlm {
        responses: Mutex<Vec<Choice>>,
    }

    impl MockLlm {
        fn new(responses: Vec<Choice>) -> Self {
            Self {
                responses: Mutex::new(responses),
            }
        }
    }

    #[async_trait]
    impl LlmClient for MockLlm {
        async fn send(&self, _messages: &[Message], _tools: &[Tool]) -> Result<Choice> {
            let mut responses = self.responses.lock().unwrap();
            if responses.is_empty() {
                Err(Error::ApiError("no more mock responses".into()))
            } else {
                Ok(responses.remove(0))
            }
        }
    }

    /// A tool executor with no tools — every call fails, mirroring how a
    /// subagent would see "unknown tool" for anything it tries that isn't there.
    struct EmptyExecutor;

    #[async_trait]
    impl ToolExecutor for EmptyExecutor {
        fn list_tools(&self) -> Vec<Tool> {
            vec![]
        }

        async fn execute(
            &self,
            name: &str,
            _args_json: &str,
            _turn: &TurnContext<'_>,
        ) -> Result<String> {
            Err(Error::ToolExecutionError(format!("Unknown tool: {name}")))
        }
    }

    fn make_tool(profiles: Vec<AgentProfile>, llm: Arc<dyn LlmClient>) -> DelegateTool {
        DelegateTool::new(
            Arc::new(EmptyExecutor),
            PathBuf::from("/tmp"),
            false,
            profiles,
            llm,
            sample_app_config(),
            sample_agent_config(),
        )
    }

    #[test]
    fn definition_lists_available_profiles() {
        let llm = Arc::new(MockLlm::new(vec![]));
        let tool = make_tool(
            vec![sample_profile("reviewer", "Reviews code for bugs.")],
            llm,
        );
        let def = tool.definition();

        assert_eq!(def.function.name, DELEGATE_TOOL_NAME);
        assert!(def.function.description.contains("reviewer"));
        assert!(def.function.description.contains("Reviews code for bugs."));

        let names = def.function.parameters["properties"]["agent"]["enum"]
            .as_array()
            .unwrap();
        assert_eq!(names, &vec![serde_json::Value::String("reviewer".into())]);
    }

    #[tokio::test]
    async fn execute_returns_message_for_unknown_agent() {
        let llm = Arc::new(MockLlm::new(vec![]));
        let tool = make_tool(vec![sample_profile("reviewer", "desc")], llm);
        let harness = TurnHarness::new();

        let result = tool
            .execute(
                r#"{"agent": "ghost", "task": "do something"}"#,
                &harness.turn(),
            )
            .await
            .unwrap();

        assert!(result.contains("Unknown subagent 'ghost'"));
        assert!(result.contains("reviewer"));
    }

    #[tokio::test]
    async fn execute_runs_subagent_in_isolated_context_and_returns_final_answer() {
        let llm = Arc::new(MockLlm::new(vec![text_choice("subagent answer")]));
        let tool = make_tool(vec![sample_profile("reviewer", "desc")], llm);
        let harness = TurnHarness::new();

        let result = tool
            .execute(
                r#"{"agent": "reviewer", "task": "look at this diff"}"#,
                &harness.turn(),
            )
            .await
            .unwrap();

        assert_eq!(result, "subagent answer");
    }

    #[tokio::test]
    async fn execute_notes_when_subagent_hits_its_iteration_limit() {
        let llm = Arc::new(MockLlm::new(vec![tool_call_choice(), tool_call_choice()]));
        let mut profile = sample_profile("looper", "desc");
        profile.max_iterations = Some(2);
        let tool = make_tool(vec![profile], llm);
        let harness = TurnHarness::new();

        let result = tool
            .execute(
                r#"{"agent": "looper", "task": "loop forever"}"#,
                &harness.turn(),
            )
            .await
            .unwrap();

        assert!(result.contains("reached its iteration limit (2)"));
    }

    #[tokio::test]
    async fn execute_stops_immediately_when_parent_turn_already_cancelled() {
        // Subagent must inherit the parent's cancel token, not a fresh one —
        // otherwise a `session/cancel` on the orchestrator would never reach
        // an in-flight subagent.
        let llm = Arc::new(MockLlm::new(vec![text_choice("should not be seen")]));
        let tool = make_tool(vec![sample_profile("reviewer", "desc")], llm);

        let cancel = CancellationToken::new();
        cancel.cancel();
        let permission_gate: Arc<dyn PermissionGate> = Arc::new(AllowAll);
        let turn = TurnContext {
            cancel: &cancel,
            permission_gate: &permission_gate,
        };

        let result = tool
            .execute(
                r#"{"agent": "reviewer", "task": "look at this diff"}"#,
                &turn,
            )
            .await
            .unwrap();

        // The loop bails before ever calling the LLM, so no final text is produced.
        assert_eq!(result, "");
    }

    struct RejectPermissionGate;

    #[async_trait]
    impl PermissionGate for RejectPermissionGate {
        async fn check(
            &self,
            _tool_call_id: &str,
            _tool_name: &str,
            _arguments: &str,
        ) -> PermissionDecision {
            PermissionDecision::RejectOnce
        }
    }

    #[tokio::test]
    async fn subagent_tool_calls_go_through_parent_permission_gate() {
        // Subagent tool calls must be checked by the same gate as the
        // orchestrator's own — there is no separate, more-trusting policy for
        // subagents.
        let llm = Arc::new(MockLlm::new(vec![
            tool_call_choice(),
            text_choice("denied"),
        ]));
        let tool = make_tool(vec![sample_profile("reviewer", "desc")], llm);

        let cancel = CancellationToken::new();
        let permission_gate: Arc<dyn PermissionGate> = Arc::new(RejectPermissionGate);
        let turn = TurnContext {
            cancel: &cancel,
            permission_gate: &permission_gate,
        };

        let result = tool
            .execute(
                r#"{"agent": "reviewer", "task": "look at this diff"}"#,
                &turn,
            )
            .await
            .unwrap();

        assert_eq!(result, "denied");
    }

    #[test]
    fn with_delegation_exposes_delegate_tool_even_without_profiles() {
        // Inline subagents make delegate_task useful with zero configured
        // profiles, so the wrapper is unconditional.
        let llm = Arc::new(MockLlm::new(vec![]));
        let base: Arc<dyn ToolExecutor> = Arc::new(EmptyExecutor);
        let executor = with_delegation(
            base,
            PathBuf::from("/tmp"),
            false,
            vec![],
            llm,
            sample_app_config(),
            sample_agent_config(),
        );

        let names: Vec<_> = executor
            .list_tools()
            .into_iter()
            .map(|t| t.function.name)
            .collect();
        assert!(names.contains(&DELEGATE_TOOL_NAME.to_string()));
    }

    #[test]
    fn definition_omits_enum_when_no_profiles() {
        // An empty `enum` would make `agent` unusable on strict providers; with
        // no profiles the constraint is dropped entirely.
        let llm = Arc::new(MockLlm::new(vec![]));
        let tool = make_tool(vec![], llm);
        let def = tool.definition();

        assert!(def.function.parameters["properties"]["agent"]["enum"].is_null());
        assert!(def.function.description.contains("none configured"));
        let required = def.function.parameters["required"].as_array().unwrap();
        assert_eq!(required, &vec![serde_json::Value::String("task".into())]);
    }

    #[tokio::test]
    async fn execute_runs_inline_subagent_from_system_prompt() {
        let llm = Arc::new(MockLlm::new(vec![text_choice("inline answer")]));
        let tool = make_tool(vec![], llm);
        let harness = TurnHarness::new();

        let result = tool
            .execute(
                r#"{"system_prompt": "You are a poet.", "task": "write a haiku"}"#,
                &harness.turn(),
            )
            .await
            .unwrap();

        assert_eq!(result, "inline answer");
    }

    #[tokio::test]
    async fn execute_notes_when_inline_subagent_hits_iteration_limit() {
        let llm = Arc::new(MockLlm::new(vec![tool_call_choice(), tool_call_choice()]));
        let tool = make_tool(vec![], llm);
        let harness = TurnHarness::new();

        let result = tool
            .execute(
                r#"{"system_prompt": "Loop.", "max_iterations": 2, "task": "go"}"#,
                &harness.turn(),
            )
            .await
            .unwrap();

        assert!(result.contains("subagent 'inline' reached its iteration limit (2)"));
    }

    #[tokio::test]
    async fn execute_rejects_both_agent_and_system_prompt() {
        let llm = Arc::new(MockLlm::new(vec![]));
        let tool = make_tool(vec![sample_profile("reviewer", "desc")], llm);
        let harness = TurnHarness::new();

        let result = tool
            .execute(
                r#"{"agent": "reviewer", "system_prompt": "You are X.", "task": "go"}"#,
                &harness.turn(),
            )
            .await
            .unwrap();

        assert!(result.contains("not both"));
    }

    #[tokio::test]
    async fn execute_rejects_neither_agent_nor_system_prompt() {
        let llm = Arc::new(MockLlm::new(vec![]));
        let tool = make_tool(vec![], llm);
        let harness = TurnHarness::new();

        let result = tool
            .execute(r#"{"task": "go"}"#, &harness.turn())
            .await
            .unwrap();

        assert!(result.contains("Missing subagent"));
    }

    #[tokio::test]
    async fn execute_rejects_non_string_inline_tools() {
        let llm = Arc::new(MockLlm::new(vec![]));
        let tool = make_tool(vec![], llm);
        let harness = TurnHarness::new();

        let err = tool
            .execute(
                r#"{"system_prompt": "X.", "tools": [1, 2], "task": "go"}"#,
                &harness.turn(),
            )
            .await
            .unwrap_err();

        assert!(err.to_string().contains("array of strings"));
    }

    #[test]
    fn inline_profile_maps_all_optional_fields() {
        let v: serde_json::Value = serde_json::from_str(
            r#"{
                "tools": ["read_file"],
                "model": "claude-haiku-4-5",
                "provider": "anthropic",
                "max_iterations": 3
            }"#,
        )
        .unwrap();

        let profile = inline_profile("You are X.", &v).unwrap();
        assert_eq!(profile.name, "inline");
        assert_eq!(profile.system_prompt, "You are X.");
        assert_eq!(profile.tools, Some(vec!["read_file".to_string()]));
        assert_eq!(profile.model.as_deref(), Some("claude-haiku-4-5"));
        assert_eq!(profile.provider.as_deref(), Some("anthropic"));
        assert_eq!(profile.max_iterations, Some(3));
    }

    #[tokio::test]
    async fn with_delegation_exposes_delegate_tool_alongside_base_tools() {
        let llm = Arc::new(MockLlm::new(vec![text_choice("done")]));
        let base: Arc<dyn ToolExecutor> = Arc::new(EmptyExecutor);
        let executor = with_delegation(
            base,
            PathBuf::from("/tmp"),
            false,
            vec![sample_profile("reviewer", "desc")],
            llm,
            sample_app_config(),
            sample_agent_config(),
        );

        let names: Vec<_> = executor
            .list_tools()
            .into_iter()
            .map(|t| t.function.name)
            .collect();
        assert!(names.contains(&DELEGATE_TOOL_NAME.to_string()));

        let harness = TurnHarness::new();
        let result = executor
            .execute(
                DELEGATE_TOOL_NAME,
                r#"{"agent": "reviewer", "task": "go"}"#,
                &harness.turn(),
            )
            .await
            .unwrap();
        assert_eq!(result, "done");
    }
}