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, LlmClientConfig, LlmClientTrait, LlmError,
};
pub const MOCK_LLM_ENV: &str = "TCODE_MOCK_LLM";
pub const MOCK_LLM_ECHO: &str = "echo";
pub fn build_llm_client() -> Result<Arc<dyn LlmClientTrait>, RpcError> {
if std::env::var(MOCK_LLM_ENV).ok().as_deref() == Some(MOCK_LLM_ECHO) {
return Ok(Arc::new(EchoLlmClient::new()));
}
let openrouter_config = LlmClientConfig::from_env().ok();
let client = DispatchingLlmClient::new(openrouter_config)
.map_err(|e| RpcError::internal(format!("build LLM client: {e}")))?;
Ok(Arc::new(client))
}
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 LlmClientTrait for EchoLlmClient {
async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, LlmError> {
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(LlmError::MissingConfig(format!(
"EchoLlmClient script exhausted at call {idx}"
)));
}
};
serde_json::from_value(fixture).map_err(|e| {
LlmError::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}
})
}
#[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,
};
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 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()
);
}
}