trusty_agents_common/runner.rs
1//! AgentRunner DI seam — portable types for task dispatch and agent output.
2//!
3//! Why: The `AgentRunner` trait (plus `RunContext`, `AgentOutput`, and
4//! `HistoryMessage`) is the SOA boundary between the workflow engine/PM loop
5//! and concrete agent implementations (subprocess, in-process, mock). Keeping
6//! these types in `trusty-agents` made it impossible for external crates (e.g.
7//! orchestration harnesses that don't depend on the full `trusty-agents`
8//! binary crate) to implement or mock the runner without a full dependency.
9//! Extracting to `trusty-agents-common` breaks that coupling: any crate that
10//! only needs to implement or test against `AgentRunner` can depend on this
11//! tiny crate. Moved to `trusty-agents-common` in Wave 2 (issue #867, refs
12//! #830/#832).
13//! What: Defines `HistoryMessage` (portable IPC wire type), `RunContext`
14//! (per-invocation directives), `AgentOutput` (agent result envelope), and
15//! the `AgentRunner` async trait.
16//! Note: `HistoryMessage::into_typed()` (which converts to async-openai's
17//! `ChatCompletionRequestMessage`) is NOT here — it requires `async-openai`
18//! and lives in `trusty-agents::session`. Only the portable
19//! `{role, content}` struct + its `user`/`assistant` constructors are here.
20//! Test: Compile-tested via `trusty-agents` which re-exports these types and
21//! has tests that construct `AgentOutput`, `RunContext`, and `HistoryMessage`.
22//! The `test_run_with_history_forwards_ctx` test in
23//! `trusty-agents::tools::traits` exercises the default `run_with_history`
24//! implementation, and is the bug #122 regression guard.
25
26use std::path::PathBuf;
27
28use anyhow::Result;
29use async_trait::async_trait;
30use serde::{Deserialize, Serialize};
31
32use crate::perf::TokenUsage;
33
34/// Simple `{role, content}` serializable form used over IPC.
35///
36/// Why: `ChatCompletionRequestMessage` is an async-openai enum with complex
37/// shape that doesn't round-trip cleanly through NDJSON IPC. A tiny
38/// `HistoryMessage` is trivially serde-friendly and enough to rebuild the
39/// typed messages on the sub-agent side.
40/// What: Pair of `role` ("user"|"assistant"|"system") and `content` strings.
41/// Note: The `into_typed()` method (which converts back to
42/// `ChatCompletionRequestMessage`) requires `async-openai` and therefore
43/// lives in `trusty-agents::session` as a standalone helper function rather
44/// than here. Call sites in `trusty-agents` use
45/// `trusty_agents::session::history_message_into_typed(msg)`.
46/// Test: See `trusty-agents::session` tests + IPC round-trip in
47/// `trusty-agents::ipc::tests`.
48#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
49pub struct HistoryMessage {
50 pub role: String,
51 pub content: String,
52}
53
54impl HistoryMessage {
55 /// Construct a `HistoryMessage` with role=`"user"`.
56 ///
57 /// Why: Callers serialize a dialog turn over IPC without touching the
58 /// role string directly, avoiding typos.
59 /// What: Plain struct literal with `role="user"`.
60 /// Test: Indirectly via `history_message_typed_round_trip` in
61 /// `trusty-agents::session::tests`.
62 #[allow(dead_code)]
63 pub fn user(content: impl Into<String>) -> Self {
64 Self {
65 role: "user".to_string(),
66 content: content.into(),
67 }
68 }
69
70 /// Construct a `HistoryMessage` with role=`"assistant"`.
71 ///
72 /// Why: Symmetric with `user` — keeps IPC construction declarative.
73 /// What: Plain struct literal with `role="assistant"`.
74 /// Test: Indirectly via `history_message_typed_round_trip` in
75 /// `trusty-agents::session::tests`.
76 #[allow(dead_code)]
77 pub fn assistant(content: impl Into<String>) -> Self {
78 Self {
79 role: "assistant".to_string(),
80 content: content.into(),
81 }
82 }
83}
84
85/// Per-invocation context threaded from orchestrator to agent runner.
86///
87/// Why: Previously, orchestrators (the wave loop in particular) passed
88/// per-call directives like the assigned file path and a tightened turn
89/// budget via process-global env vars (`std::env::set_var`). That is
90/// unsound in Rust 2024 because env mutation is not thread-safe under
91/// multi-threaded tokio runtimes. Threading a `RunContext` through the
92/// `AgentRunner` trait replaces the shared mutation with a per-call value
93/// that runners can apply to the child process (via `Command::env` / `current_dir`)
94/// without touching the parent's environment.
95/// What: Carries optional overrides — the assigned file for single-file
96/// wave-loop invocations, a per-call max-turns cap, and a working directory
97/// that the runner should use as the subprocess CWD.
98/// Test: Exercised indirectly through the wave-loop and runner dispatch
99/// tests (`wave_loop_runs_one_agent_per_file`, runner unit tests).
100#[derive(Debug, Default, Clone)]
101pub struct RunContext {
102 /// When `Some(path)`, the runner should scope any file-writing tool to
103 /// exactly this relative path. The wave loop sets this so each per-file
104 /// agent can only emit its assigned file.
105 pub assigned_file: Option<PathBuf>,
106 /// When `Some(n)`, the runner should enforce a max-turns cap of `n` for
107 /// this single invocation, overriding whatever the agent's TOML sets.
108 pub max_turns_override: Option<u32>,
109 /// When `Some(dir)`, the runner should use `dir` as the subprocess's
110 /// current working directory. Needed for the claude-code runner so the
111 /// CLI's file-writing tools resolve relative paths inside `out_dir`.
112 pub working_dir: Option<PathBuf>,
113 /// When `Some(model)`, the runner should use `model` as the LLM model for
114 /// this invocation, overriding the agent TOML's `[agent].model` /
115 /// `[llm].model_override`. Sourced from the workflow phase's
116 /// `model` field (#107, renamed from `model_override` in #359).
117 ///
118 /// Why: Previously the workflow engine only logged `phase.model`
119 /// as "advisory" — it never reached the runner. For `ClaudeCodeAgentRunner`
120 /// this meant every phase used the plan-agent TOML's model
121 /// (`claude-sonnet-4-6`) regardless of what `config/workflows/*.json`
122 /// specified. Threading the override through `RunContext` lets the runner
123 /// pass it as `--model` to the `claude` CLI (and via
124 /// `TAGENT_MODEL_<AGENT>` env for subprocess runners), preserving the
125 /// documented priority chain (env > phase override > agent TOML > default).
126 /// What: Optional string (e.g. `"anthropic/claude-opus-4-6"`). Runners that
127 /// don't understand it are free to ignore it; the default
128 /// `AgentRunner::run_with_context` still falls back to `run()` for mock
129 /// test doubles.
130 /// Test: `ClaudeCodeAgentRunner::run_with_config_ctx` honors it; the
131 /// engine populates it from `phase.model` in both the non-wave
132 /// and wave-loop paths.
133 pub model: Option<String>,
134}
135
136/// Structured output returned by an `AgentRunner`.
137///
138/// Why: Downstream workflow phases need a concise `summary` (~500 words) for
139/// template substitution while file-extraction still needs the full `content`.
140/// Bundling them in one struct lets callers choose which to consume without
141/// needing separate trait methods.
142/// What: `content` is the raw agent output; `summary` is the extracted
143/// `## Summary` section (or a prefix fallback); `usage` is the aggregated
144/// LLM token count for the invocation.
145/// Test: See workflow engine tests; constructed from `IpcMessage::Result`.
146#[derive(Debug, Clone)]
147pub struct AgentOutput {
148 pub content: String,
149 pub summary: Option<String>,
150 /// Aggregated LLM token usage for this agent invocation (#47).
151 ///
152 /// Why: `WorkflowEngine` needs per-phase token/cost data for the perf
153 /// record. Bubbling it from the sub-agent through the runner trait keeps
154 /// the instrumentation pipeline single-sourced.
155 /// What: `TokenUsage::default()` (all zeros) when no usage was reported
156 /// by the sub-agent (e.g. older binary or pre-LLM tool-only error).
157 /// Test: `perf::tests::collector_records_phases` exercises the sink;
158 /// end-to-end wiring is covered by workflow integration.
159 pub usage: TokenUsage,
160}
161
162impl AgentOutput {
163 /// Build from content alone; summary/usage will be defaults.
164 ///
165 /// Why: Most test doubles and simple callers only care about content;
166 /// a convenience constructor avoids boilerplate.
167 /// What: Constructs with empty summary and zero usage.
168 /// Test: Used across mock runner construction in unit tests.
169 #[allow(dead_code)]
170 pub fn from_content(content: impl Into<String>) -> Self {
171 Self {
172 content: content.into(),
173 summary: None,
174 usage: TokenUsage::default(),
175 }
176 }
177
178 /// Return summary if present, else fall back to content.
179 ///
180 /// Why: Template substitution in the workflow engine prefers the summary
181 /// (concise) but falls back to full content when no summary was extracted.
182 /// What: Returns `summary.as_deref()` or `&content`.
183 /// Test: Indirect — every template that calls `summary_or_content()`.
184 #[allow(dead_code)]
185 pub fn summary_or_content(&self) -> &str {
186 self.summary.as_deref().unwrap_or(&self.content)
187 }
188}
189
190/// Runs a task against a named agent.
191///
192/// Why: Abstracts over how an agent is executed — subprocess, in-process, or
193/// mock. Lets tests avoid spawning real processes.
194/// What: `run(agent_name, task)` returns the agent's `AgentOutput` (content
195/// plus optional summary). `run_with_history` extends this to pass prior
196/// conversation turns for persistent-session agents (#51); the default
197/// implementation ignores history so legacy impls keep working unchanged.
198/// Test: `tests/` substitute in-memory implementations; `test_run_with_history_forwards_ctx`
199/// in `trusty-agents::tools::traits` is the regression guard for default
200/// `run_with_history` forwarding through `run_with_context`.
201#[async_trait]
202pub trait AgentRunner: Send + Sync {
203 async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput>;
204
205 /// Run a task while forwarding any prior session history.
206 ///
207 /// Why: Persistent-session agents (#51) need their caller to replay
208 /// earlier user/assistant turns so the sub-agent can rebuild context
209 /// in a fresh subprocess. Bug #122: the previous default fell through to
210 /// `run()` instead of `run_with_context()`, so persistent-session callers
211 /// silently lost `working_dir` and `model` carried in `ctx`.
212 /// What: Default implementation ignores `history` and delegates to
213 /// `run_with_context(ctx)`, so `working_dir` and `model` are
214 /// honoured even for runners that do not override `run_with_history`.
215 /// Concrete runners that know how to carry history across the process
216 /// boundary override this.
217 /// Test: `SubprocessAgentRunner` exercises the override; the default
218 /// path is covered by `test_run_with_history_forwards_ctx` and the
219 /// existing mock-runner tests in `workflow`.
220 async fn run_with_history(
221 &self,
222 agent_name: &str,
223 task: &str,
224 _history: &[HistoryMessage],
225 ctx: &RunContext,
226 ) -> Result<AgentOutput> {
227 // Default: fall through to run_with_context so working_dir + model
228 // are honoured even when the concrete runner doesn't override run_with_history.
229 self.run_with_context(agent_name, task, ctx).await
230 }
231
232 /// Run a task with a `RunContext` carrying per-invocation overrides.
233 ///
234 /// Why: Replaces unsafe `std::env::set_var` threading of per-call state
235 /// (assigned file, tightened turn budget, working dir) with a structured
236 /// value that runners can apply to the child process only. Default impl
237 /// ignores the context and falls back to `run()` so existing mock runners
238 /// (including test doubles) keep working unchanged.
239 /// What: Concrete runners override this to scope env vars to the child
240 /// (`Command::env`) and optionally set its CWD (`Command::current_dir`).
241 /// Test: Wave-loop tests prove the context fields reach the child.
242 async fn run_with_context(
243 &self,
244 agent_name: &str,
245 task: &str,
246 _ctx: &RunContext,
247 ) -> Result<AgentOutput> {
248 self.run(agent_name, task).await
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use std::path::PathBuf;
255 use std::sync::{Arc, Mutex};
256
257 use anyhow::Result;
258 use async_trait::async_trait;
259
260 use super::{AgentOutput, AgentRunner, HistoryMessage, RunContext, TokenUsage};
261
262 /// Mock runner that records the RunContext it receives in `run_with_context`.
263 ///
264 /// Why: We need to assert that the trait default `run_with_history` impl
265 /// actually forwards `ctx` to `run_with_context` (bug #122 regression guard).
266 /// What: Stores each ctx snapshot; `run` is unused (test calls only
267 /// `run_with_history`).
268 /// Test: `test_run_with_history_forwards_ctx` constructs one of these,
269 /// calls `run_with_history` with a specific `RunContext`, and asserts the
270 /// recorded snapshot matches.
271 struct CtxCapture {
272 captured: Arc<Mutex<Vec<RunContext>>>,
273 }
274
275 #[async_trait]
276 impl AgentRunner for CtxCapture {
277 async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
278 Ok(AgentOutput {
279 content: "run".into(),
280 summary: None,
281 usage: TokenUsage::default(),
282 })
283 }
284
285 async fn run_with_context(
286 &self,
287 _agent_name: &str,
288 _task: &str,
289 ctx: &RunContext,
290 ) -> Result<AgentOutput> {
291 self.captured.lock().unwrap().push(ctx.clone());
292 Ok(AgentOutput {
293 content: "run_with_context".into(),
294 summary: None,
295 usage: TokenUsage::default(),
296 })
297 }
298 }
299
300 /// Verifies that the trait default `run_with_history` forwards `ctx` to
301 /// `run_with_context` rather than dropping it (bug #122 regression guard).
302 ///
303 /// Why: Before the fix, the default called `self.run()` which ignores ctx,
304 /// meaning persistent-session agents lost working_dir and model.
305 /// What: Calls `run_with_history` with specific working_dir and model,
306 /// then asserts `run_with_context` received those values.
307 /// Test: Run with `cargo test -p trusty-agents-common test_run_with_history_forwards_ctx`.
308 #[tokio::test]
309 async fn test_run_with_history_forwards_ctx() {
310 let captured = Arc::new(Mutex::new(Vec::new()));
311 let runner = CtxCapture {
312 captured: captured.clone(),
313 };
314
315 let ctx = RunContext {
316 working_dir: Some(PathBuf::from("/tmp/test-wd")),
317 model: Some("anthropic/claude-opus-4-5".to_string()),
318 max_turns_override: Some(5),
319 assigned_file: None,
320 };
321
322 let out = runner
323 .run_with_history("test-agent", "do something", &[], &ctx)
324 .await
325 .expect("run_with_history should succeed");
326
327 assert_eq!(
328 out.content, "run_with_context",
329 "default run_with_history must call run_with_context, not run()"
330 );
331
332 let snaps = captured.lock().unwrap();
333 assert_eq!(
334 snaps.len(),
335 1,
336 "run_with_context should be called exactly once"
337 );
338
339 let recorded = &snaps[0];
340 assert_eq!(
341 recorded.working_dir,
342 Some(PathBuf::from("/tmp/test-wd")),
343 "working_dir must be forwarded through run_with_history"
344 );
345 assert_eq!(
346 recorded.model,
347 Some("anthropic/claude-opus-4-5".to_string()),
348 "model must be forwarded through run_with_history"
349 );
350 assert_eq!(
351 recorded.max_turns_override,
352 Some(5),
353 "max_turns_override must be forwarded through run_with_history"
354 );
355 }
356
357 #[test]
358 fn history_message_constructors() {
359 let u = HistoryMessage::user("hello");
360 assert_eq!(u.role, "user");
361 assert_eq!(u.content, "hello");
362
363 let a = HistoryMessage::assistant("world");
364 assert_eq!(a.role, "assistant");
365 assert_eq!(a.content, "world");
366 }
367
368 #[test]
369 fn agent_output_from_content() {
370 let out = AgentOutput::from_content("test output");
371 assert_eq!(out.content, "test output");
372 assert!(out.summary.is_none());
373 assert_eq!(out.usage, TokenUsage::default());
374 }
375
376 #[test]
377 fn agent_output_summary_or_content_fallback() {
378 let out = AgentOutput::from_content("fallback content");
379 assert_eq!(out.summary_or_content(), "fallback content");
380
381 let out_with_summary = AgentOutput {
382 content: "full content".into(),
383 summary: Some("short summary".into()),
384 usage: TokenUsage::default(),
385 };
386 assert_eq!(out_with_summary.summary_or_content(), "short summary");
387 }
388}