Skip to main content

trusty_code/runner/
in_process.rs

1//! In-process agent runner — drives a sub-agent's own loop without a subprocess.
2//!
3//! Why: The model-comparison harness (issue #1029) must run a delegated
4//! sub-agent *inside the same process* as the PM, so a single run is cheap,
5//! fully observable, and free of IPC/process-spawn flakiness. The PM's
6//! `delegate_to_agent` tool calls an `AgentRunner`; this is the production
7//! implementation of that seam — for each call it loads the sub-agent's config,
8//! builds the sub-agent's gated tool registry, resolves its model and assembled
9//! system prompt, and drives an `AgentLoop` to completion, returning the
10//! sub-agent's `AgentOutput` (including its accrued token usage) back to the PM.
11//! What: `InProcessAgentRunner` implements `AgentRunner`. It holds an
12//! `Arc<dyn InferenceAdapter>` (shared with the PM so usage rolls up onto one
13//! transcript), an `Arc<dyn RegistryFactory>` (the DI seam for how a sub-agent's
14//! tools are assembled — fs/bash scoped to the working dir, plus a nested
15//! delegate), the agents config directory, optional project `CLAUDE.md` context,
16//! and an `InProcessRunnerConfig` (default turn/timeout budget). `RunnerKind`'s
17//! default is `InProcess` (config.rs), making this the real default backend.
18//! Test: `runner::tests` — stubbed-PM delegation, return-to-PM `AgentOutput`,
19//! `tools.allowed` enforcement, and usage roll-up — all offline via a scripted
20//! `InferenceAdapter` mock.
21
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use std::sync::atomic::AtomicBool;
25
26use anyhow::Result;
27use async_trait::async_trait;
28
29use crate::agent_loop::{AgentLoop, AgentLoopConfig, ToolEventSink};
30use crate::agents::AgentConfig;
31use crate::llm::InferenceAdapter;
32use crate::mode::HarnessMode;
33use crate::prompt::assemble_system_prompt_for_mode;
34use crate::provider::{resolve_context_window, resolve_max_tokens, resolve_model};
35use crate::runner::error::RunnerError;
36use crate::tools::{AgentOutput, AgentRunner, RunContext, ToolRegistry};
37
38/// Builds the tool registry a sub-agent is allowed to use for one invocation.
39///
40/// Why: How a sub-agent's tools are wired (fs/bash scoped to the run's working
41/// directory, a nested `delegate_to_agent`, search providers, …) is an
42/// orchestration concern that varies by deployment and must not be hard-coded
43/// into the runner. Injecting a factory keeps the runner policy-free and lets
44/// the orchestrator (#1030) and tests supply exactly the registry they want.
45/// What: `build` receives the resolved `AgentConfig` and the per-call
46/// `RunContext` and returns the *full* registry of tools available to that
47/// agent before allowlist gating; the runner then applies `tools.allowed`.
48/// Test: `runner::tests` use a closure-backed factory; production wiring lives
49/// in the orchestrator / `tm meta` layer.
50#[async_trait]
51pub trait RegistryFactory: Send + Sync {
52    /// Build the (ungated) tool registry for `agent` under `ctx`.
53    ///
54    /// Why: The factory owns tool construction; the runner owns gating. Keeping
55    /// them separate means a single factory serves every agent and the runner
56    /// applies each agent's own `tools.allowed` uniformly.
57    /// What: Returns an `Arc<ToolRegistry>` containing all tools the deployment
58    /// offers this agent; the runner narrows it to `tools.allowed`.
59    /// Test: Closure-backed impl in `runner::tests`.
60    async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry>;
61}
62
63/// Blanket impl so a plain async closure can serve as a `RegistryFactory`.
64///
65/// Why: Most call sites (and every test) want to supply registry assembly as a
66/// one-line closure rather than declaring a named type; this keeps wiring terse.
67/// What: Any `Fn(&AgentConfig, &RunContext) -> Fut` returning a future of
68/// `Arc<ToolRegistry>` implements `RegistryFactory`.
69/// Test: `runner::tests::delegate_runs_engineer_loop` constructs the runner from
70/// a closure.
71#[async_trait]
72impl<F, Fut> RegistryFactory for F
73where
74    F: Fn(AgentConfig, RunContext) -> Fut + Send + Sync,
75    Fut: std::future::Future<Output = Arc<ToolRegistry>> + Send,
76{
77    async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
78        self(agent.clone(), ctx.clone()).await
79    }
80}
81
82/// Static tuning for an in-process runner's default loop budget.
83///
84/// Why: The turn cap and timeout are the dials a deployment most often varies;
85/// grouping them keeps the runner constructor stable. Per-call `RunContext`
86/// overrides still take precedence over these defaults.
87/// What: `max_turns` and `timeout_secs` seed each invocation's `AgentLoopConfig`
88/// unless `RunContext.max_turns_override` overrides the turn cap.
89/// Test: `runner::tests::run_context_overrides_max_turns`.
90#[derive(Debug, Clone)]
91pub struct InProcessRunnerConfig {
92    /// Default maximum LLM round-trips per sub-agent run.
93    pub max_turns: u32,
94    /// Default wall-clock budget per sub-agent run, in seconds.
95    pub timeout_secs: u64,
96}
97
98impl Default for InProcessRunnerConfig {
99    /// Generous-but-bounded defaults for a delegated sub-agent's own loop.
100    ///
101    /// Why: (bake-off L1 diagnosis) The former default of 8 turns was tuned for
102    /// a toy/single-file task; a realistic multi-file package build (reading
103    /// several existing files, writing/editing several more, running the
104    /// project's own tests before finishing per the strengthened finish-gate
105    /// convention) routinely needs more than 8 LLM round-trips. Exhausting the
106    /// cap mid-task forces a `TurnCapExceeded` abort, which historically
107    /// triggered a destructive PM re-delegation that discarded correct partial
108    /// work and rebuilt a simpler (sometimes incomplete) solution from scratch
109    /// — see `tools::delegate::redelegation_hint`, the companion fix that makes
110    /// re-delegation reuse-aware regardless of this budget. 40 turns is
111    /// deliberately generous: the tradeoff is a higher worst-case cost/latency
112    /// ceiling per delegation in exchange for comfortably fitting a real
113    /// package-sized task without truncation. Still fully overridable per call
114    /// via `RunContext.max_turns_override` (`run_pipeline`) or per-runner via
115    /// `with_config`/`InProcessRunnerConfig::default().max_turns = N`.
116    /// What: 40 turns, 120s timeout.
117    /// Test: `runner::tests::config_default_is_sane`,
118    /// `runner::tests::default_max_turns_is_generous`.
119    fn default() -> Self {
120        Self {
121            max_turns: 40,
122            timeout_secs: 120,
123        }
124    }
125}
126
127/// Runs a delegated sub-agent in-process by driving its own `AgentLoop`.
128///
129/// Why: This is the concrete `AgentRunner` the PM's `delegate_to_agent` tool
130/// dispatches to in the M1 harness. Running in-process (vs. subprocess) keeps a
131/// comparison run a single, observable process and lets the sub-agent's token
132/// usage accrue onto the same shared client the PM uses, so the orchestrator can
133/// roll engineer cost up into the PM's transcript (#1030).
134/// What: Holds the shared LLM client, a `RegistryFactory`, the agents config
135/// directory, optional project context, and the default loop budget. For each
136/// `run`, it loads `<config_dir>/<agent_name>.md`, asks the factory for the
137/// agent's tools, gates them by `tools.allowed`, resolves the model and
138/// assembled system prompt, then runs an `AgentLoop` and returns its output.
139/// Test: `runner::tests::*` cover the full delegation path offline.
140pub struct InProcessAgentRunner {
141    llm: Arc<dyn InferenceAdapter>,
142    registry_factory: Arc<dyn RegistryFactory>,
143    config_dir: PathBuf,
144    project_context: Option<String>,
145    config: InProcessRunnerConfig,
146    /// #2056: propagated to every sub-agent `AgentLoop` this runner drives, so
147    /// a delegated sub-agent's tool activity is observable to the same sink
148    /// the delegating (PM) loop uses. `None` (the default) matches the
149    /// pre-#2056 behaviour exactly.
150    sink: Option<Arc<dyn ToolEventSink>>,
151    /// #2056: propagated to every sub-agent `AgentLoop`, so cancelling the
152    /// PM's run also stops any in-flight delegated sub-agent loop.
153    cancel: Option<Arc<AtomicBool>>,
154    /// #2059: the resolved `HarnessMode` for the delegating (PM) run,
155    /// propagated to every sub-agent `AgentLoop` this runner drives so a
156    /// delegated sub-agent's prompt/tool-schema assembly uses the SAME mode
157    /// as its delegator. Defaults to `HarnessMode::default()`, matching
158    /// pre-#2059 behaviour exactly (both modes are functionally identical
159    /// in M1 regardless).
160    mode: HarnessMode,
161    /// #2069: the rendered, metadata-only skill catalog
162    /// (`skills::format_skill_catalog`) threaded into every sub-agent prompt
163    /// this runner assembles, in `HarnessMode::DailyDriver` only (the mode
164    /// arm ignores it entirely in `Parity` — see
165    /// `assemble_system_prompt_for_mode`'s docs). `None` until
166    /// `with_skills_catalog` is called, matching pre-#2069 behaviour exactly.
167    skills_catalog: Option<String>,
168    /// (#7948) The session-scoped half of the permission gate. A gate is
169    /// minted per delegation in `run_pipeline` from the DELEGATED agent's own
170    /// config. `None` means no gate, exactly as before #7948.
171    permissions: Option<crate::permissions::PermissionContext>,
172    /// (#8206) The directory this runner's delegated agents' fs/bash tools are
173    /// scoped to — the bound project root, or the run's scratch root when
174    /// projectless. Read only by the verify-before-finish gate, which must not
175    /// refuse a finish over a test suite that demonstrably is not there.
176    /// `None` (the default) means no project is bound, which makes the gate's
177    /// refusal arm unreachable — see `verify_gate::default_finish_gate`.
178    work_root: Option<PathBuf>,
179}
180
181impl InProcessAgentRunner {
182    /// Construct a runner from its collaborators.
183    ///
184    /// Why: Constructor injection keeps the runner testable — production passes a
185    /// real `LlmClient` and a real registry factory; tests pass a scripted mock
186    /// client and a closure factory.
187    /// What: Stores the shared client, the registry factory, the agents config
188    /// directory, and a default `InProcessRunnerConfig`. Project context is
189    /// `None` until `with_project_context` is called.
190    /// Test: `runner::tests::delegate_runs_engineer_loop`.
191    pub fn new(
192        llm: Arc<dyn InferenceAdapter>,
193        registry_factory: Arc<dyn RegistryFactory>,
194        config_dir: impl Into<PathBuf>,
195    ) -> Self {
196        Self {
197            llm,
198            registry_factory,
199            config_dir: config_dir.into(),
200            project_context: None,
201            config: InProcessRunnerConfig::default(),
202            sink: None,
203            cancel: None,
204            mode: HarnessMode::default(),
205            skills_catalog: None,
206            permissions: None,
207            work_root: None,
208        }
209    }
210
211    /// Attach the session-scoped permission context every delegated sub-agent
212    /// loop this runner drives is gated by (#7948).
213    ///
214    /// Why: this is the one production construction site for a delegated
215    /// sub-agent's `AgentLoop` (`run_task` and `task::executor` both delegate
216    /// through it), so wiring the context here gates every delegation.
217    /// What: builder-style setter. The gate itself is minted per delegation
218    /// in `run_pipeline`, because its map comes from the delegated agent.
219    /// Test: `agent_loop::tests::permission_gate::deny_never_dispatches`.
220    pub fn with_permissions(mut self, ctx: crate::permissions::PermissionContext) -> Self {
221        self.permissions = Some(ctx);
222        self
223    }
224
225    /// Attach a [`ToolEventSink`] every delegated sub-agent loop this runner
226    /// drives will notify around its own tool dispatches (#2056).
227    ///
228    /// Why: Makes a delegated sub-agent's tool activity observable to the
229    /// same sink the delegating loop uses, without the delegate tool or the
230    /// PM loop needing to know about it.
231    /// What: Builder-style setter; returns `self` for chaining.
232    /// Test: `runner::tests::sink_reaches_delegated_loop`.
233    pub fn with_tool_event_sink(mut self, sink: Arc<dyn ToolEventSink>) -> Self {
234        self.sink = Some(sink);
235        self
236    }
237
238    /// Attach a cancellation flag every delegated sub-agent loop this runner
239    /// drives will check (#2056).
240    ///
241    /// Why: Cancelling the delegating (PM) run must also stop an in-flight
242    /// delegated sub-agent loop, not just the PM's own turns.
243    /// What: Builder-style setter; returns `self` for chaining.
244    /// Test: `runner::tests::cancel_flag_reaches_delegated_loop`.
245    pub fn with_cancel_flag(mut self, cancel: Arc<AtomicBool>) -> Self {
246        self.cancel = Some(cancel);
247        self
248    }
249
250    /// Set the resolved `HarnessMode` every sub-agent `AgentLoop` this runner
251    /// drives will use (#2059).
252    ///
253    /// Why: a delegated sub-agent's prompt/tool-schema assembly must use the
254    /// SAME resolved mode as its delegator — a daily-driver PM run should not
255    /// silently delegate to a parity-mode engineer, or vice versa.
256    /// What: Builder-style setter; returns `self` for chaining.
257    /// Test: `runner::tests::with_mode_completes_a_delegated_run_in_both_modes`.
258    pub fn with_mode(mut self, mode: HarnessMode) -> Self {
259        self.mode = mode;
260        self
261    }
262
263    /// Attach project `CLAUDE.md` context injected into every assembled prompt.
264    ///
265    /// Why: The parity prompt assembler (#1032) merges verbatim project context
266    /// as a fixed section; threading it here means every sub-agent the runner
267    /// drives sees the same project rules the PM does.
268    /// What: Stores `context` to pass to `assemble_system_prompt`.
269    /// Test: `runner::tests::project_context_reaches_prompt` (via the system
270    /// prompt captured by the scripted client).
271    pub fn with_project_context(mut self, context: impl Into<String>) -> Self {
272        self.project_context = Some(context.into());
273        self
274    }
275
276    /// Attach the rendered skill catalog (#2069) injected into every
277    /// `HarnessMode::DailyDriver` prompt this runner assembles.
278    ///
279    /// Why: A delegated sub-agent should see the same cheap, metadata-only
280    /// skill catalog the delegating PM does, without the runner needing to
281    /// know how the catalog was discovered (the caller renders it via
282    /// `skills::format_skill_catalog` and passes the result straight
283    /// through).
284    /// What: Builder-style setter; returns `self` for chaining. Ignored
285    /// entirely by `HarnessMode::Parity` at prompt-assembly time.
286    /// Test: `runner::tests::skills_catalog_reaches_daily_driver_prompt`,
287    /// `runner::tests::skills_catalog_ignored_in_parity`.
288    pub fn with_skills_catalog(mut self, catalog: impl Into<String>) -> Self {
289        self.skills_catalog = Some(catalog.into());
290        self
291    }
292
293    /// Bind the work root the verify-before-finish gate probes for a
294    /// detectable test suite (#8206).
295    ///
296    /// Why: Without it the gate refused a `finish_task` on an empty
297    /// projectless scratch root, where no test command could ever have run —
298    /// the live #8206 transcript wedged on exactly that refusal.
299    /// What: The SAME directory the caller scoped this runner's fs/bash tools
300    /// to. Unset leaves the gate's refusal arm unreachable.
301    /// Test: `runner::tests::work_root_reaches_the_finish_gate`.
302    pub fn with_work_root(mut self, work_root: impl Into<PathBuf>) -> Self {
303        self.work_root = Some(work_root.into());
304        self
305    }
306
307    /// Override the default loop budget (turn cap + timeout).
308    ///
309    /// Why: Deployments and tests may want a tighter or looser default than the
310    /// built-in 40 turns / 120s.
311    /// What: Replaces `self.config`.
312    /// Test: `runner::tests::run_context_overrides_max_turns` sets a config then
313    /// overrides it per-call.
314    pub fn with_config(mut self, config: InProcessRunnerConfig) -> Self {
315        self.config = config;
316        self
317    }
318
319    /// Override only the wall-clock timeout of the default loop budget (#2207).
320    ///
321    /// Why: `run_task`/`task::executor` resolve a single run-wide deadline
322    /// (`crate::provider::resolve_deadline_secs`) that must apply to the
323    /// delegated engineer's loop as well as the delegating PM's own — but
324    /// they have no reason to touch `max_turns`. A dedicated setter avoids
325    /// forcing every call site to reconstruct a whole `InProcessRunnerConfig`
326    /// (and risk silently resetting `max_turns` to its default) just to
327    /// change one field.
328    /// What: Builder-style setter; returns `self` for chaining. Leaves
329    /// `self.config.max_turns` untouched.
330    /// Test: `runner::tests::with_timeout_secs_overrides_only_timeout`.
331    pub fn with_timeout_secs(mut self, timeout_secs: u64) -> Self {
332        self.config.timeout_secs = timeout_secs;
333        self
334    }
335
336    /// Load the agent config for `agent_name` from the config directory,
337    /// falling back to the embedded default roster when no disk config
338    /// exists (#3046).
339    ///
340    /// Why: Each delegation targets a named agent; its model, prompt, and
341    /// `tools.allowed` come from `<config_dir>/<agent_name>.md` (#2897 Slice
342    /// D — `.toml` is no longer a loadable source) when present, or from
343    /// `crate::assets::DEFAULT_AGENTS` when it is not — every delegated
344    /// sub-agent run goes through this method, so it is the load-bearing
345    /// site for making the 31-agent embedded roster actually dispatchable
346    /// from a real run (the gap #3046 closes). Distinguishing "no such
347    /// config anywhere" (`UnknownAgent`) from "a config exists but is
348    /// unparseable" (`ConfigLoad`) gives the caller actionable errors; this
349    /// method's own typed-error contract is preserved unchanged by mapping
350    /// [`crate::agents::resolve_agent`]'s shared `ResolveAgentError` onto
351    /// these SAME two `RunnerError` variants.
352    /// What: Delegates the disk-then-embedded precedence entirely to
353    /// [`crate::agents::resolve_agent`], then maps
354    /// `ResolveAgentError::NotFound` -> `RunnerError::UnknownAgent` and
355    /// `ResolveAgentError::Load` -> `RunnerError::ConfigLoad`.
356    /// Test: `runner::tests::unknown_agent_errors`,
357    /// `runner::tests::delegate_runs_engineer_loop`,
358    /// `runner::tests::embedded_restricted_agent_dispatch_preserves_tools_allowed`.
359    fn load_agent(&self, agent_name: &str) -> Result<AgentConfig, RunnerError> {
360        crate::agents::resolve_agent(&self.config_dir, agent_name).map_err(|e| match e {
361            crate::agents::ResolveAgentError::NotFound { name, dir, .. } => {
362                RunnerError::UnknownAgent { name, dir }
363            }
364            crate::agents::ResolveAgentError::Load { name, source } => {
365                RunnerError::ConfigLoad { name, source }
366            }
367        })
368    }
369
370    /// Resolve the gated registry, model, and assembled prompt, then run the loop.
371    ///
372    /// Why: Factoring the per-call pipeline out of the trait methods lets both
373    /// `run` and `run_with_context` share one implementation; the only
374    /// difference between them is the `RunContext` they pass in.
375    /// What: Loads the agent config, builds and gates its registry (honouring
376    /// `tools.allowed`), resolves the model (`RunContext` > agent > default) and
377    /// turn cap (`RunContext.max_turns_override` > runner default), assembles the
378    /// system prompt (BASE + agent prompt + project context), runs the
379    /// `AgentLoop` — attaching (#2279) `verify_gate::default_finish_gate` so a
380    /// premature `finish_task` gets a recoverable retry rather than
381    /// terminating the loop — and maps any loop error to `RunnerError::Loop`.
382    /// Test: `runner::tests::*`.
383    async fn run_pipeline(
384        &self,
385        agent_name: &str,
386        task: &str,
387        ctx: &RunContext,
388    ) -> Result<AgentOutput, RunnerError> {
389        let agent = self.load_agent(agent_name)?;
390
391        // Build the agent's full tool set, then gate it by `tools.allowed`.
392        // #8031: via the shared helper `--no-delegate` also calls, so a
393        // single-agent run and a delegated one can never assemble the set
394        // differently.
395        let registry = agent_registry(self.registry_factory.as_ref(), &agent, ctx).await;
396        // #8206: read BEFORE the registry moves into the loop below. An agent
397        // whose `tools.allowed` gated `bash` out cannot run any test command,
398        // so its verify-before-finish gate must never refuse it for not having.
399        let registry_has_bash = registry.contains(crate::tools::BASH_TOOL_NAME);
400
401        // Resolve the model and the per-call turn cap (RunContext wins).
402        let model = resolve_model(&agent, Some(ctx));
403        let max_turns = ctx.max_turns_override.unwrap_or(self.config.max_turns);
404        // #run_task-maxtokens-bug: the delegated agent's own `[llm].max_tokens`
405        // must reach its loop — previously this was dropped entirely and every
406        // sub-agent turn was silently capped at the agent-loop default.
407        let max_tokens = resolve_max_tokens(&agent);
408
409        // #2308: derive the compaction threshold from this agent's ACTUAL
410        // resolved context window rather than the flat, model-blind
411        // `CompactionConfig::default()` — see that impl's doc for the root
412        // cause (a 6_000-token threshold is ~3% of a real 200K-token Bedrock
413        // Claude Sonnet window).
414        let compaction =
415            crate::agent_loop::CompactionConfig::for_context_window(resolve_context_window(&model));
416
417        let loop_config = AgentLoopConfig {
418            max_turns,
419            timeout_secs: self.config.timeout_secs,
420            model,
421            max_tokens,
422            mode: self.mode,
423            compaction,
424            // #2346: cadence stays disabled for the delegated sub-agent's own
425            // loop — the epic scopes cadence to the PM transcript only
426            // (`task::executor::run_and_record`'s persistent-session path);
427            // delegated engineer loops stay bounded/ephemeral per-delegation.
428            cadence: None,
429            // #3902: no test-only override for this production call site —
430            // falls back to `telemetry::default_data_dir()` exactly as
431            // before this field existed.
432            telemetry_data_dir: None,
433        };
434
435        // Assemble the mode-branched system prompt (BASE + agent prompt +
436        // project ctx) — see `assemble_system_prompt_for_mode`'s docs (#2059).
437        // Fallback guidance (the #1023 per-tier seam) is not wired here yet.
438        // `skills_catalog` (#2069) is appended only in `HarnessMode::DailyDriver`.
439        // #4602: gated on THIS delegation's registry, so an agent narrowed by
440        // `tools.allowed` is never told to call a tool the gate removed.
441        let system = assemble_system_prompt_for_mode(
442            self.mode,
443            &agent,
444            self.project_context.as_deref(),
445            None,
446            self.skills_catalog.as_deref(),
447            Some(registry.as_ref()),
448        );
449
450        // (DOC-39 AC-13.1/13.2) Mint a fresh, per-spawn stable id for THIS
451        // delegation. Why here specifically: `run_pipeline` is the ONE
452        // production call site that constructs a delegated sub-agent's
453        // `AgentLoop` — both `run_task` and `task::executor` delegate through
454        // this runner (see the struct's own docs) — and it runs exactly once
455        // per `delegate_to_agent` invocation, i.e. once per spawn. `agent_name`
456        // alone (e.g. `"python-engineer"`) cannot distinguish two
457        // concurrently-delegated sub-agents of the same kind; this UUID v4 is
458        // the correlation key a UI must key on instead — see
459        // `AgentLoop::with_agent_id`'s docs.
460        let agent_id = uuid::Uuid::new_v4().to_string();
461
462        let mut agent_loop = AgentLoop::new(loop_config, Arc::clone(&self.llm), registry)
463            // #2279: every sub-agent this runner drives gets the default
464            // verify-before-finish gate — its own `bash` calls land in its
465            // own `Transcript`, so no external state is needed. This is the
466            // ONE production construction site for every delegated
467            // sub-agent loop (both `run_task` and `task::executor` delegate
468            // through this runner), so wiring it here covers both entry
469            // points without duplicating the attachment at each call site.
470            // #8206: the gate additionally needs this delegation's own
471            // registry (does it even have `bash`?) and the bound work root
472            // (is there a test suite to detect?) — both resolved right here,
473            // so a refusal is only ever raised where the agent could comply.
474            .with_finish_gate(crate::verify_gate::default_finish_gate(
475                crate::verify_gate::VerifyGateContext::new(
476                    self.work_root.clone(),
477                    registry_has_bash,
478                ),
479            ))
480            // #2682: the complement to the verify gate above — suppress a
481            // redundant full-suite re-run once the suite has passed and nothing
482            // has changed since, so the engineer stops burning turns on
483            // repeated "one final run to confirm" passes. Same single
484            // construction site, so both `run_task` and `task::executor`
485            // delegations get it.
486            .with_redundant_run_suppression()
487            // (UI Phase 1) Attribute this sub-agent's tool events to itself.
488            // This is the ONE production construction site for every delegated
489            // sub-agent loop (both `run_task` and `task::executor` delegate
490            // through this runner), and the sink it shares with the PM below is
491            // the same `Arc` — so this call is what makes a delegated
492            // engineer's tool calls distinguishable from the PM's.
493            .with_agent(agent_name)
494            // (DOC-39 AC-13) Attribute this SPAWN's tool events with the fresh
495            // id minted above — the missing half of the UI Phase-1 attribution
496            // that let two same-named concurrent delegations collide.
497            .with_agent_id(agent_id.clone());
498        if let Some(sink) = &self.sink {
499            agent_loop = agent_loop.with_tool_event_sink(Arc::clone(sink));
500        }
501        if let Some(cancel) = &self.cancel {
502            agent_loop = agent_loop.with_cancel_flag(Arc::clone(cancel));
503        }
504        // #7948: minted from the DELEGATED agent's own config, so a sub-agent's
505        // `permissions:` block governs its own calls, not its delegator's.
506        if let Some(ctx) = &self.permissions {
507            agent_loop = agent_loop.with_permission_gate(Arc::new(
508                ctx.gate_for(Arc::new(agent.clone()), agent_id.clone()),
509            ));
510        }
511
512        // #7940: bracket the sub-agent's loop with the delegation-lifecycle
513        // hooks. Here specifically for the same reason `agent_id` is minted
514        // here: this is the ONE production site that runs exactly once per
515        // `delegate_to_agent` dispatch, so a spawn can never be reported
516        // twice or without the id its tool/message events carry.
517        if let Some(sink) = &self.sink {
518            sink.agent_spawned(agent_name, &agent_id, task).await;
519        }
520        let outcome = agent_loop
521            .run(&system, task)
522            .await
523            .map_err(|source| RunnerError::Loop {
524                name: agent_name.to_string(),
525                source,
526            });
527        if let Some(sink) = &self.sink {
528            match &outcome {
529                Ok(_) => sink.agent_done(agent_name, &agent_id, "success").await,
530                Err(e) => {
531                    sink.agent_failed(agent_name, &agent_id, &e.to_string())
532                        .await
533                }
534            }
535        }
536        outcome
537    }
538}
539
540/// The tool registry one agent may actually use for one invocation.
541///
542/// Why (#8031): this is the ONE definition of "the tcode tools an agent gets" —
543/// build the factory's full set for that agent, then narrow it by the agent's
544/// own `tools.allowed`. `run_pipeline` uses it for a delegated sub-agent, and
545/// `--no-delegate` uses it to give the TOP-LEVEL agent the identical set,
546/// through the identical gate. Two independent copies of those two steps would
547/// let a single-agent run drift into a wider tool surface than a delegated run
548/// of the same agent.
549/// What: `factory.build(agent, ctx)` then [`gate_registry`]. The run-time
550/// `permissions:` map is a separate, later gate the caller attaches to the
551/// `AgentLoop` (`PermissionContext::gate_for`) — this decides only what the
552/// model is ever SHOWN.
553/// Test: `runner::tests::tools_allowed_is_enforced`,
554/// `task::executor::tests::no_delegate_run_respects_the_agents_tools_allowlist`.
555pub(crate) async fn agent_registry(
556    factory: &dyn RegistryFactory,
557    agent: &AgentConfig,
558    ctx: &RunContext,
559) -> Arc<ToolRegistry> {
560    let full = factory.build(agent, ctx).await;
561    gate_registry(&full, agent)
562}
563
564/// Narrow a full registry to the agent's `tools.allowed`, if any.
565///
566/// Why: The agent loop dispatches with no per-call allowlist, so the enforcement
567/// point for `tools.allowed` (issue #1029) is handing the loop a registry that
568/// only contains the permitted tools. An absent (`None`) allowlist means "all
569/// tools the factory built are permitted".
570/// What: If `tools.allowed` is `Some(list)`, returns `Arc::new(full.gated(list))`;
571/// otherwise returns the full registry unchanged (cheap `Arc` clone).
572/// Test: `runner::tests::tools_allowed_is_enforced`,
573/// `runner::tests::no_allowlist_permits_all`.
574fn gate_registry(full: &Arc<ToolRegistry>, agent: &AgentConfig) -> Arc<ToolRegistry> {
575    match agent.tools.as_ref().and_then(|t| t.allowed.as_ref()) {
576        Some(allowed) => Arc::new(full.gated(allowed)),
577        None => Arc::clone(full),
578    }
579}
580
581#[async_trait]
582impl AgentRunner for InProcessAgentRunner {
583    /// Run `task` against the named agent with default per-call context.
584    ///
585    /// Why: The simplest entry point the delegate tool calls; no overrides.
586    /// What: Delegates to `run_pipeline` with a default `RunContext`, converting
587    /// `RunnerError` into the trait's `anyhow::Error`.
588    /// Test: `runner::tests::delegate_runs_engineer_loop`.
589    async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
590        let ctx = RunContext::default();
591        Ok(self.run_pipeline(agent_name, task, &ctx).await?)
592    }
593
594    /// Run `task` against the named agent honouring per-call `ctx` overrides.
595    ///
596    /// Why: The orchestrator may pin a model, working directory, or turn cap for
597    /// a single delegation; `RunContext` carries those without global state.
598    /// What: Delegates to `run_pipeline` with the supplied `ctx`.
599    /// Test: `runner::tests::run_context_overrides_max_turns`,
600    /// `runner::tests::run_context_overrides_model`.
601    async fn run_with_context(
602        &self,
603        agent_name: &str,
604        task: &str,
605        ctx: &RunContext,
606    ) -> Result<AgentOutput> {
607        Ok(self.run_pipeline(agent_name, task, ctx).await?)
608    }
609}
610
611/// Convenience: discover whether an agent config exists for `name` under
612/// `dir`, on disk, in the embedded default roster (#3046), OR as a plugin
613/// agent (issue #3539/#3547).
614///
615/// Why: Callers (e.g. `tools::delegate::DelegateToAgentTool::execute`'s
616/// pre-flight gate) sometimes need to pre-check an agent name without
617/// constructing a runner; exposing the same disk-then-embedded(-then-plugin)
618/// rule [`crate::agents::resolve_agent`] uses keeps the two in lockstep — a
619/// pre-flight check that only saw disk would reject a real embedded roster
620/// name (e.g. `rust-engineer`) — or, as of #3539, a real plugin agent —
621/// before the runner ever got a chance to resolve it. Before this fix, a
622/// namespaced `<plugin>:<name>` always failed here (neither join matched),
623/// so `delegate_to_agent`'s pre-flight gate rejected every plugin agent as
624/// "unknown" even though `resolve_agent` could resolve it — plugin agents
625/// were listed but never actually dispatchable (code-critic PR #3547
626/// review, HIGH 4).
627/// What: a namespaced `name` (containing `:`) is routed to
628/// `plugins::agents::find_plugin_agent_config` — gated first by
629/// `plugins::is_valid_namespaced_name` (the traversal guard; also
630/// redundantly enforced inside `find_plugin_agent_config` itself, issue
631/// #3547 HIGH 3) and by recovering a project root from `dir` via
632/// `plugins::project_root_two_levels_up`. `true` iff that resolves to
633/// `Some(Ok(_))` — a plugin agent must actually load cleanly, NOT merely be
634/// found-but-broken, to pass this gate. This is DELIBERATELY stricter than
635/// the plain-name path below (a bare existence check, not a parseability
636/// one): `find_plugin_agent_config` can return `Some(Err(_))` for a
637/// SECURITY rejection (a symlinked `.md` file escaping `agents_dir` —
638/// issue #3547 CRITICAL 5, CWE-59), and that must fail this pre-flight gate
639/// outright rather than let `delegate_to_agent` proceed to invoke the
640/// runner on a name that can never actually resolve (code-critic PR #3547
641/// re-review — `Some(Err(_))` counting as "exists" let a symlink-rejected
642/// name slip past the pre-flight gate; the real `InProcessAgentRunner`
643/// would still refuse it one layer later via `resolve_agent`, so content
644/// never reached an LLM prompt either way, but the gate's whole purpose is
645/// to fail fast with a clear "unknown agent" error before ever attempting
646/// dispatch). Otherwise, unchanged: `true` iff `<dir>/<name>.md` exists
647/// (#2897 Slice D — `.toml` is no longer a loadable source) OR `name`
648/// matches an entry in `crate::assets::DEFAULT_AGENTS`.
649/// Test: `runner::tests::agent_config_exists_detects_present_and_absent`,
650/// `runner::tests::agent_config_exists_detects_embedded_default`,
651/// `runner::tests::agent_config_exists_detects_plugin_agent`,
652/// `runner::tests::agent_config_exists_rejects_plugin_traversal_name`,
653/// `runner::tests::agent_config_exists_rejects_symlinked_plugin_agent`.
654pub fn agent_config_exists(dir: &Path, name: &str) -> bool {
655    if let Some((plugin, local)) = name.split_once(':') {
656        if !crate::plugins::is_valid_namespaced_name(name) {
657            return false;
658        }
659        return crate::plugins::project_root_two_levels_up(dir)
660            .and_then(|root| crate::plugins::agents::find_plugin_agent_config(&root, plugin, local))
661            .is_some_and(|r| r.is_ok());
662    }
663    dir.join(format!("{name}.md")).exists()
664        || crate::assets::DEFAULT_AGENTS
665            .iter()
666            .any(|a| a.name() == name)
667}