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}
169
170impl InProcessAgentRunner {
171 /// Construct a runner from its collaborators.
172 ///
173 /// Why: Constructor injection keeps the runner testable — production passes a
174 /// real `LlmClient` and a real registry factory; tests pass a scripted mock
175 /// client and a closure factory.
176 /// What: Stores the shared client, the registry factory, the agents config
177 /// directory, and a default `InProcessRunnerConfig`. Project context is
178 /// `None` until `with_project_context` is called.
179 /// Test: `runner::tests::delegate_runs_engineer_loop`.
180 pub fn new(
181 llm: Arc<dyn InferenceAdapter>,
182 registry_factory: Arc<dyn RegistryFactory>,
183 config_dir: impl Into<PathBuf>,
184 ) -> Self {
185 Self {
186 llm,
187 registry_factory,
188 config_dir: config_dir.into(),
189 project_context: None,
190 config: InProcessRunnerConfig::default(),
191 sink: None,
192 cancel: None,
193 mode: HarnessMode::default(),
194 skills_catalog: None,
195 }
196 }
197
198 /// Attach a [`ToolEventSink`] every delegated sub-agent loop this runner
199 /// drives will notify around its own tool dispatches (#2056).
200 ///
201 /// Why: Makes a delegated sub-agent's tool activity observable to the
202 /// same sink the delegating loop uses, without the delegate tool or the
203 /// PM loop needing to know about it.
204 /// What: Builder-style setter; returns `self` for chaining.
205 /// Test: `runner::tests::sink_reaches_delegated_loop`.
206 pub fn with_tool_event_sink(mut self, sink: Arc<dyn ToolEventSink>) -> Self {
207 self.sink = Some(sink);
208 self
209 }
210
211 /// Attach a cancellation flag every delegated sub-agent loop this runner
212 /// drives will check (#2056).
213 ///
214 /// Why: Cancelling the delegating (PM) run must also stop an in-flight
215 /// delegated sub-agent loop, not just the PM's own turns.
216 /// What: Builder-style setter; returns `self` for chaining.
217 /// Test: `runner::tests::cancel_flag_reaches_delegated_loop`.
218 pub fn with_cancel_flag(mut self, cancel: Arc<AtomicBool>) -> Self {
219 self.cancel = Some(cancel);
220 self
221 }
222
223 /// Set the resolved `HarnessMode` every sub-agent `AgentLoop` this runner
224 /// drives will use (#2059).
225 ///
226 /// Why: a delegated sub-agent's prompt/tool-schema assembly must use the
227 /// SAME resolved mode as its delegator — a daily-driver PM run should not
228 /// silently delegate to a parity-mode engineer, or vice versa.
229 /// What: Builder-style setter; returns `self` for chaining.
230 /// Test: `runner::tests::with_mode_completes_a_delegated_run_in_both_modes`.
231 pub fn with_mode(mut self, mode: HarnessMode) -> Self {
232 self.mode = mode;
233 self
234 }
235
236 /// Attach project `CLAUDE.md` context injected into every assembled prompt.
237 ///
238 /// Why: The parity prompt assembler (#1032) merges verbatim project context
239 /// as a fixed section; threading it here means every sub-agent the runner
240 /// drives sees the same project rules the PM does.
241 /// What: Stores `context` to pass to `assemble_system_prompt`.
242 /// Test: `runner::tests::project_context_reaches_prompt` (via the system
243 /// prompt captured by the scripted client).
244 pub fn with_project_context(mut self, context: impl Into<String>) -> Self {
245 self.project_context = Some(context.into());
246 self
247 }
248
249 /// Attach the rendered skill catalog (#2069) injected into every
250 /// `HarnessMode::DailyDriver` prompt this runner assembles.
251 ///
252 /// Why: A delegated sub-agent should see the same cheap, metadata-only
253 /// skill catalog the delegating PM does, without the runner needing to
254 /// know how the catalog was discovered (the caller renders it via
255 /// `skills::format_skill_catalog` and passes the result straight
256 /// through).
257 /// What: Builder-style setter; returns `self` for chaining. Ignored
258 /// entirely by `HarnessMode::Parity` at prompt-assembly time.
259 /// Test: `runner::tests::skills_catalog_reaches_daily_driver_prompt`,
260 /// `runner::tests::skills_catalog_ignored_in_parity`.
261 pub fn with_skills_catalog(mut self, catalog: impl Into<String>) -> Self {
262 self.skills_catalog = Some(catalog.into());
263 self
264 }
265
266 /// Override the default loop budget (turn cap + timeout).
267 ///
268 /// Why: Deployments and tests may want a tighter or looser default than the
269 /// built-in 40 turns / 120s.
270 /// What: Replaces `self.config`.
271 /// Test: `runner::tests::run_context_overrides_max_turns` sets a config then
272 /// overrides it per-call.
273 pub fn with_config(mut self, config: InProcessRunnerConfig) -> Self {
274 self.config = config;
275 self
276 }
277
278 /// Override only the wall-clock timeout of the default loop budget (#2207).
279 ///
280 /// Why: `run_task`/`task::executor` resolve a single run-wide deadline
281 /// (`crate::provider::resolve_deadline_secs`) that must apply to the
282 /// delegated engineer's loop as well as the delegating PM's own — but
283 /// they have no reason to touch `max_turns`. A dedicated setter avoids
284 /// forcing every call site to reconstruct a whole `InProcessRunnerConfig`
285 /// (and risk silently resetting `max_turns` to its default) just to
286 /// change one field.
287 /// What: Builder-style setter; returns `self` for chaining. Leaves
288 /// `self.config.max_turns` untouched.
289 /// Test: `runner::tests::with_timeout_secs_overrides_only_timeout`.
290 pub fn with_timeout_secs(mut self, timeout_secs: u64) -> Self {
291 self.config.timeout_secs = timeout_secs;
292 self
293 }
294
295 /// Load the agent config for `agent_name` from the config directory,
296 /// falling back to the embedded default roster when no disk config
297 /// exists (#3046).
298 ///
299 /// Why: Each delegation targets a named agent; its model, prompt, and
300 /// `tools.allowed` come from `<config_dir>/<agent_name>.md` (#2897 Slice
301 /// D — `.toml` is no longer a loadable source) when present, or from
302 /// `crate::assets::DEFAULT_AGENTS` when it is not — every delegated
303 /// sub-agent run goes through this method, so it is the load-bearing
304 /// site for making the 31-agent embedded roster actually dispatchable
305 /// from a real run (the gap #3046 closes). Distinguishing "no such
306 /// config anywhere" (`UnknownAgent`) from "a config exists but is
307 /// unparseable" (`ConfigLoad`) gives the caller actionable errors; this
308 /// method's own typed-error contract is preserved unchanged by mapping
309 /// [`crate::agents::resolve_agent`]'s shared `ResolveAgentError` onto
310 /// these SAME two `RunnerError` variants.
311 /// What: Delegates the disk-then-embedded precedence entirely to
312 /// [`crate::agents::resolve_agent`], then maps
313 /// `ResolveAgentError::NotFound` -> `RunnerError::UnknownAgent` and
314 /// `ResolveAgentError::Load` -> `RunnerError::ConfigLoad`.
315 /// Test: `runner::tests::unknown_agent_errors`,
316 /// `runner::tests::delegate_runs_engineer_loop`,
317 /// `runner::tests::embedded_restricted_agent_dispatch_preserves_tools_allowed`.
318 fn load_agent(&self, agent_name: &str) -> Result<AgentConfig, RunnerError> {
319 crate::agents::resolve_agent(&self.config_dir, agent_name).map_err(|e| match e {
320 crate::agents::ResolveAgentError::NotFound { name, dir, .. } => {
321 RunnerError::UnknownAgent { name, dir }
322 }
323 crate::agents::ResolveAgentError::Load { name, source } => {
324 RunnerError::ConfigLoad { name, source }
325 }
326 })
327 }
328
329 /// Resolve the gated registry, model, and assembled prompt, then run the loop.
330 ///
331 /// Why: Factoring the per-call pipeline out of the trait methods lets both
332 /// `run` and `run_with_context` share one implementation; the only
333 /// difference between them is the `RunContext` they pass in.
334 /// What: Loads the agent config, builds and gates its registry (honouring
335 /// `tools.allowed`), resolves the model (`RunContext` > agent > default) and
336 /// turn cap (`RunContext.max_turns_override` > runner default), assembles the
337 /// system prompt (BASE + agent prompt + project context), runs the
338 /// `AgentLoop` — attaching (#2279) `verify_gate::default_finish_gate` so a
339 /// premature `finish_task` gets a recoverable retry rather than
340 /// terminating the loop — and maps any loop error to `RunnerError::Loop`.
341 /// Test: `runner::tests::*`.
342 async fn run_pipeline(
343 &self,
344 agent_name: &str,
345 task: &str,
346 ctx: &RunContext,
347 ) -> Result<AgentOutput, RunnerError> {
348 let agent = self.load_agent(agent_name)?;
349
350 // Build the agent's full tool set, then gate it by `tools.allowed`.
351 let full_registry = self.registry_factory.build(&agent, ctx).await;
352 let registry = gate_registry(&full_registry, &agent);
353
354 // Resolve the model and the per-call turn cap (RunContext wins).
355 let model = resolve_model(&agent, Some(ctx));
356 let max_turns = ctx.max_turns_override.unwrap_or(self.config.max_turns);
357 // #run_task-maxtokens-bug: the delegated agent's own `[llm].max_tokens`
358 // must reach its loop — previously this was dropped entirely and every
359 // sub-agent turn was silently capped at the agent-loop default.
360 let max_tokens = resolve_max_tokens(&agent);
361
362 // #2308: derive the compaction threshold from this agent's ACTUAL
363 // resolved context window rather than the flat, model-blind
364 // `CompactionConfig::default()` — see that impl's doc for the root
365 // cause (a 6_000-token threshold is ~3% of a real 200K-token Bedrock
366 // Claude Sonnet window).
367 let compaction =
368 crate::agent_loop::CompactionConfig::for_context_window(resolve_context_window(&model));
369
370 let loop_config = AgentLoopConfig {
371 max_turns,
372 timeout_secs: self.config.timeout_secs,
373 model,
374 max_tokens,
375 mode: self.mode,
376 compaction,
377 // #2346: cadence stays disabled for the delegated sub-agent's own
378 // loop — the epic scopes cadence to the PM transcript only
379 // (`task::executor::run_and_record`'s persistent-session path);
380 // delegated engineer loops stay bounded/ephemeral per-delegation.
381 cadence: None,
382 // #3902: no test-only override for this production call site —
383 // falls back to `telemetry::default_data_dir()` exactly as
384 // before this field existed.
385 telemetry_data_dir: None,
386 };
387
388 // Assemble the mode-branched system prompt (BASE + agent prompt +
389 // project ctx) — see `assemble_system_prompt_for_mode`'s docs (#2059).
390 // Fallback guidance (the #1023 per-tier seam) is not wired here yet.
391 // `skills_catalog` (#2069) is appended only in `HarnessMode::DailyDriver`.
392 let system = assemble_system_prompt_for_mode(
393 self.mode,
394 &agent,
395 self.project_context.as_deref(),
396 None,
397 self.skills_catalog.as_deref(),
398 );
399
400 // (DOC-39 AC-13.1/13.2) Mint a fresh, per-spawn stable id for THIS
401 // delegation. Why here specifically: `run_pipeline` is the ONE
402 // production call site that constructs a delegated sub-agent's
403 // `AgentLoop` — both `run_task` and `task::executor` delegate through
404 // this runner (see the struct's own docs) — and it runs exactly once
405 // per `delegate_to_agent` invocation, i.e. once per spawn. `agent_name`
406 // alone (e.g. `"python-engineer"`) cannot distinguish two
407 // concurrently-delegated sub-agents of the same kind; this UUID v4 is
408 // the correlation key a UI must key on instead — see
409 // `AgentLoop::with_agent_id`'s docs.
410 let agent_id = uuid::Uuid::new_v4().to_string();
411
412 let mut agent_loop = AgentLoop::new(loop_config, Arc::clone(&self.llm), registry)
413 // #2279: every sub-agent this runner drives gets the default
414 // verify-before-finish gate — its own `bash` calls land in its
415 // own `Transcript`, so no external state is needed. This is the
416 // ONE production construction site for every delegated
417 // sub-agent loop (both `run_task` and `task::executor` delegate
418 // through this runner), so wiring it here covers both entry
419 // points without duplicating the attachment at each call site.
420 .with_finish_gate(crate::verify_gate::default_finish_gate())
421 // #2682: the complement to the verify gate above — suppress a
422 // redundant full-suite re-run once the suite has passed and nothing
423 // has changed since, so the engineer stops burning turns on
424 // repeated "one final run to confirm" passes. Same single
425 // construction site, so both `run_task` and `task::executor`
426 // delegations get it.
427 .with_redundant_run_suppression()
428 // (UI Phase 1) Attribute this sub-agent's tool events to itself.
429 // This is the ONE production construction site for every delegated
430 // sub-agent loop (both `run_task` and `task::executor` delegate
431 // through this runner), and the sink it shares with the PM below is
432 // the same `Arc` — so this call is what makes a delegated
433 // engineer's tool calls distinguishable from the PM's.
434 .with_agent(agent_name)
435 // (DOC-39 AC-13) Attribute this SPAWN's tool events with the fresh
436 // id minted above — the missing half of the UI Phase-1 attribution
437 // that let two same-named concurrent delegations collide.
438 .with_agent_id(agent_id);
439 if let Some(sink) = &self.sink {
440 agent_loop = agent_loop.with_tool_event_sink(Arc::clone(sink));
441 }
442 if let Some(cancel) = &self.cancel {
443 agent_loop = agent_loop.with_cancel_flag(Arc::clone(cancel));
444 }
445
446 agent_loop
447 .run(&system, task)
448 .await
449 .map_err(|source| RunnerError::Loop {
450 name: agent_name.to_string(),
451 source,
452 })
453 }
454}
455
456/// Narrow a full registry to the agent's `tools.allowed`, if any.
457///
458/// Why: The agent loop dispatches with no per-call allowlist, so the enforcement
459/// point for `tools.allowed` (issue #1029) is handing the loop a registry that
460/// only contains the permitted tools. An absent (`None`) allowlist means "all
461/// tools the factory built are permitted".
462/// What: If `tools.allowed` is `Some(list)`, returns `Arc::new(full.gated(list))`;
463/// otherwise returns the full registry unchanged (cheap `Arc` clone).
464/// Test: `runner::tests::tools_allowed_is_enforced`,
465/// `runner::tests::no_allowlist_permits_all`.
466fn gate_registry(full: &Arc<ToolRegistry>, agent: &AgentConfig) -> Arc<ToolRegistry> {
467 match agent.tools.as_ref().and_then(|t| t.allowed.as_ref()) {
468 Some(allowed) => Arc::new(full.gated(allowed)),
469 None => Arc::clone(full),
470 }
471}
472
473#[async_trait]
474impl AgentRunner for InProcessAgentRunner {
475 /// Run `task` against the named agent with default per-call context.
476 ///
477 /// Why: The simplest entry point the delegate tool calls; no overrides.
478 /// What: Delegates to `run_pipeline` with a default `RunContext`, converting
479 /// `RunnerError` into the trait's `anyhow::Error`.
480 /// Test: `runner::tests::delegate_runs_engineer_loop`.
481 async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
482 let ctx = RunContext::default();
483 Ok(self.run_pipeline(agent_name, task, &ctx).await?)
484 }
485
486 /// Run `task` against the named agent honouring per-call `ctx` overrides.
487 ///
488 /// Why: The orchestrator may pin a model, working directory, or turn cap for
489 /// a single delegation; `RunContext` carries those without global state.
490 /// What: Delegates to `run_pipeline` with the supplied `ctx`.
491 /// Test: `runner::tests::run_context_overrides_max_turns`,
492 /// `runner::tests::run_context_overrides_model`.
493 async fn run_with_context(
494 &self,
495 agent_name: &str,
496 task: &str,
497 ctx: &RunContext,
498 ) -> Result<AgentOutput> {
499 Ok(self.run_pipeline(agent_name, task, ctx).await?)
500 }
501}
502
503/// Convenience: discover whether an agent config exists for `name` under
504/// `dir`, on disk, in the embedded default roster (#3046), OR as a plugin
505/// agent (issue #3539/#3547).
506///
507/// Why: Callers (e.g. `tools::delegate::DelegateToAgentTool::execute`'s
508/// pre-flight gate) sometimes need to pre-check an agent name without
509/// constructing a runner; exposing the same disk-then-embedded(-then-plugin)
510/// rule [`crate::agents::resolve_agent`] uses keeps the two in lockstep — a
511/// pre-flight check that only saw disk would reject a real embedded roster
512/// name (e.g. `rust-engineer`) — or, as of #3539, a real plugin agent —
513/// before the runner ever got a chance to resolve it. Before this fix, a
514/// namespaced `<plugin>:<name>` always failed here (neither join matched),
515/// so `delegate_to_agent`'s pre-flight gate rejected every plugin agent as
516/// "unknown" even though `resolve_agent` could resolve it — plugin agents
517/// were listed but never actually dispatchable (code-critic PR #3547
518/// review, HIGH 4).
519/// What: a namespaced `name` (containing `:`) is routed to
520/// `plugins::agents::find_plugin_agent_config` — gated first by
521/// `plugins::is_valid_namespaced_name` (the traversal guard; also
522/// redundantly enforced inside `find_plugin_agent_config` itself, issue
523/// #3547 HIGH 3) and by recovering a project root from `dir` via
524/// `plugins::project_root_two_levels_up`. `true` iff that resolves to
525/// `Some(Ok(_))` — a plugin agent must actually load cleanly, NOT merely be
526/// found-but-broken, to pass this gate. This is DELIBERATELY stricter than
527/// the plain-name path below (a bare existence check, not a parseability
528/// one): `find_plugin_agent_config` can return `Some(Err(_))` for a
529/// SECURITY rejection (a symlinked `.md` file escaping `agents_dir` —
530/// issue #3547 CRITICAL 5, CWE-59), and that must fail this pre-flight gate
531/// outright rather than let `delegate_to_agent` proceed to invoke the
532/// runner on a name that can never actually resolve (code-critic PR #3547
533/// re-review — `Some(Err(_))` counting as "exists" let a symlink-rejected
534/// name slip past the pre-flight gate; the real `InProcessAgentRunner`
535/// would still refuse it one layer later via `resolve_agent`, so content
536/// never reached an LLM prompt either way, but the gate's whole purpose is
537/// to fail fast with a clear "unknown agent" error before ever attempting
538/// dispatch). Otherwise, unchanged: `true` iff `<dir>/<name>.md` exists
539/// (#2897 Slice D — `.toml` is no longer a loadable source) OR `name`
540/// matches an entry in `crate::assets::DEFAULT_AGENTS`.
541/// Test: `runner::tests::agent_config_exists_detects_present_and_absent`,
542/// `runner::tests::agent_config_exists_detects_embedded_default`,
543/// `runner::tests::agent_config_exists_detects_plugin_agent`,
544/// `runner::tests::agent_config_exists_rejects_plugin_traversal_name`,
545/// `runner::tests::agent_config_exists_rejects_symlinked_plugin_agent`.
546pub fn agent_config_exists(dir: &Path, name: &str) -> bool {
547 if let Some((plugin, local)) = name.split_once(':') {
548 if !crate::plugins::is_valid_namespaced_name(name) {
549 return false;
550 }
551 return crate::plugins::project_root_two_levels_up(dir)
552 .and_then(|root| crate::plugins::agents::find_plugin_agent_config(&root, plugin, local))
553 .is_some_and(|r| r.is_ok());
554 }
555 dir.join(format!("{name}.md")).exists()
556 || crate::assets::DEFAULT_AGENTS
557 .iter()
558 .any(|a| a.name() == name)
559}