trusty_code/task/mock_llm.rs
1//! Deterministic, offline "echo" LLM client for #2056's mandatory offline
2//! testability (no live model, no API key).
3//!
4//! Why: task execution needs a live LLM in production, but the e2e/CI suite
5//! must exercise the FULL flow (create -> attach -> run -> live tool events
6//! -> done) without one. Setting `TCODE_MOCK_LLM=echo` (checked by
7//! [`build_llm_client`]) swaps this deterministic client in for the real
8//! `LlmClient` — the daemon still starts and serves `ping`/`health`/
9//! `session.*` fine with neither set; only `task.run` needs one or the
10//! other.
11//! What: [`EchoLlmClient`] replays a FIXED script exercising exactly the
12//! shape #2056 wires: the PM delegates once to `python-engineer`, which
13//! runs one `bash` tool call then stops, after which the PM sees the result
14//! and stops too. This is production code (not `#[cfg(test)]`) because the
15//! REAL `tcode` binary, spawned as a subprocess in `tests/task_e2e.rs`, must
16//! be able to construct it with no test harness in scope.
17//! Test: `task::mock_llm::tests::*`; exercised end-to-end (as a real
18//! subprocess) by `tests/task_e2e.rs`.
19
20use std::sync::Arc;
21use std::sync::atomic::{AtomicUsize, Ordering};
22
23use async_trait::async_trait;
24use serde_json::{Value, json};
25
26use crate::jsonrpc::RpcError;
27use crate::llm::{
28 ChatRequest, ChatResponse, DispatchingLlmClient, LlmClientConfig, LlmClientTrait, LlmError,
29};
30
31/// Environment variable selecting the mock LLM. Set to [`MOCK_LLM_ECHO`] to
32/// enable [`EchoLlmClient`] instead of a real OpenRouter client.
33pub const MOCK_LLM_ENV: &str = "TCODE_MOCK_LLM";
34
35/// The `TCODE_MOCK_LLM` value that selects [`EchoLlmClient`].
36pub const MOCK_LLM_ECHO: &str = "echo";
37
38/// Build the `Arc<dyn LlmClientTrait>` `task.run` executions share.
39///
40/// Why: the single seam that decides "real model or offline mock" — kept
41/// here (not inlined at each call site) so the decision is made exactly
42/// once and is easy to find.
43/// What: if [`MOCK_LLM_ENV`] is set to [`MOCK_LLM_ECHO`], returns an
44/// [`EchoLlmClient`]. Otherwise builds a real `DispatchingLlmClient` — routing
45/// `bedrock/*` model slugs to AWS Bedrock and everything else to OpenRouter
46/// via `OPENROUTER_API_KEY` (#1021 phase 1). `OPENROUTER_API_KEY` is read
47/// best-effort (via `LlmClientConfig::from_env().ok()`): a pure-Bedrock
48/// `task.run` must not be blocked by a key it will never use (#2245) — a
49/// missing key only surfaces as `RpcError::internal` if a non-bedrock model
50/// actually needs OpenRouter and it turns out to be unconfigured, at which
51/// point `DispatchingLlmClient::chat` returns that error and the caller
52/// still gets an actionable message naming both escape hatches.
53/// Test: `task::mock_llm::tests::mock_env_selects_echo_client`,
54/// `task::mock_llm::tests::real_client_builds_without_openrouter_key`.
55pub fn build_llm_client() -> Result<Arc<dyn LlmClientTrait>, RpcError> {
56 if std::env::var(MOCK_LLM_ENV).ok().as_deref() == Some(MOCK_LLM_ECHO) {
57 return Ok(Arc::new(EchoLlmClient::new()));
58 }
59 let openrouter_config = LlmClientConfig::from_env().ok();
60 let client = DispatchingLlmClient::new(openrouter_config)
61 .map_err(|e| RpcError::internal(format!("build LLM client: {e}")))?;
62 Ok(Arc::new(client))
63}
64
65/// A deterministic, scripted `LlmClientTrait` for offline task-execution
66/// testing (#2056).
67///
68/// Why: exercises the SAME PM -> engineer -> tool -> engineer-stop ->
69/// PM-stop shape `run_task`'s own offline tests use, but as production code
70/// so the real daemon binary can drive it with no network access at all.
71/// What: an atomic cursor over a fixed 4-response script:
72///
73/// 1. PM calls `delegate_to_agent(python-engineer, ...)`.
74/// 2. Engineer calls `bash(command="echo hello-from-mock-engineer")`.
75/// 3. Engineer stops with final text.
76/// 4. PM stops with final text.
77///
78/// Running past the script's end returns an `LlmError` rather than
79/// panicking, so a bug that adds an unexpected turn fails loudly instead of
80/// hanging.
81/// Test: `task::mock_llm::tests::script_drives_full_delegation_flow`.
82pub struct EchoLlmClient {
83 cursor: AtomicUsize,
84}
85
86impl EchoLlmClient {
87 /// Construct a fresh client at the start of its script.
88 pub fn new() -> Self {
89 Self {
90 cursor: AtomicUsize::new(0),
91 }
92 }
93}
94
95impl Default for EchoLlmClient {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101#[async_trait]
102impl LlmClientTrait for EchoLlmClient {
103 async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, LlmError> {
104 let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
105 let fixture = match idx {
106 0 => delegate_response(),
107 1 => bash_response(),
108 2 => stop_response("engineer: echoed hello-from-mock-engineer"),
109 3 => stop_response("pm: task complete"),
110 _ => {
111 return Err(LlmError::MissingConfig(format!(
112 "EchoLlmClient script exhausted at call {idx}"
113 )));
114 }
115 };
116 serde_json::from_value(fixture).map_err(|e| {
117 LlmError::MissingConfig(format!("EchoLlmClient: invalid scripted fixture: {e}"))
118 })
119 }
120}
121
122/// Turn 1 fixture: the PM delegates to `python-engineer`.
123fn delegate_response() -> Value {
124 json!({
125 "id": "mock-delegate",
126 "choices": [{
127 "message": {
128 "role": "assistant",
129 "content": null,
130 "tool_calls": [{
131 "id": "call-delegate",
132 "type": "function",
133 "function": {
134 "name": "delegate_to_agent",
135 "arguments": json!({"agent_name": "python-engineer", "task": "echo a greeting"}).to_string()
136 }
137 }]
138 },
139 "finish_reason": "tool_calls"
140 }],
141 "usage": {"prompt_tokens": 40, "completion_tokens": 10, "total_tokens": 50}
142 })
143}
144
145/// Turn 2 fixture: the engineer runs a single, known, side-effect-free `bash`
146/// command.
147fn bash_response() -> Value {
148 json!({
149 "id": "mock-bash",
150 "choices": [{
151 "message": {
152 "role": "assistant",
153 "content": null,
154 "tool_calls": [{
155 "id": "call-bash",
156 "type": "function",
157 "function": {
158 "name": "bash",
159 "arguments": json!({"command": "echo hello-from-mock-engineer"}).to_string()
160 }
161 }]
162 },
163 "finish_reason": "tool_calls"
164 }],
165 "usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}
166 })
167}
168
169/// A no-tool-call final-answer fixture (turns 3 and 4).
170fn stop_response(text: &str) -> Value {
171 json!({
172 "id": "mock-stop",
173 "choices": [{
174 "message": {"role": "assistant", "content": text, "tool_calls": []},
175 "finish_reason": "stop"
176 }],
177 "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
178 })
179}
180
181/// Serializes every test in this crate that sets/reads the process-wide
182/// [`MOCK_LLM_ENV`] var — `cargo test` runs tests in parallel within one
183/// binary, and an unguarded `set_var`/`remove_var` pair would race across
184/// modules (both here and in `task::protocol::tests`/`serve::tests`). A
185/// `tokio::sync::Mutex` (not `std::sync::Mutex`) because every caller holds
186/// the guard across an `.await` (the router dispatch the env var must stay
187/// set for) — clippy's `await_holding_lock` correctly flags a std mutex held
188/// that way.
189#[cfg(test)]
190pub(crate) static MOCK_LLM_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 /// The script must drive exactly the delegate -> bash -> stop -> stop
197 /// shape #2056's executor relies on.
198 #[tokio::test]
199 async fn script_drives_full_delegation_flow() {
200 let client = EchoLlmClient::new();
201 let req = ChatRequest {
202 model: "mock".to_string(),
203 messages: vec![],
204 temperature: None,
205 max_tokens: None,
206 tools: None,
207 tool_choice: None,
208 usage: None,
209 };
210
211 let turn1 = client.chat(&req).await.expect("turn 1");
212 assert_eq!(
213 turn1.first_tool_calls()[0].function.name,
214 "delegate_to_agent"
215 );
216
217 let turn2 = client.chat(&req).await.expect("turn 2");
218 assert_eq!(turn2.first_tool_calls()[0].function.name, "bash");
219
220 let turn3 = client.chat(&req).await.expect("turn 3");
221 assert!(turn3.first_tool_calls().is_empty());
222
223 let turn4 = client.chat(&req).await.expect("turn 4");
224 assert!(turn4.first_tool_calls().is_empty());
225
226 let err = client.chat(&req).await;
227 assert!(err.is_err(), "the script must not silently repeat");
228 }
229
230 /// `build_llm_client` must select the echo client when the env var is set.
231 #[tokio::test]
232 async fn mock_env_selects_echo_client() {
233 let _guard = MOCK_LLM_ENV_LOCK.lock().await;
234 // SAFETY: test-only env mutation; serialized by `MOCK_LLM_ENV_LOCK`.
235 unsafe {
236 std::env::set_var(MOCK_LLM_ENV, MOCK_LLM_ECHO);
237 }
238 let result = build_llm_client();
239 unsafe {
240 std::env::remove_var(MOCK_LLM_ENV);
241 }
242 assert!(result.is_ok(), "echo mode must never fail to construct");
243 }
244
245 /// `build_llm_client` must succeed even when `OPENROUTER_API_KEY` is
246 /// unset and mock mode is off — the real daemon `task.run` path a
247 /// pure-Bedrock run takes (#2245).
248 ///
249 /// Why: This is the exact function the default (non-`--legacy-in-process`)
250 /// `tcode run-task` path calls inside the daemon; pinning the fix here,
251 /// not just in `main.rs`, covers both entry points the smoke test's root
252 /// cause named.
253 /// What: Locks out `mock_env_selects_echo_client` (both mutate process
254 /// env), unsets `OPENROUTER_API_KEY`, asserts `Ok`.
255 /// Test: this test.
256 #[tokio::test]
257 async fn real_client_builds_without_openrouter_key() {
258 let _guard = MOCK_LLM_ENV_LOCK.lock().await;
259 let prev = std::env::var("OPENROUTER_API_KEY").ok();
260 // SAFETY: test-only env mutation; serialized by `MOCK_LLM_ENV_LOCK`
261 // (every test touching process-wide LLM-selection env vars in this
262 // module takes that lock, so this is safe alongside them too).
263 unsafe {
264 std::env::remove_var("OPENROUTER_API_KEY");
265 }
266 let result = build_llm_client();
267 if let Some(key) = prev {
268 // SAFETY: see above.
269 unsafe {
270 std::env::set_var("OPENROUTER_API_KEY", key);
271 }
272 }
273 assert!(
274 result.is_ok(),
275 "expected Ok when OPENROUTER_API_KEY is unset, got err: {:?}",
276 result.err()
277 );
278 }
279}