use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use async_trait::async_trait;
use serde_json::{Value, json};
use super::{AgentLoop, AgentLoopConfig, AgentLoopError, CompactionConfig, ToolEventSink};
use crate::llm::{ChatRequest, ChatResponse, LlmClientTrait, LlmError};
use crate::tools::{FinishTaskTool, ToolExecutor, ToolRegistry, ToolResult};
struct ScriptedLlm {
responses: Vec<ChatResponse>,
cursor: AtomicUsize,
requests: Mutex<Vec<Vec<crate::llm::ChatMessage>>>,
max_tokens_seen: Mutex<Vec<Option<u32>>>,
tools_seen: Mutex<Vec<Option<Vec<crate::llm::ToolDefinition>>>>,
usage_seen: Mutex<Vec<Option<crate::llm::RequestUsageConfig>>>,
}
impl ScriptedLlm {
fn from_json(fixtures: &[Value]) -> Self {
let responses = fixtures
.iter()
.map(|v| serde_json::from_value(v.clone()).expect("valid ChatResponse fixture"))
.collect();
Self {
responses,
cursor: AtomicUsize::new(0),
requests: Mutex::new(Vec::new()),
max_tokens_seen: Mutex::new(Vec::new()),
tools_seen: Mutex::new(Vec::new()),
usage_seen: Mutex::new(Vec::new()),
}
}
fn calls(&self) -> usize {
self.cursor.load(Ordering::SeqCst)
}
fn requests(&self) -> Vec<Vec<crate::llm::ChatMessage>> {
self.requests.lock().expect("lock").clone()
}
fn max_tokens_seen(&self) -> Vec<Option<u32>> {
self.max_tokens_seen.lock().expect("lock").clone()
}
fn tools_seen(&self) -> Vec<Option<Vec<crate::llm::ToolDefinition>>> {
self.tools_seen.lock().expect("lock").clone()
}
fn usage_seen(&self) -> Vec<Option<crate::llm::RequestUsageConfig>> {
self.usage_seen.lock().expect("lock").clone()
}
}
#[async_trait]
impl LlmClientTrait for ScriptedLlm {
async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
if let Ok(mut guard) = self.requests.lock() {
guard.push(req.messages.clone());
}
if let Ok(mut guard) = self.max_tokens_seen.lock() {
guard.push(req.max_tokens);
}
if let Ok(mut guard) = self.tools_seen.lock() {
guard.push(req.tools.clone());
}
if let Ok(mut guard) = self.usage_seen.lock() {
guard.push(req.usage.clone());
}
let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
match self.responses.get(idx) {
Some(resp) => Ok(resp.clone()),
None => Err(LlmError::MissingConfig(format!(
"scripted LLM exhausted at call {idx}"
))),
}
}
}
struct EchoTool {
fail: bool,
}
#[async_trait]
impl ToolExecutor for EchoTool {
fn name(&self) -> &str {
"echo"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "echo",
"description": "Echo the provided text back.",
"parameters": {
"type": "object",
"properties": { "text": { "type": "string" } },
"required": ["text"]
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
if self.fail {
return ToolResult::err("echo tool failed (recoverable)");
}
let text = args.get("text").and_then(Value::as_str).unwrap_or("<none>");
ToolResult::ok(format!("echo: {text}"))
}
}
fn tool_call_response(call_id: &str, text_arg: &str) -> Value {
json!({
"id": "gen-tool",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": call_id,
"type": "function",
"function": {
"name": "echo",
"arguments": format!("{{\"text\":\"{text_arg}\"}}")
}
}]
},
"finish_reason": "tool_calls"
}],
"usage": { "prompt_tokens": 12, "completion_tokens": 8, "total_tokens": 20 }
})
}
fn tool_call_with_stop_finish(call_id: &str, text_arg: &str) -> Value {
json!({
"id": "gen-tool-stop",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": call_id,
"type": "function",
"function": {
"name": "echo",
"arguments": format!("{{\"text\":\"{text_arg}\"}}")
}
}]
},
"finish_reason": "stop"
}],
"usage": { "prompt_tokens": 11, "completion_tokens": 9, "total_tokens": 20 }
})
}
fn stop_response(text: &str) -> Value {
json!({
"id": "gen-stop",
"choices": [{
"message": { "role": "assistant", "content": text, "tool_calls": [] },
"finish_reason": "stop"
}],
"usage": { "prompt_tokens": 7, "completion_tokens": 5, "total_tokens": 12 }
})
}
fn make_loop(
llm: Arc<ScriptedLlm>,
registry: Arc<ToolRegistry>,
config: AgentLoopConfig,
) -> AgentLoop {
AgentLoop::new(config, llm, registry)
}
fn registry_with_echo(fail: bool) -> Arc<ToolRegistry> {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(EchoTool { fail }));
Arc::new(reg)
}
fn finish_task_call_response(call_id: &str, raw_arguments: &str) -> Value {
json!({
"id": "gen-finish",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": call_id,
"type": "function",
"function": { "name": "finish_task", "arguments": raw_arguments }
}]
},
"finish_reason": "tool_calls"
}],
"usage": { "prompt_tokens": 6, "completion_tokens": 6, "total_tokens": 12 }
})
}
fn registry_with_finish_task() -> Arc<ToolRegistry> {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(FinishTaskTool::new()));
Arc::new(reg)
}
#[test]
fn config_defaults_are_sane() {
let cfg = AgentLoopConfig::default();
assert!(cfg.max_turns >= 1);
assert!(cfg.timeout_secs >= 1);
assert!(!cfg.model.is_empty());
assert!(
cfg.max_tokens > 1024,
"default max_tokens must exceed the old hard-coded 1024 cap"
);
}
#[tokio::test]
async fn configured_max_tokens_reaches_chat_request() {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let registry = registry_with_echo(false);
let agent = make_loop(
llm.clone(),
registry,
AgentLoopConfig {
max_tokens: 8192,
..AgentLoopConfig::default()
},
);
agent
.run("system", "write a file")
.await
.expect("single stop turn should complete");
let seen = llm.max_tokens_seen();
assert_eq!(seen, vec![Some(8192)]);
assert_ne!(
seen[0],
Some(1024),
"configured max_tokens must not be clamped back to the old default"
);
}
#[tokio::test]
async fn malformed_tool_arguments_report_recoverable_error_and_loop_continues() {
let malformed_call = json!({
"id": "gen-tool-malformed",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call_bad",
"type": "function",
"function": { "name": "echo", "arguments": "{not valid json" }
}]
},
"finish_reason": "tool_calls"
}],
"usage": { "prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10 }
});
let llm = Arc::new(ScriptedLlm::from_json(&[
malformed_call,
stop_response("Recovered from malformed arguments"),
]));
let registry = registry_with_echo(false);
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "call echo with bad json")
.await
.expect("loop should continue past malformed tool arguments");
assert_eq!(out.content, "Recovered from malformed arguments");
assert_eq!(
llm.calls(),
2,
"loop should make two calls despite the malformed call"
);
}
#[tokio::test]
async fn unknown_tool_call_reports_recoverable_error_and_loop_continues() {
let unknown_call = json!({
"id": "gen-tool-unknown",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call_unknown",
"type": "function",
"function": { "name": "does_not_exist", "arguments": "{}" }
}]
},
"finish_reason": "tool_calls"
}],
"usage": { "prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10 }
});
let llm = Arc::new(ScriptedLlm::from_json(&[
unknown_call,
stop_response("Recovered from unknown tool"),
]));
let registry = registry_with_echo(false);
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "call a nonexistent tool")
.await
.expect("loop should continue past an unknown tool call");
assert_eq!(out.content, "Recovered from unknown tool");
assert_eq!(llm.calls(), 2);
}
#[test]
fn schema_tool_name_extracts_or_falls_back() {
let good = json!({ "type": "function", "function": { "name": "echo" } });
assert_eq!(super::schema_tool_name(&good), "echo");
let no_function = json!({ "type": "function" });
assert_eq!(super::schema_tool_name(&no_function), "<unknown>");
let non_string_name = json!({ "function": { "name": 42 } });
assert_eq!(super::schema_tool_name(&non_string_name), "<unknown>");
}
#[test]
fn tool_definitions_identical_across_modes_in_m1() {
let llm = Arc::new(ScriptedLlm::from_json(&[]));
let registry = registry_with_echo(false);
let parity = make_loop(
llm.clone(),
registry.clone(),
AgentLoopConfig {
mode: crate::mode::HarnessMode::Parity,
..AgentLoopConfig::default()
},
);
let daily_driver = make_loop(
llm,
registry,
AgentLoopConfig {
mode: crate::mode::HarnessMode::DailyDriver,
..AgentLoopConfig::default()
},
);
assert_eq!(parity.tool_definitions(), daily_driver.tool_definitions());
}
fn aggressive_compaction() -> CompactionConfig {
CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
}
}
#[tokio::test]
async fn daily_driver_mode_compacts_long_running_loop() {
let mut fixtures: Vec<Value> = (0..5)
.map(|i| tool_call_response(&format!("call_{i}"), &format!("turn-{i}")))
.collect();
fixtures.push(stop_response("all done"));
let llm = Arc::new(ScriptedLlm::from_json(&fixtures));
let registry = registry_with_echo(false);
let agent = make_loop(
llm.clone(),
registry,
AgentLoopConfig {
max_turns: 10,
mode: crate::mode::HarnessMode::DailyDriver,
compaction: aggressive_compaction(),
..AgentLoopConfig::default()
},
);
agent
.run("system prompt", "the original task")
.await
.expect("run completes");
let requests = llm.requests();
let last_request = requests.last().expect("at least one request");
let has_summary = last_request
.iter()
.any(|m| m.content.as_deref().unwrap_or("").contains("[compacted"));
assert!(
has_summary,
"expected a compaction summary in {last_request:?}"
);
let tail = last_request.last().expect("non-empty request");
assert_eq!(tail.role, "user");
assert_eq!(tail.content.as_deref(), Some("the original task"));
assert!(
last_request.len() < 12,
"expected a shrunk request, got {} messages",
last_request.len()
);
}
#[tokio::test]
async fn parity_mode_never_compacts_even_past_threshold() {
let mut fixtures: Vec<Value> = (0..5)
.map(|i| tool_call_response(&format!("call_{i}"), &format!("turn-{i}")))
.collect();
fixtures.push(stop_response("all done"));
let llm = Arc::new(ScriptedLlm::from_json(&fixtures));
let registry = registry_with_echo(false);
let agent = make_loop(
llm.clone(),
registry,
AgentLoopConfig {
max_turns: 10,
mode: crate::mode::HarnessMode::Parity,
compaction: aggressive_compaction(),
..AgentLoopConfig::default()
},
);
agent
.run("system prompt", "the original task")
.await
.expect("run completes");
let requests = llm.requests();
for request in &requests {
let has_summary = request
.iter()
.any(|m| m.content.as_deref().unwrap_or("").contains("[compacted"));
assert!(!has_summary, "Parity must never compact, got {request:?}");
}
let last_request = requests.last().expect("at least one request");
assert_eq!(
last_request.len(),
12,
"Parity must send the full raw history"
);
}
#[tokio::test]
async fn parity_mode_message_sequences_are_model_independent() {
fn script() -> Vec<Value> {
let mut fixtures: Vec<Value> = (0..5)
.map(|i| tool_call_response(&format!("call_{i}"), &format!("turn-{i}")))
.collect();
fixtures.push(stop_response("all done"));
fixtures
}
fn run_with_model(model: &str) -> (AgentLoop, Arc<ScriptedLlm>) {
let llm = Arc::new(ScriptedLlm::from_json(&script()));
let registry = registry_with_echo(false);
let agent = make_loop(
llm.clone(),
registry,
AgentLoopConfig {
max_turns: 10,
model: model.to_string(),
mode: crate::mode::HarnessMode::Parity,
compaction: aggressive_compaction(),
..AgentLoopConfig::default()
},
);
(agent, llm)
}
let (agent_a, llm_a) = run_with_model("openai/gpt-4o-mini");
let (agent_b, llm_b) = run_with_model("anthropic/claude-opus-4-5");
agent_a
.run("system prompt", "the original task")
.await
.expect("run a completes");
agent_b
.run("system prompt", "the original task")
.await
.expect("run b completes");
assert_eq!(
llm_a.requests(),
llm_b.requests(),
"Parity's assembled message sequences must be identical across models"
);
}
#[tokio::test]
async fn two_turn_flow_completes() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call_1", "world"),
stop_response("Final answer: done"),
]));
let registry = registry_with_echo(false);
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("You are helpful.", "Echo 'world' then conclude.")
.await
.expect("loop should complete");
assert_eq!(out.content, "Final answer: done");
assert_eq!(llm.calls(), 2, "loop should make exactly two chat calls");
}
#[tokio::test]
async fn stop_finish_with_tool_call_still_dispatches() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_with_stop_finish("call_1", "world"),
stop_response("Final answer: done"),
]));
let registry = registry_with_echo(false);
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("You are helpful.", "Echo then conclude.")
.await
.expect("loop should dispatch the tool despite stop finish_reason");
assert_eq!(
out.content, "Final answer: done",
"must continue past the stop-with-tool-call turn, not exit early"
);
assert_eq!(
llm.calls(),
2,
"stop finish_reason must not short-circuit pending tool dispatch"
);
}
#[tokio::test]
async fn turn_cap_returns_partial_transcript() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("c1", "a"),
tool_call_response("c2", "b"),
tool_call_response("c3", "c"),
]));
let registry = registry_with_echo(false);
let config = AgentLoopConfig {
max_turns: 2,
..AgentLoopConfig::default()
};
let agent = make_loop(llm.clone(), registry, config);
let err = agent
.run("system", "loop forever")
.await
.expect_err("should hit the turn cap");
match err {
AgentLoopError::TurnCapExceeded { max_turns, partial } => {
assert_eq!(max_turns, 2);
assert!(
partial.usage.prompt_tokens > 0,
"partial usage should accrue"
);
}
other => panic!("expected TurnCapExceeded, got {other:?}"),
}
assert_eq!(llm.calls(), 2, "loop must stop calling at the cap");
}
#[tokio::test]
async fn timeout_returns_partial() {
struct SleepyLlm {
inner: ScriptedLlm,
delay: std::time::Duration,
}
#[async_trait]
impl LlmClientTrait for SleepyLlm {
async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
tokio::time::sleep(self.delay).await;
self.inner.chat(req).await
}
}
let llm: Arc<dyn LlmClientTrait> = Arc::new(SleepyLlm {
inner: ScriptedLlm::from_json(&[stop_response("too slow")]),
delay: std::time::Duration::from_secs(3),
});
let registry = registry_with_echo(false);
let config = AgentLoopConfig {
timeout_secs: 1,
..AgentLoopConfig::default()
};
let agent = AgentLoop::new(config, llm, registry);
let started = std::time::Instant::now();
let err = agent
.run("system", "a task that takes too long")
.await
.expect_err("a 1s deadline against a 3s-delayed response must time out");
let elapsed = started.elapsed();
match err {
AgentLoopError::Timeout {
timeout_secs,
partial,
} => {
assert_eq!(timeout_secs, 1, "must report the configured deadline");
let _ = partial;
}
other => panic!("expected Timeout, got {other:?}"),
}
assert!(
elapsed < std::time::Duration::from_secs(3),
"the 1s deadline must fire well before the mock's 3s delay, elapsed={elapsed:?}"
);
}
#[tokio::test]
async fn generous_timeout_does_not_abort_a_fast_run() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call_1", "world"),
stop_response("done well within budget"),
]));
let registry = registry_with_echo(false);
let config = AgentLoopConfig {
timeout_secs: 5,
..AgentLoopConfig::default()
};
let agent = make_loop(llm, registry, config);
let output = agent
.run("system", "quick task")
.await
.expect("a fast run under a generous deadline must not be aborted");
assert_eq!(output.content, "done well within budget");
}
#[tokio::test]
async fn recoverable_tool_error_continues() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call_1", "world"),
stop_response("Recovered and concluded"),
]));
let registry = registry_with_echo(true); let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "try the failing tool")
.await
.expect("loop should continue past a recoverable tool error");
assert_eq!(out.content, "Recovered and concluded");
assert_eq!(
llm.calls(),
2,
"loop should make two calls despite tool failure"
);
}
#[tokio::test]
async fn usage_accrues_across_turns() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call_1", "x"),
stop_response("done"),
]));
let registry = registry_with_echo(false);
let agent = make_loop(llm, registry, AgentLoopConfig::default());
let out = agent.run("system", "task").await.expect("completes");
assert_eq!(out.usage.prompt_tokens, 12 + 7);
assert_eq!(out.usage.completion_tokens, 8 + 5);
}
#[tokio::test]
async fn no_tools_immediate_stop() {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("just text")]));
let registry = Arc::new(ToolRegistry::new());
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "say something")
.await
.expect("completes");
assert_eq!(out.content, "just text");
assert_eq!(llm.calls(), 1);
}
#[tokio::test]
async fn explicit_finish_task_terminates_loop_with_structured_summary() {
let llm = Arc::new(ScriptedLlm::from_json(&[finish_task_call_response(
"call-finish",
r#"{"status": "completed", "summary": "implemented the feature"}"#,
)]));
let registry = registry_with_finish_task();
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "do the task")
.await
.expect("explicit finish_task should terminate the loop");
assert_eq!(llm.calls(), 1, "loop must not make a second chat call");
assert_eq!(out.summary.as_deref(), Some("implemented the feature"));
assert_eq!(
out.content, "Task completed: implemented the feature",
"content must reflect the structured report, not raw transcript text"
);
}
#[tokio::test]
async fn malformed_finish_task_repairs_then_terminates() {
let llm = Arc::new(ScriptedLlm::from_json(&[
finish_task_call_response("call-bad", "{not valid json"),
finish_task_call_response(
"call-good",
r#"{"status": "completed", "summary": "fixed and done"}"#,
),
]));
let registry = registry_with_finish_task();
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "do the task")
.await
.expect("loop should repair and terminate on the corrected call");
assert_eq!(
llm.calls(),
2,
"one malformed attempt, one repaired attempt"
);
assert_eq!(out.summary.as_deref(), Some("fixed and done"));
assert_eq!(out.content, "Task completed: fixed and done");
}
#[tokio::test]
async fn finish_task_missing_required_field_is_recoverable_not_terminal() {
let llm = Arc::new(ScriptedLlm::from_json(&[
finish_task_call_response("call-missing", r#"{"status": "completed"}"#),
stop_response("recovered from missing summary"),
]));
let registry = registry_with_finish_task();
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "do the task")
.await
.expect("missing required field must not abort the loop");
assert_eq!(llm.calls(), 2);
assert_eq!(out.content, "recovered from missing summary");
assert_eq!(
out.summary, None,
"the D3 fallback path must not set a finish_task summary"
);
}
#[tokio::test]
async fn finish_task_invalid_enum_value_is_recoverable_not_terminal() {
let llm = Arc::new(ScriptedLlm::from_json(&[
finish_task_call_response(
"call-bad-enum",
r#"{"status": "in_progress", "summary": "still working"}"#,
),
stop_response("recovered from bad enum value"),
]));
let registry = registry_with_finish_task();
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "do the task")
.await
.expect("invalid enum value must not abort the loop");
assert_eq!(llm.calls(), 2);
assert_eq!(out.content, "recovered from bad enum value");
}
#[tokio::test]
async fn finish_task_full_shape_propagates_into_output() {
let llm = Arc::new(ScriptedLlm::from_json(&[finish_task_call_response(
"call-full",
r#"{"status": "completed", "summary": "shipped it", "changes": [{"file": "a.rs", "lines_added": 10, "lines_removed": 2}], "tests_run": 4, "tests_passed": 4}"#,
)]));
let registry = registry_with_finish_task();
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default());
let out = agent
.run("system", "do the task")
.await
.expect("full-shape finish_task should terminate the loop");
assert!(out.content.contains("Task completed: shipped it"));
assert!(out.content.contains("a.rs (+10/-2)"));
assert!(out.content.contains("Tests: 4/4 passed"));
}
#[tokio::test]
#[ignore = "requires OPENROUTER_API_KEY; skipped in CI"]
async fn agent_loop_live() {
use crate::llm::{LlmClient, LlmClientConfig};
let Ok(key) = std::env::var("OPENROUTER_API_KEY") else {
eprintln!("OPENROUTER_API_KEY not set — skipping live agent-loop test");
return;
};
if key.is_empty() {
eprintln!("OPENROUTER_API_KEY empty — skipping live agent-loop test");
return;
}
let client = LlmClient::from_config(
LlmClientConfig::new(key)
.expect("config")
.with_title("trusty-code-agent-loop-test"),
)
.expect("client");
let registry = registry_with_echo(false);
let agent = AgentLoop::new(
AgentLoopConfig {
max_turns: 4,
timeout_secs: 60,
model: "openai/gpt-4o-mini".to_string(),
mode: crate::mode::HarnessMode::default(),
..AgentLoopConfig::default()
},
Arc::new(client),
registry,
);
let out = agent
.run(
"You are a concise assistant.",
"Reply with exactly the word: pong",
)
.await
.expect("live loop should complete");
assert!(!out.content.is_empty(), "final answer should be non-empty");
assert!(
out.usage.prompt_tokens > 0,
"usage should accrue on a live call"
);
eprintln!(
"live agent-loop output: {:?} usage={:?}",
out.content, out.usage
);
}
struct RecordingSink {
calls: Mutex<Vec<String>>,
}
impl RecordingSink {
fn new() -> Self {
Self {
calls: Mutex::new(Vec::new()),
}
}
fn calls(&self) -> Vec<String> {
self.calls.lock().expect("lock poisoned").clone()
}
}
#[async_trait]
impl ToolEventSink for RecordingSink {
async fn tool_started(&self, call_id: &str, tool: &str, _args_preview: &str) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("started:{tool}:{call_id}"));
}
async fn tool_finished(&self, call_id: &str, tool: &str, success: bool, _result_preview: &str) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("finished:{tool}:{call_id}:{success}"));
}
async fn tool_error(&self, call_id: &str, tool: &str, _error: &str) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("error:{tool}:{call_id}"));
}
}
#[tokio::test]
async fn sink_receives_started_then_finished_in_order() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
let registry = registry_with_echo(false);
let sink = Arc::new(RecordingSink::new());
let agent =
make_loop(llm, registry, AgentLoopConfig::default()).with_tool_event_sink(sink.clone());
agent
.run("sys", "task")
.await
.expect("loop should complete");
assert_eq!(
sink.calls(),
vec!["started:echo:call-1", "finished:echo:call-1:true"]
);
}
#[tokio::test]
async fn sink_recoverable_error_is_finished_not_error() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
let registry = registry_with_echo(true);
let sink = Arc::new(RecordingSink::new());
let agent =
make_loop(llm, registry, AgentLoopConfig::default()).with_tool_event_sink(sink.clone());
agent
.run("sys", "task")
.await
.expect("loop should complete");
assert_eq!(
sink.calls(),
vec!["started:echo:call-1", "finished:echo:call-1:false"]
);
}
#[tokio::test]
async fn cancel_flag_aborts_before_next_turn() {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
"should never be reached",
)]));
let registry = registry_with_echo(false);
let cancel = Arc::new(AtomicBool::new(true));
let agent =
make_loop(llm.clone(), registry, AgentLoopConfig::default()).with_cancel_flag(cancel);
let err = agent
.run("sys", "task")
.await
.expect_err("must abort as cancelled");
assert!(matches!(err, AgentLoopError::Cancelled { .. }));
assert_eq!(
llm.calls(),
0,
"cancellation must be observed before any chat call"
);
}
#[tokio::test]
async fn stop_signal_aborts_before_next_turn() {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
"should never be reached",
)]));
let registry = registry_with_echo(false);
let agent = make_loop(llm.clone(), registry, AgentLoopConfig::default())
.with_stop_signal(Arc::new(|| true));
let err = agent
.run("sys", "task")
.await
.expect_err("must abort as stopped-by-signal");
assert!(matches!(err, AgentLoopError::StoppedBySignal { .. }));
assert_eq!(
llm.calls(),
0,
"the stop signal must be observed before any chat call"
);
}
#[tokio::test]
async fn daily_driver_anthropic_model_marks_cache_breakpoints() {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let registry = registry_with_echo(false);
let agent = make_loop(
llm.clone(),
registry,
AgentLoopConfig {
model: "anthropic/claude-sonnet-4-5".into(),
mode: crate::mode::HarnessMode::DailyDriver,
..AgentLoopConfig::default()
},
);
agent
.run("you are a helpful assistant", "do the thing")
.await
.expect("single stop turn should complete");
let requests = llm.requests();
let system_msg = requests[0]
.iter()
.find(|m| m.role == "system")
.expect("system message present");
assert_eq!(
system_msg.cache_control,
Some(crate::llm::CacheControl::ephemeral()),
"system message must carry the cache breakpoint"
);
let tools = llm.tools_seen()[0]
.clone()
.expect("tools array present (echo tool registered)");
let last_tool = tools.last().expect("at least one tool");
assert_eq!(
last_tool.function.cache_control,
Some(crate::llm::CacheControl::ephemeral()),
"last tool definition must carry the cache breakpoint"
);
}
#[tokio::test]
async fn daily_driver_bedrock_model_marks_cache_breakpoints() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call_1", "world"),
stop_response("done"),
]));
let registry = registry_with_echo(false);
let agent = make_loop(
llm.clone(),
registry,
AgentLoopConfig {
model: "bedrock/us.anthropic.claude-sonnet-4-5".into(),
mode: crate::mode::HarnessMode::DailyDriver,
..AgentLoopConfig::default()
},
);
agent
.run("you are a helpful assistant", "do the thing")
.await
.expect("two-turn flow should complete");
let requests = llm.requests();
let system_msg = requests[0]
.iter()
.find(|m| m.role == "system")
.expect("system message present");
assert_eq!(
system_msg.cache_control,
Some(crate::llm::CacheControl::ephemeral()),
"system message must carry the cache breakpoint for a Bedrock route"
);
let tools = llm.tools_seen()[0]
.clone()
.expect("tools array present (echo tool registered)");
let last_tool = tools.last().expect("at least one tool");
assert_eq!(
last_tool.function.cache_control,
Some(crate::llm::CacheControl::ephemeral()),
"last tool definition must carry the cache breakpoint for a Bedrock route"
);
let second_request = &requests[1];
let non_system: Vec<&crate::llm::ChatMessage> = second_request
.iter()
.filter(|m| m.role != "system")
.collect();
assert_eq!(
non_system.len(),
3,
"expected user, assistant, and tool messages on the second turn"
);
assert!(
non_system[0].cache_control.is_none(),
"the oldest non-system message must NOT carry the breakpoint once it \
rolls outside the last-two window"
);
assert_eq!(
non_system[1].cache_control,
Some(crate::llm::CacheControl::ephemeral()),
"the assistant message (second-to-last) must carry the rolling history breakpoint"
);
assert_eq!(
non_system[2].cache_control,
Some(crate::llm::CacheControl::ephemeral()),
"the tool-result message (last) must carry the rolling history breakpoint"
);
}
#[tokio::test]
async fn parity_mode_never_marks_cache_breakpoints() {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let registry = registry_with_echo(false);
let agent = make_loop(
llm.clone(),
registry,
AgentLoopConfig {
model: "anthropic/claude-sonnet-4-5".into(),
mode: crate::mode::HarnessMode::Parity,
..AgentLoopConfig::default()
},
);
agent
.run("you are a helpful assistant", "do the thing")
.await
.expect("single stop turn should complete");
let requests = llm.requests();
let system_msg = requests[0]
.iter()
.find(|m| m.role == "system")
.expect("system message present");
assert!(
system_msg.cache_control.is_none(),
"Parity mode must never carry a cache breakpoint on the system message"
);
let tools = llm.tools_seen()[0]
.clone()
.expect("tools array present (echo tool registered)");
let last_tool = tools.last().expect("at least one tool");
assert!(
last_tool.function.cache_control.is_none(),
"Parity mode must never carry a cache breakpoint on the tools array"
);
}
#[tokio::test]
async fn non_anthropic_model_never_marks_cache_breakpoints() {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let registry = registry_with_echo(false);
let agent = make_loop(
llm.clone(),
registry,
AgentLoopConfig {
model: "openai/gpt-4o-mini".into(),
mode: crate::mode::HarnessMode::DailyDriver,
..AgentLoopConfig::default()
},
);
agent
.run("you are a helpful assistant", "do the thing")
.await
.expect("single stop turn should complete");
let requests = llm.requests();
let system_msg = requests[0]
.iter()
.find(|m| m.role == "system")
.expect("system message present");
assert!(
system_msg.cache_control.is_none(),
"non-Anthropic models must never carry a cache breakpoint on the system message"
);
let tools = llm.tools_seen()[0]
.clone()
.expect("tools array present (echo tool registered)");
let last_tool = tools.last().expect("at least one tool");
assert!(
last_tool.function.cache_control.is_none(),
"non-Anthropic models must never carry a cache breakpoint on the tools array"
);
}
#[tokio::test]
async fn build_request_sets_detailed_usage_for_openrouter() {
let or_llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let or_agent = make_loop(
or_llm.clone(),
registry_with_echo(false),
AgentLoopConfig {
model: "anthropic/claude-sonnet-4-5".into(),
..AgentLoopConfig::default()
},
);
or_agent
.run("you are a helpful assistant", "do the thing")
.await
.expect("single stop turn should complete");
assert_eq!(
or_llm.usage_seen()[0],
Some(crate::llm::RequestUsageConfig::detailed()),
"OpenRouter-routed requests must carry the detailed-usage directive"
);
let bedrock_llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let bedrock_agent = make_loop(
bedrock_llm.clone(),
registry_with_echo(false),
AgentLoopConfig {
model: "bedrock/us.anthropic.claude-sonnet-4-5".into(),
..AgentLoopConfig::default()
},
);
bedrock_agent
.run("you are a helpful assistant", "do the thing")
.await
.expect("single stop turn should complete");
assert_eq!(
bedrock_llm.usage_seen()[0],
None,
"Bedrock-routed requests must never carry the OpenRouter-only detailed-usage directive"
);
}