Skip to main content

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