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 LlmClientTrait>` (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//! `LlmClientTrait` 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::LlmClientTrait;
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>.toml`, 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 LlmClientTrait>,
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 LlmClientTrait>,
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    ///
297    /// Why: Each delegation targets a named agent; its model, prompt, and
298    /// `tools.allowed` come from `<config_dir>/<agent_name>.toml`. Distinguishing
299    /// "no such file" (`UnknownAgent`) from "file present but unparseable"
300    /// (`ConfigLoad`) gives the caller actionable errors.
301    /// What: Builds the path, returns `UnknownAgent` if it does not exist, else
302    /// loads it (mapping a parse failure to `ConfigLoad`).
303    /// Test: `runner::tests::unknown_agent_errors`,
304    /// `runner::tests::delegate_runs_engineer_loop`.
305    fn load_agent(&self, agent_name: &str) -> Result<AgentConfig, RunnerError> {
306        let path = self.config_dir.join(format!("{agent_name}.toml"));
307        if !path.exists() {
308            return Err(RunnerError::UnknownAgent {
309                name: agent_name.to_string(),
310                dir: self.config_dir.clone(),
311            });
312        }
313        AgentConfig::load(&path).map_err(|source| RunnerError::ConfigLoad {
314            name: agent_name.to_string(),
315            source,
316        })
317    }
318
319    /// Resolve the gated registry, model, and assembled prompt, then run the loop.
320    ///
321    /// Why: Factoring the per-call pipeline out of the trait methods lets both
322    /// `run` and `run_with_context` share one implementation; the only
323    /// difference between them is the `RunContext` they pass in.
324    /// What: Loads the agent config, builds and gates its registry (honouring
325    /// `tools.allowed`), resolves the model (`RunContext` > agent > default) and
326    /// turn cap (`RunContext.max_turns_override` > runner default), assembles the
327    /// system prompt (BASE + agent prompt + project context), runs the
328    /// `AgentLoop` — attaching (#2279) `verify_gate::default_finish_gate` so a
329    /// premature `finish_task` gets a recoverable retry rather than
330    /// terminating the loop — and maps any loop error to `RunnerError::Loop`.
331    /// Test: `runner::tests::*`.
332    async fn run_pipeline(
333        &self,
334        agent_name: &str,
335        task: &str,
336        ctx: &RunContext,
337    ) -> Result<AgentOutput, RunnerError> {
338        let agent = self.load_agent(agent_name)?;
339
340        // Build the agent's full tool set, then gate it by `tools.allowed`.
341        let full_registry = self.registry_factory.build(&agent, ctx).await;
342        let registry = gate_registry(&full_registry, &agent);
343
344        // Resolve the model and the per-call turn cap (RunContext wins).
345        let model = resolve_model(&agent, Some(ctx));
346        let max_turns = ctx.max_turns_override.unwrap_or(self.config.max_turns);
347        // #run_task-maxtokens-bug: the delegated agent's own `[llm].max_tokens`
348        // must reach its loop — previously this was dropped entirely and every
349        // sub-agent turn was silently capped at the agent-loop default.
350        let max_tokens = resolve_max_tokens(&agent);
351
352        // #2308: derive the compaction threshold from this agent's ACTUAL
353        // resolved context window rather than the flat, model-blind
354        // `CompactionConfig::default()` — see that impl's doc for the root
355        // cause (a 6_000-token threshold is ~3% of a real 200K-token Bedrock
356        // Claude Sonnet window).
357        let compaction =
358            crate::agent_loop::CompactionConfig::for_context_window(resolve_context_window(&model));
359
360        let loop_config = AgentLoopConfig {
361            max_turns,
362            timeout_secs: self.config.timeout_secs,
363            model,
364            max_tokens,
365            mode: self.mode,
366            compaction,
367            // #2346: cadence stays disabled for the delegated sub-agent's own
368            // loop — the epic scopes cadence to the PM transcript only
369            // (`task::executor::run_and_record`'s persistent-session path);
370            // delegated engineer loops stay bounded/ephemeral per-delegation.
371            cadence: None,
372        };
373
374        // Assemble the mode-branched system prompt (BASE + agent prompt +
375        // project ctx) — see `assemble_system_prompt_for_mode`'s docs (#2059).
376        // Fallback guidance (the #1023 per-tier seam) is not wired here yet.
377        // `skills_catalog` (#2069) is appended only in `HarnessMode::DailyDriver`.
378        let system = assemble_system_prompt_for_mode(
379            self.mode,
380            &agent,
381            self.project_context.as_deref(),
382            None,
383            self.skills_catalog.as_deref(),
384        );
385
386        let mut agent_loop = AgentLoop::new(loop_config, Arc::clone(&self.llm), registry)
387            // #2279: every sub-agent this runner drives gets the default
388            // verify-before-finish gate — its own `bash` calls land in its
389            // own `Transcript`, so no external state is needed. This is the
390            // ONE production construction site for every delegated
391            // sub-agent loop (both `run_task` and `task::executor` delegate
392            // through this runner), so wiring it here covers both entry
393            // points without duplicating the attachment at each call site.
394            .with_finish_gate(crate::verify_gate::default_finish_gate())
395            // #2682: the complement to the verify gate above — suppress a
396            // redundant full-suite re-run once the suite has passed and nothing
397            // has changed since, so the engineer stops burning turns on
398            // repeated "one final run to confirm" passes. Same single
399            // construction site, so both `run_task` and `task::executor`
400            // delegations get it.
401            .with_redundant_run_suppression();
402        if let Some(sink) = &self.sink {
403            agent_loop = agent_loop.with_tool_event_sink(Arc::clone(sink));
404        }
405        if let Some(cancel) = &self.cancel {
406            agent_loop = agent_loop.with_cancel_flag(Arc::clone(cancel));
407        }
408
409        agent_loop
410            .run(&system, task)
411            .await
412            .map_err(|source| RunnerError::Loop {
413                name: agent_name.to_string(),
414                source,
415            })
416    }
417}
418
419/// Narrow a full registry to the agent's `tools.allowed`, if any.
420///
421/// Why: The agent loop dispatches with no per-call allowlist, so the enforcement
422/// point for `tools.allowed` (issue #1029) is handing the loop a registry that
423/// only contains the permitted tools. An absent (`None`) allowlist means "all
424/// tools the factory built are permitted".
425/// What: If `tools.allowed` is `Some(list)`, returns `Arc::new(full.gated(list))`;
426/// otherwise returns the full registry unchanged (cheap `Arc` clone).
427/// Test: `runner::tests::tools_allowed_is_enforced`,
428/// `runner::tests::no_allowlist_permits_all`.
429fn gate_registry(full: &Arc<ToolRegistry>, agent: &AgentConfig) -> Arc<ToolRegistry> {
430    match agent.tools.as_ref().and_then(|t| t.allowed.as_ref()) {
431        Some(allowed) => Arc::new(full.gated(allowed)),
432        None => Arc::clone(full),
433    }
434}
435
436#[async_trait]
437impl AgentRunner for InProcessAgentRunner {
438    /// Run `task` against the named agent with default per-call context.
439    ///
440    /// Why: The simplest entry point the delegate tool calls; no overrides.
441    /// What: Delegates to `run_pipeline` with a default `RunContext`, converting
442    /// `RunnerError` into the trait's `anyhow::Error`.
443    /// Test: `runner::tests::delegate_runs_engineer_loop`.
444    async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
445        let ctx = RunContext::default();
446        Ok(self.run_pipeline(agent_name, task, &ctx).await?)
447    }
448
449    /// Run `task` against the named agent honouring per-call `ctx` overrides.
450    ///
451    /// Why: The orchestrator may pin a model, working directory, or turn cap for
452    /// a single delegation; `RunContext` carries those without global state.
453    /// What: Delegates to `run_pipeline` with the supplied `ctx`.
454    /// Test: `runner::tests::run_context_overrides_max_turns`,
455    /// `runner::tests::run_context_overrides_model`.
456    async fn run_with_context(
457        &self,
458        agent_name: &str,
459        task: &str,
460        ctx: &RunContext,
461    ) -> Result<AgentOutput> {
462        Ok(self.run_pipeline(agent_name, task, ctx).await?)
463    }
464}
465
466/// Convenience: discover whether an agent config exists for `name` under `dir`.
467///
468/// Why: Callers (e.g. the orchestrator wiring the delegate tool) sometimes need
469/// to pre-check an agent name without constructing a runner; exposing the same
470/// path rule the runner uses keeps the two in lockstep.
471/// What: Returns `true` iff `<dir>/<name>.toml` exists.
472/// Test: `runner::tests::agent_config_exists_detects_present_and_absent`.
473pub fn agent_config_exists(dir: &Path, name: &str) -> bool {
474    dir.join(format!("{name}.toml")).exists()
475}