use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::jsonrpc::RpcError;
use crate::llm::{
ChatRequest, ChatResponse, DispatchingLlmClient, InferenceAdapter, InferenceError,
};
pub const MOCK_LLM_ENV: &str = "TCODE_MOCK_LLM";
pub const MOCK_LLM_ECHO: &str = "echo";
pub const MOCK_LLM_ECHO_FANOUT: &str = "echo-fanout";
pub const MOCK_LLM_ECHO_RECALL: &str = "echo-recall";
pub const MOCK_LLM_ECHO_SEARCH: &str = "echo-search";
pub const MOCK_LLM_ECHO_SOAK: &str = "echo-soak";
pub const MOCK_LLM_ECHO_SOAK_LOAD: &str = "echo-soak-load";
pub fn build_llm_client() -> Result<Arc<dyn InferenceAdapter>, RpcError> {
match std::env::var(MOCK_LLM_ENV).ok().as_deref() {
Some(MOCK_LLM_ECHO) => return Ok(Arc::new(EchoLlmClient::new())),
Some(MOCK_LLM_ECHO_FANOUT) => return Ok(Arc::new(FanoutEchoLlmClient::new())),
Some(MOCK_LLM_ECHO_RECALL) => return Ok(Arc::new(RecallEchoLlmClient::new())),
Some(MOCK_LLM_ECHO_SEARCH) => return Ok(Arc::new(SearchEchoLlmClient::new())),
Some(MOCK_LLM_ECHO_SOAK) => return Ok(Arc::new(SoakEchoLlmClient::new())),
Some(MOCK_LLM_ECHO_SOAK_LOAD) => return Ok(Arc::new(SoakLoadEchoLlmClient::new())),
_ => {}
}
Ok(Arc::new(DispatchingLlmClient::new()))
}
pub struct EchoLlmClient {
cursor: AtomicUsize,
}
impl EchoLlmClient {
pub fn new() -> Self {
Self {
cursor: AtomicUsize::new(0),
}
}
}
impl Default for EchoLlmClient {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl InferenceAdapter for EchoLlmClient {
crate::llm::mock_adapter_identity!("mock-echo");
async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
let fixture = match idx {
0 => delegate_response(),
1 => bash_response(),
2 => stop_response("engineer: echoed hello-from-mock-engineer"),
3 => stop_response("pm: task complete"),
_ => {
return Err(InferenceError::MissingConfig(format!(
"EchoLlmClient script exhausted at call {idx}"
)));
}
};
serde_json::from_value(fixture).map_err(|e| {
InferenceError::MissingConfig(format!("EchoLlmClient: invalid scripted fixture: {e}"))
})
}
}
fn delegate_response() -> Value {
json!({
"id": "mock-delegate",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call-delegate",
"type": "function",
"function": {
"name": "delegate_to_agent",
"arguments": json!({"agent_name": "python-engineer", "task": "echo a greeting"}).to_string()
}
}]
},
"finish_reason": "tool_calls"
}],
"usage": {"prompt_tokens": 40, "completion_tokens": 10, "total_tokens": 50}
})
}
fn bash_response() -> Value {
json!({
"id": "mock-bash",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call-bash",
"type": "function",
"function": {
"name": "bash",
"arguments": json!({"command": "echo hello-from-mock-engineer"}).to_string()
}
}]
},
"finish_reason": "tool_calls"
}],
"usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}
})
}
fn stop_response(text: &str) -> Value {
json!({
"id": "mock-stop",
"choices": [{
"message": {"role": "assistant", "content": text, "tool_calls": []},
"finish_reason": "stop"
}],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
})
}
pub struct FanoutEchoLlmClient {
cursor: AtomicUsize,
}
impl FanoutEchoLlmClient {
pub fn new() -> Self {
Self {
cursor: AtomicUsize::new(0),
}
}
}
impl Default for FanoutEchoLlmClient {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl InferenceAdapter for FanoutEchoLlmClient {
crate::llm::mock_adapter_identity!("mock-fanout-echo");
async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
let fixture = match idx {
0 => fanout_delegate_response(),
1 => bash_response_named("call-bash-a", "echo hello-from-engineer-a"),
2 => stop_response("engineer A: done"),
3 => bash_response_named("call-bash-b", "echo hello-from-engineer-b"),
4 => stop_response("engineer B: done"),
5 => stop_response("pm: fan-out complete"),
_ => {
return Err(InferenceError::MissingConfig(format!(
"FanoutEchoLlmClient script exhausted at call {idx}"
)));
}
};
serde_json::from_value(fixture).map_err(|e| {
InferenceError::MissingConfig(format!(
"FanoutEchoLlmClient: invalid scripted fixture: {e}"
))
})
}
}
fn fanout_delegate_response() -> Value {
json!({
"id": "mock-fanout-delegate",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call-delegate-a",
"type": "function",
"function": {
"name": "delegate_to_agent",
"arguments": json!({"agent_name": "python-engineer", "task": "task A"}).to_string()
}
},
{
"id": "call-delegate-b",
"type": "function",
"function": {
"name": "delegate_to_agent",
"arguments": json!({"agent_name": "python-engineer", "task": "task B"}).to_string()
}
}
]
},
"finish_reason": "tool_calls"
}],
"usage": {"prompt_tokens": 50, "completion_tokens": 20, "total_tokens": 70}
})
}
fn bash_response_named(call_id: &str, command: &str) -> Value {
json!({
"id": "mock-bash",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": call_id,
"type": "function",
"function": {
"name": "bash",
"arguments": json!({"command": command}).to_string()
}
}]
},
"finish_reason": "tool_calls"
}],
"usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}
})
}
pub struct RecallEchoLlmClient {
cursor: AtomicUsize,
}
impl RecallEchoLlmClient {
pub fn new() -> Self {
Self {
cursor: AtomicUsize::new(0),
}
}
}
impl Default for RecallEchoLlmClient {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl InferenceAdapter for RecallEchoLlmClient {
crate::llm::mock_adapter_identity!("mock-recall-echo");
async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
let fixture = match idx {
0 => recall_response(),
1 => stop_response("pm: recalled what I needed"),
_ => {
return Err(InferenceError::MissingConfig(format!(
"RecallEchoLlmClient script exhausted at call {idx}"
)));
}
};
serde_json::from_value(fixture).map_err(|e| {
InferenceError::MissingConfig(format!(
"RecallEchoLlmClient: invalid scripted fixture: {e}"
))
})
}
}
fn recall_response() -> Value {
json!({
"id": "mock-recall",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call-recall",
"type": "function",
"function": {
"name": "recall_session",
"arguments": json!({"query": "pkce oauth flow"}).to_string()
}
}]
},
"finish_reason": "tool_calls"
}],
"usage": {"prompt_tokens": 30, "completion_tokens": 10, "total_tokens": 40}
})
}
pub struct SearchEchoLlmClient {
cursor: AtomicUsize,
}
impl SearchEchoLlmClient {
pub fn new() -> Self {
Self {
cursor: AtomicUsize::new(0),
}
}
}
impl Default for SearchEchoLlmClient {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl InferenceAdapter for SearchEchoLlmClient {
crate::llm::mock_adapter_identity!("mock-search-echo");
async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
let fixture = match idx {
0 => delegate_response(),
1 => search_code_response(),
2 => stop_response("engineer: found it"),
3 => stop_response("pm: task complete"),
_ => {
return Err(InferenceError::MissingConfig(format!(
"SearchEchoLlmClient script exhausted at call {idx}"
)));
}
};
serde_json::from_value(fixture).map_err(|e| {
InferenceError::MissingConfig(format!(
"SearchEchoLlmClient: invalid scripted fixture: {e}"
))
})
}
}
fn search_code_response() -> Value {
json!({
"id": "mock-search",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call-search",
"type": "function",
"function": {
"name": "search_code",
"arguments": json!({"query": "where does auth live", "mode": "semantic"}).to_string()
}
}]
},
"finish_reason": "tool_calls"
}],
"usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}
})
}
#[path = "mock_llm_soak.rs"]
mod mock_llm_soak;
pub use mock_llm_soak::SoakEchoLlmClient;
#[path = "mock_llm_soak_load.rs"]
mod mock_llm_soak_load;
pub use mock_llm_soak_load::SoakLoadEchoLlmClient;
#[cfg(test)]
pub(crate) static MOCK_LLM_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn script_drives_full_delegation_flow() {
let client = EchoLlmClient::new();
let req = ChatRequest {
model: "mock".to_string(),
messages: vec![],
temperature: None,
max_tokens: None,
tools: None,
tool_choice: None,
usage: None,
stop: None,
};
let turn1 = client.chat(&req).await.expect("turn 1");
assert_eq!(
turn1.first_tool_calls()[0].function.name,
"delegate_to_agent"
);
let turn2 = client.chat(&req).await.expect("turn 2");
assert_eq!(turn2.first_tool_calls()[0].function.name, "bash");
let turn3 = client.chat(&req).await.expect("turn 3");
assert!(turn3.first_tool_calls().is_empty());
let turn4 = client.chat(&req).await.expect("turn 4");
assert!(turn4.first_tool_calls().is_empty());
let err = client.chat(&req).await;
assert!(err.is_err(), "the script must not silently repeat");
}
#[tokio::test]
async fn fanout_script_drives_two_delegations_to_the_same_agent() {
let client = FanoutEchoLlmClient::new();
let req = ChatRequest {
model: "mock".to_string(),
messages: vec![],
temperature: None,
max_tokens: None,
tools: None,
tool_choice: None,
usage: None,
stop: None,
};
let turn1 = client.chat(&req).await.expect("turn 1");
let calls = turn1.first_tool_calls();
assert_eq!(calls.len(), 2, "the PM must fan out to TWO delegations");
assert!(calls.iter().all(|c| c.function.name == "delegate_to_agent"));
assert!(
calls
.iter()
.all(|c| c.function.arguments.contains("python-engineer")),
"both delegations must target the SAME agent_name"
);
let turn2 = client.chat(&req).await.expect("turn 2 (engineer A bash)");
assert_eq!(turn2.first_tool_calls()[0].function.name, "bash");
let turn3 = client.chat(&req).await.expect("turn 3 (engineer A stop)");
assert!(turn3.first_tool_calls().is_empty());
let turn4 = client.chat(&req).await.expect("turn 4 (engineer B bash)");
assert_eq!(turn4.first_tool_calls()[0].function.name, "bash");
let turn5 = client.chat(&req).await.expect("turn 5 (engineer B stop)");
assert!(turn5.first_tool_calls().is_empty());
let turn6 = client.chat(&req).await.expect("turn 6 (pm stop)");
assert!(turn6.first_tool_calls().is_empty());
let err = client.chat(&req).await;
assert!(err.is_err(), "the script must not silently repeat");
}
#[tokio::test]
async fn recall_script_drives_a_single_recall_call() {
let client = RecallEchoLlmClient::new();
let req = ChatRequest {
model: "mock".to_string(),
messages: vec![],
temperature: None,
max_tokens: None,
tools: None,
tool_choice: None,
usage: None,
stop: None,
};
let turn1 = client.chat(&req).await.expect("turn 1");
let calls = turn1.first_tool_calls();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].function.name, "recall_session");
assert!(calls[0].function.arguments.contains("pkce"));
let turn2 = client.chat(&req).await.expect("turn 2 (pm stop)");
assert!(turn2.first_tool_calls().is_empty());
let err = client.chat(&req).await;
assert!(err.is_err(), "the script must not silently repeat");
}
#[tokio::test]
async fn search_script_drives_full_delegation_flow() {
let client = SearchEchoLlmClient::new();
let req = ChatRequest {
model: "mock".to_string(),
messages: vec![],
temperature: None,
max_tokens: None,
tools: None,
tool_choice: None,
usage: None,
stop: None,
};
let turn1 = client.chat(&req).await.expect("turn 1");
assert_eq!(
turn1.first_tool_calls()[0].function.name,
"delegate_to_agent"
);
let turn2 = client.chat(&req).await.expect("turn 2");
assert_eq!(turn2.first_tool_calls()[0].function.name, "search_code");
let turn3 = client.chat(&req).await.expect("turn 3");
assert!(turn3.first_tool_calls().is_empty());
let turn4 = client.chat(&req).await.expect("turn 4");
assert!(turn4.first_tool_calls().is_empty());
let err = client.chat(&req).await;
assert!(err.is_err(), "the script must not silently repeat");
}
#[tokio::test]
async fn mock_env_selects_echo_client() {
let _guard = MOCK_LLM_ENV_LOCK.lock().await;
unsafe {
std::env::set_var(MOCK_LLM_ENV, MOCK_LLM_ECHO);
}
let result = build_llm_client();
unsafe {
std::env::remove_var(MOCK_LLM_ENV);
}
assert!(result.is_ok(), "echo mode must never fail to construct");
}
#[tokio::test]
async fn real_client_builds_without_openrouter_key() {
let _guard = MOCK_LLM_ENV_LOCK.lock().await;
let prev = std::env::var("OPENROUTER_API_KEY").ok();
unsafe {
std::env::remove_var("OPENROUTER_API_KEY");
}
let result = build_llm_client();
if let Some(key) = prev {
unsafe {
std::env::set_var("OPENROUTER_API_KEY", key);
}
}
assert!(
result.is_ok(),
"expected Ok when OPENROUTER_API_KEY is unset, got err: {:?}",
result.err()
);
}
}