trusty_code/task/executor.rs
1//! Daemon-owned background task execution (#2056): wires the session/event
2//! layer (#2054/#2055) to the existing engine (`agent_loop`/`runner`/`tools`/
3//! `llm`) — the M1 control-plane cut line.
4//!
5//! Why: `run_task` (the CLI's `tcode run-task`) already proves this engine
6//! end-to-end, but it runs synchronously, in the calling process, and
7//! renders a `RunReport` for a terminal. A daemon-driven task must instead
8//! run as a background task the triggering RPC does NOT block on, stream
9//! its progress live to `session.attach`ed clients via the #2055 event
10//! envelope, and persist its outcome onto the `Session` for a future
11//! `session.get_transcript` (#2058). This module is new glue, NOT a fork of
12//! the engine: it builds the exact same PM-delegates-to-engineer shape
13//! `run_task::execute_run_task` does (see that module's doc comment), reusing
14//! `agent_loop::AgentLoop`, `runner::InProcessAgentRunner`, `tools::*`, and
15//! `run_task`'s own public `RecordingLlmClient`/`TurnRecord`/
16//! `aggregate_usage_per_role`/`resolve_agent_model_slug` machinery — only the
17//! orchestration shell (spawn-and-report vs. run-and-render) differs.
18//! What: [`TaskRunParams`] carries one run's inputs; [`spawn_task_run`] is
19//! the single entry point `task::protocol::task_run` calls — it reserves the
20//! session's execution slot synchronously (rejecting a second overlapping
21//! run before any background work starts), then hands the actual run off to
22//! a `tokio::spawn`'d task that builds both loops (attaching the #2056
23//! `SessionToolEventSink` + a shared cancel flag to BOTH the PM's and the
24//! delegated engineer's `AgentLoop`), drives the PM loop, prices the
25//! transcript PER ROLE against each role's own resolved model via
26//! `run_task::aggregate_usage_per_role` (#1475 bug 1 — this daemon path and
27//! the legacy CLI path now share the ONE implementation, so they can never
28//! independently drift), persists the outcome, and transitions the session
29//! to its terminal state.
30//! Test: `task::executor::tests::*`; the full flow end-to-end (a real
31//! subprocess) in `tests/task_e2e.rs`.
32
33use std::path::PathBuf;
34use std::sync::atomic::AtomicBool;
35use std::sync::{Arc, Mutex};
36use std::time::Duration;
37
38use async_trait::async_trait;
39
40use crate::agent_loop::{AgentLoop, AgentLoopConfig, ToolEventSink};
41use crate::agents::AgentConfig;
42use crate::jsonrpc::RpcError;
43use crate::llm::{DebugCaptureSink, LlmClientTrait, wrap_with_debug_capture};
44use crate::mode::HarnessMode;
45use crate::project_context::load_project_context;
46use crate::prompt::assemble_system_prompt_for_mode;
47use crate::provider::{resolve_deadline_secs, resolve_max_tokens, resolve_model};
48use crate::run_task::{
49 RecordingLlmClient, SharedTranscript, aggregate_usage_per_role, resolve_agent_model_slug,
50};
51use crate::runner::{InProcessAgentRunner, RegistryFactory};
52use crate::session::{SessionRegistry, SessionStatus};
53use crate::skills::{FsSkillResolver, format_skill_catalog, locate_skills_dir};
54use crate::tools::{
55 AgentOutput, AgentRunner, BashTool, DelegateToAgentTool, EditTool, FinishTaskTool,
56 ReadFileTool, RunContext, SkillResolver, ToolRegistry, UseSkillTool, WriteFileTool,
57};
58
59use super::sink::SessionToolEventSink;
60
61/// Default bash timeout for the engineer's tools, in seconds (mirrors
62/// `run_task::ENGINEER_BASH_TIMEOUT_SECS` — not exported, so duplicated as a
63/// small constant rather than restructuring that module's visibility).
64const ENGINEER_BASH_TIMEOUT_SECS: u64 = 120;
65
66/// Hardcoded delegated engineer agent name, matching the `run_task`/fixture
67/// convention used across this crate (`<agents_dir>/python-engineer.toml`).
68/// A future ticket may make this configurable per `task.run` call.
69pub const ENGINEER_AGENT_NAME: &str = "python-engineer";
70
71/// Inputs to start one background task execution.
72///
73/// Why: bundles everything `spawn_task_run` needs so `task::protocol`'s
74/// handler stays a thin params-parsing shim.
75/// What: `session_id` must already exist in the registry (created by the
76/// caller — see `task::protocol::task_run`); `agent_name` is the top-level
77/// (PM) agent, `task` is the free-form request text, `project`/`agents_dir`
78/// mirror `run_task::RunTaskParams`, and `model_override` pins the
79/// DELEGATED ENGINEER's model for this run only (mirrors `run_task`'s
80/// `--engineer-model`). `mode` (#2059) is the ALREADY-RESOLVED `HarnessMode`
81/// (`task::protocol::task_run` resolves it via `crate::mode::resolve_mode`
82/// before constructing this — resolution is a request-parsing concern, not
83/// an execution one).
84#[derive(Debug, Clone)]
85pub struct TaskRunParams {
86 pub session_id: String,
87 pub task: String,
88 pub agent_name: String,
89 pub project: PathBuf,
90 pub agents_dir: PathBuf,
91 pub model_override: Option<String>,
92 pub mode: HarnessMode,
93 /// Per-run wall-clock deadline override, in seconds (#2207). `None`
94 /// falls through to `crate::provider::resolve_deadline_secs`'s env-var
95 /// and default tiers — resolved once in `run_and_record` and applied to
96 /// BOTH the PM's own loop and the delegated engineer's loop.
97 pub deadline_secs: Option<u64>,
98}
99
100/// Reserve the session's execution slot and spawn the background run.
101///
102/// Why: the single entry point `task::protocol::task_run` calls. Reserving
103/// the slot SYNCHRONOUSLY (before any `tokio::spawn`) is what makes "a
104/// second overlapping `task.run` on the same session is rejected"
105/// observable to the CALLER of the second request, not just internally.
106/// What: calls `registry.begin_execution` (propagating `session_not_found`/
107/// `invalid_argument` — already terminal / already running — verbatim),
108/// then spawns [`run_and_record`] and immediately attaches the real
109/// `JoinHandle` back onto the registry (see `SessionRegistry::attach_execution_handle`'s
110/// docs for why that is a separate call).
111/// Test: `task::executor::tests::spawn_task_run_rejects_second_overlapping_run`;
112/// the full run is exercised by `tests/task_e2e.rs`.
113pub fn spawn_task_run(
114 registry: Arc<SessionRegistry>,
115 llm: Arc<dyn LlmClientTrait>,
116 params: TaskRunParams,
117) -> Result<(), RpcError> {
118 let cancel = registry.begin_execution(¶ms.session_id)?;
119 let session_id = params.session_id.clone();
120 let registry_for_task = Arc::clone(®istry);
121
122 let handle = tokio::spawn(async move {
123 run_and_record(registry_for_task, llm, params, cancel).await;
124 });
125 registry.attach_execution_handle(&session_id, handle);
126 Ok(())
127}
128
129/// The actual PM -> engineer run, executed entirely inside the spawned task.
130///
131/// Why: kept as one function (rather than splitting further) because every
132/// step depends on state built by the previous one; the doc comment on
133/// `spawn_task_run` and the module docs carry the "why this shape" framing.
134/// What: loads the PM config (a failure here is recorded as a `Failed`
135/// outcome, not a panic); builds the engineer runner + PM registry with the
136/// SAME shape `run_task::execute_run_task` uses; runs the PM `AgentLoop`
137/// (both it and the delegated engineer share the #2056 sink + cancel flag);
138/// prices the transcript per-role; persists the outcome; and transitions the
139/// session to `Finished`/`Cancelled`/`Failed` before clearing the execution
140/// slot.
141async fn run_and_record(
142 registry: Arc<SessionRegistry>,
143 llm: Arc<dyn LlmClientTrait>,
144 params: TaskRunParams,
145 cancel: Arc<AtomicBool>,
146) {
147 let session_id = params.session_id.clone();
148 let transcript: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
149 let sink: Arc<dyn ToolEventSink> = Arc::new(SessionToolEventSink::new(
150 Arc::clone(®istry),
151 session_id.clone(),
152 ));
153
154 // #2264: mirrors `run_task::execute_run_task`'s own resolution — one
155 // shared (optional) debug-capture sink for the whole run, so pm and
156 // engineer turns land in one globally-ordered JSONL file when
157 // `TCODE_DEBUG_TRANSCRIPT` is set, and cost nothing when it is not.
158 let debug_sink: Option<Arc<DebugCaptureSink>> = DebugCaptureSink::from_env();
159
160 let pm_config_path = params
161 .agents_dir
162 .join(format!("{}.toml", params.agent_name));
163 let pm_config = match AgentConfig::load(&pm_config_path) {
164 Ok(cfg) => cfg,
165 Err(e) => {
166 finish_with_failure(®istry, &session_id, &format!("PM config error: {e:#}")).await;
167 return;
168 }
169 };
170
171 let project_context = load_project_context(¶ms.project);
172 let pm_model = resolve_model(&pm_config, None);
173 let engineer_model = resolve_engineer_model(¶ms);
174
175 // #2207: resolve the run's wall-clock deadline once, applied to BOTH the
176 // PM's own loop (below) and the delegated engineer's loop
177 // (`build_engineer_runner`, via `with_timeout_secs`).
178 let deadline_secs = resolve_deadline_secs(params.deadline_secs);
179
180 // #2069: discover the (cheap, metadata-only) skill catalog and, in
181 // DailyDriver mode only, register `use_skill` so the PM can lazily fetch
182 // a skill's full body on demand. Parity never sees the catalog or the
183 // tool — see `assemble_system_prompt_for_mode`'s docs.
184 let skills_catalog = daily_driver_skills_catalog(¶ms);
185
186 let engineer_runner = build_engineer_runner(
187 wrap_with_debug_capture(Arc::clone(&llm), ENGINEER_AGENT_NAME, debug_sink.as_ref()),
188 ¶ms,
189 project_context.clone(),
190 skills_catalog.as_ref().map(|(catalog, _)| catalog.clone()),
191 Arc::clone(&transcript),
192 Arc::clone(&sink),
193 Arc::clone(&cancel),
194 );
195
196 // #2072: `finish_task` gives the PM a structured, schema-validated way to
197 // signal completion alongside the delegate tool.
198 let mut pm_registry = ToolRegistry::new();
199 pm_registry.register(Arc::new(
200 DelegateToAgentTool::new(engineer_runner).with_config_dir(params.agents_dir.clone()),
201 ));
202 pm_registry.register(Arc::new(FinishTaskTool::new()));
203 if let Some((_, resolver)) = &skills_catalog {
204 pm_registry.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
205 }
206
207 let pm_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
208 wrap_with_debug_capture(Arc::clone(&llm), "pm", debug_sink.as_ref()),
209 "pm",
210 Arc::clone(&transcript),
211 ));
212
213 let catchup_ctx = crate::catchup::pm_catchup_context(¶ms.project).await;
214 let pm_system = assemble_system_prompt_for_mode(
215 params.mode,
216 &pm_config,
217 project_context.as_deref(),
218 catchup_ctx.as_deref(),
219 skills_catalog.as_ref().map(|(catalog, _)| catalog.as_str()),
220 );
221
222 let pm_loop = AgentLoop::new(
223 AgentLoopConfig {
224 model: pm_model.clone(),
225 max_tokens: resolve_max_tokens(&pm_config),
226 mode: params.mode,
227 timeout_secs: deadline_secs,
228 ..AgentLoopConfig::default()
229 },
230 pm_llm,
231 Arc::new(pm_registry),
232 )
233 .with_tool_event_sink(Arc::clone(&sink))
234 .with_cancel_flag(Arc::clone(&cancel));
235
236 let result = pm_loop.run(&pm_system, ¶ms.task).await;
237
238 // #2206: usage/cost are aggregated from every turn that DID complete
239 // regardless of `result` — this call already ran unconditionally before
240 // the terminal-status match below, so a `Failed`/`DeadlineExceeded`
241 // outcome still persists real telemetry, not zeroed placeholders.
242 let turns = transcript.lock().map(|g| g.clone()).unwrap_or_default();
243 let (usage, cost) = aggregate_usage_per_role(&turns, &pm_model, &engineer_model);
244 registry.set_run_outcome(&session_id, turns, usage, Some(cost));
245
246 // #2207: a wall-clock deadline is distinct from a genuine run failure —
247 // `SessionStatus::DeadlineExceeded` lets a `session.status`/`task.run`
248 // consumer tell "timed out, possibly close to done" from "errored".
249 let terminal_status = match result {
250 Ok(_output) => SessionStatus::Finished,
251 Err(crate::agent_loop::AgentLoopError::Cancelled { .. }) => SessionStatus::Cancelled,
252 Err(e @ crate::agent_loop::AgentLoopError::Timeout { .. }) => {
253 let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
254 SessionStatus::DeadlineExceeded
255 }
256 Err(e) => {
257 let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
258 SessionStatus::Failed
259 }
260 };
261 let _ = registry.finish(&session_id, terminal_status);
262 registry.finish_execution(&session_id);
263}
264
265/// Build the in-process engineer runner with project-scoped fs/bash tools,
266/// the #2056 sink, the shared cancel flag, and (#2059) the SAME resolved
267/// `HarnessMode` as the delegating PM (mirrors `run_task::build_engineer_runner`,
268/// which is private to that module).
269///
270/// `skills_catalog` (#2069) is the same rendered metadata catalog the PM's own
271/// prompt gets, threaded through so the delegated engineer's DailyDriver
272/// prompt also sees it. Wiring the `use_skill` *tool* into the engineer's own
273/// per-delegation registry (`ProjectToolFactory::build`) is deferred — see
274/// this crate's #2069 delivery notes. #2207: resolves the SAME wall-clock
275/// budget applied to the delegating PM's own loop via
276/// `crate::provider::resolve_deadline_secs(params.deadline_secs)` — called
277/// again here (rather than threaded in as an extra argument) purely to keep
278/// this function's arity under clippy's `too_many_arguments` gate; the
279/// resolver is pure given the same `params.deadline_secs`/env state, so a
280/// second call is not a correctness risk.
281fn build_engineer_runner(
282 llm: Arc<dyn LlmClientTrait>,
283 params: &TaskRunParams,
284 project_context: Option<String>,
285 skills_catalog: Option<String>,
286 transcript: SharedTranscript,
287 sink: Arc<dyn ToolEventSink>,
288 cancel: Arc<AtomicBool>,
289) -> Arc<dyn AgentRunner> {
290 let engineer_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
291 llm,
292 ENGINEER_AGENT_NAME,
293 transcript,
294 ));
295
296 let factory: Arc<dyn RegistryFactory> = Arc::new(ProjectToolFactory {
297 project: params.project.clone(),
298 mode: params.mode,
299 });
300
301 let mut runner = InProcessAgentRunner::new(engineer_llm, factory, params.agents_dir.clone())
302 .with_tool_event_sink(sink)
303 .with_cancel_flag(cancel)
304 .with_mode(params.mode)
305 .with_timeout_secs(resolve_deadline_secs(params.deadline_secs));
306 if let Some(ctx) = project_context {
307 runner = runner.with_project_context(ctx);
308 }
309 if let Some(catalog) = skills_catalog {
310 runner = runner.with_skills_catalog(catalog);
311 }
312 apply_engineer_model_override(Arc::new(runner), params)
313}
314
315/// Discover the (cheap, metadata-only) skill catalog for `params.project` and
316/// build a resolver over it — but only in `HarnessMode::DailyDriver`.
317///
318/// Why: #2069's scope note is explicit — "Parity mode should NOT
319/// progressively disclose" — so `Parity` runs must never discover
320/// `.claude/skills/` at all, let alone advertise the `use_skill` tool or
321/// inject the catalog into the prompt.
322/// What: Returns `None` for `HarnessMode::Parity` or when the project has no
323/// (or an empty) skill catalog; otherwise `Some((rendered_catalog,
324/// resolver))` — the resolver backs the `use_skill` tool registration.
325/// Test: `task::executor::tests::daily_driver_skills_catalog_*`.
326fn daily_driver_skills_catalog(params: &TaskRunParams) -> Option<(String, Arc<dyn SkillResolver>)> {
327 if params.mode != HarnessMode::DailyDriver {
328 return None;
329 }
330 let skills_dir = locate_skills_dir(¶ms.project);
331 let resolver: Arc<dyn SkillResolver> = Arc::new(FsSkillResolver::new(skills_dir));
332 let catalog = format_skill_catalog(&resolver.metadata());
333 if catalog.is_empty() {
334 None
335 } else {
336 Some((catalog, resolver))
337 }
338}
339
340/// Builds the engineer's project-scoped tool registry for each delegation
341/// (mirrors `run_task::ProjectToolFactory`, which is private to that module).
342struct ProjectToolFactory {
343 project: PathBuf,
344 /// #2073: the delegating run's resolved `HarnessMode`, threaded onto the
345 /// engineer's `EditTool` so `HarnessMode::Parity` selects edit-format
346 /// order the same way regardless of which model is delegated to (§5.9's
347 /// edit-format reconciliation). `run_task::ProjectToolFactory` (the
348 /// legacy CLI path, which never resolves a `HarnessMode`) intentionally
349 /// does not carry this field — its `EditTool` stays on the pre-#2073
350 /// plain per-model order, unchanged.
351 mode: HarnessMode,
352}
353
354#[async_trait]
355impl RegistryFactory for ProjectToolFactory {
356 async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
357 // #2068: resolve the engineer's model slug so `EditTool` can pick its
358 // per-model edit-format fallback order (mirrors
359 // `run_task::ProjectToolFactory::build`, which is private to that module).
360 let model_slug = resolve_model(agent, Some(ctx));
361 let mut reg = ToolRegistry::new();
362 reg.register(Arc::new(ReadFileTool::new(&self.project)));
363 reg.register(Arc::new(WriteFileTool::new(&self.project)));
364 reg.register(Arc::new(
365 EditTool::new(&self.project)
366 .with_model_slug(model_slug)
367 .with_mode(self.mode),
368 ));
369 reg.register(Arc::new(BashTool::new(
370 Some(self.project.clone()),
371 Duration::from_secs(ENGINEER_BASH_TIMEOUT_SECS),
372 )));
373 reg.register(Arc::new(FinishTaskTool::new()));
374 Arc::new(reg)
375 }
376}
377
378/// Apply the per-run engineer-model override, if any (mirrors
379/// `run_task::apply_engineer_model_override` / `ModelPinningRunner`, both
380/// private to that module).
381fn apply_engineer_model_override(
382 runner: Arc<dyn AgentRunner>,
383 params: &TaskRunParams,
384) -> Arc<dyn AgentRunner> {
385 match ¶ms.model_override {
386 Some(model) => Arc::new(ModelPinningRunner {
387 inner: runner,
388 model: model.clone(),
389 }),
390 None => runner,
391 }
392}
393
394/// An `AgentRunner` decorator pinning a fixed model for every delegation
395/// (mirrors `run_task::ModelPinningRunner`).
396struct ModelPinningRunner {
397 inner: Arc<dyn AgentRunner>,
398 model: String,
399}
400
401#[async_trait]
402impl AgentRunner for ModelPinningRunner {
403 async fn run(&self, agent_name: &str, task: &str) -> anyhow::Result<AgentOutput> {
404 let ctx = RunContext {
405 model: Some(self.model.clone()),
406 ..Default::default()
407 };
408 self.inner.run_with_context(agent_name, task, &ctx).await
409 }
410
411 async fn run_with_context(
412 &self,
413 agent_name: &str,
414 task: &str,
415 ctx: &RunContext,
416 ) -> anyhow::Result<AgentOutput> {
417 let mut ctx = ctx.clone();
418 ctx.model = Some(self.model.clone());
419 self.inner.run_with_context(agent_name, task, &ctx).await
420 }
421}
422
423/// Resolve the engineer's model the SAME way `InProcessAgentRunner` does
424/// internally, purely so the cost split below can price the engineer's
425/// turns against its own slug rather than blending everything under the PM
426/// model.
427///
428/// Why: `InProcessAgentRunner` resolves the engineer's model internally and
429/// does not expose it; `run_task::resolve_agent_model_slug` (#2061's #1475
430/// bug 1 fix) is the ONE shared implementation of "load config, apply
431/// override else resolve from config, degrade to `unknown` on load
432/// failure" this daemon path and `run_task::execute_run_task`'s legacy CLI
433/// path both now call, so they can never independently drift.
434/// What: thin wrapper binding this module's `ENGINEER_AGENT_NAME` constant
435/// and `params.model_override`.
436fn resolve_engineer_model(params: &TaskRunParams) -> String {
437 resolve_agent_model_slug(
438 ¶ms.agents_dir,
439 ENGINEER_AGENT_NAME,
440 params.model_override.as_deref(),
441 )
442}
443
444/// Record a diagnostic log line and transition the session to `Failed`.
445///
446/// Why: a PM-config load failure happens before any loop runs, so there is
447/// no transcript/usage to persist — just the terminal state and a reason an
448/// operator (or a future `session.get_transcript`) can see.
449async fn finish_with_failure(registry: &SessionRegistry, session_id: &str, message: &str) {
450 let _ = registry.record_log(session_id, "error", message);
451 let _ = registry.finish(session_id, SessionStatus::Failed);
452 registry.finish_execution(session_id);
453}
454
455#[cfg(test)]
456#[path = "executor_tests.rs"]
457mod tests;