1use crate::compact::{CompactionOutcome, compact_history};
2use crate::llm::{Completion, ConversationUsageWindow, LLMClientDyn, TokenUsage, throttled_completion};
3use crate::prompts::subagent_system_prompt;
4use crate::session::{SessionWriter, ToolCallRecord, now_unix_ms};
5use crate::tools::{Tool, floor_char_boundary, tool_definitions};
6use eyre::Result;
7use futures::future::join_all;
8use rig_core::OneOrMany;
9use rig_core::completion::Message;
10use rig_core::completion::message::{ToolResult, ToolResultContent, UserContent};
11use serde_json::{Value, json};
12use std::collections::{HashMap, VecDeque};
13use std::path::{Path, PathBuf};
14use std::sync::atomic::{AtomicUsize, Ordering};
15use std::sync::{Arc, Mutex};
16use tokio::sync::Semaphore;
17use tracing::{debug, info, warn};
18
19const MAX_TOOL_RESULT_BYTES: usize = 50_000;
20pub const MAX_CONCURRENT_LLM_CALLS: usize = 16;
23const MAX_CONSECUTIVE_IDENTICAL_TOOL_CALLS: usize = 3;
24const MAX_CYCLE_REPETITIONS: usize = 2;
25const TOOL_CALL_HISTORY_WINDOW: usize = 8;
26const MAX_SUBAGENT_DEPTH: usize = 2;
27const MAX_CONSECUTIVE_BLOCKED_TOOL_CALLS: usize = 3;
28const FINAL_TURN_WRAP_UP_PROMPT: &str = "Budget is nearly exhausted. Stop investigating and wrap up now with your best final answer based on the evidence you already gathered. Do not call more investigation tools.";
29
30pub struct AgentResult {
31 pub text: String,
32 pub turns: usize,
33 pub tool_calls: usize,
34 pub subagents_spawned: usize,
35 pub total_input_tokens: u64,
36 pub total_output_tokens: u64,
37 pub total_tokens: u64,
38}
39
40impl AgentResult {
41 pub fn usage(&self) -> TokenUsage {
44 TokenUsage {
45 input_tokens: self.total_input_tokens,
46 output_tokens: self.total_output_tokens,
47 total_tokens: self.total_tokens,
48 }
49 }
50}
51
52pub struct AgentProgress {
53 pub turns: usize,
54 pub tool_calls: usize,
55 pub subagents_spawned: usize,
56 pub last_subagent: Option<String>,
57}
58
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60pub enum AgentDepth {
61 TopLevel,
62 Subagent { level: usize },
63}
64
65impl AgentDepth {
66 fn level(self) -> usize {
67 match self {
68 AgentDepth::TopLevel => 0,
69 AgentDepth::Subagent { level } => level,
70 }
71 }
72
73 fn is_subagent(self) -> bool {
74 matches!(self, AgentDepth::Subagent { .. })
75 }
76
77 fn can_spawn_subagent(self) -> bool {
78 self.level() < MAX_SUBAGENT_DEPTH
79 }
80}
81
82pub struct AgentConfig {
83 pub name: String,
84 pub session_agent: String,
85 pub model: String,
86 pub max_turns: usize,
87 pub compact_threshold: Option<u64>,
88 pub system_prompt: String,
89 pub subagent_system_prompt: Option<String>,
93 pub client: Arc<dyn LLMClientDyn>,
94 pub depth: AgentDepth,
95 pub terminal_tools: Vec<String>,
96 pub empty_response_nudge: Option<String>,
97 pub max_empty_responses: usize,
98 pub subagent_counter: Arc<AtomicUsize>,
99 pub llm_semaphore: Arc<Semaphore>,
100 pub progress: Option<Arc<dyn Fn(AgentProgress) + Send + Sync>>,
101 pub project_context: Option<String>,
102 pub session_writer: Option<SessionWriter>,
103}
104
105struct FinishTool {
106 result: Arc<Mutex<Option<String>>>,
107}
108
109struct ToolCallContext<'a> {
110 config: &'a AgentConfig,
111 runtime_tools: &'a HashMap<String, Arc<dyn Tool>>,
112 tools_map: &'a HashMap<String, Arc<dyn Tool>>,
113 work_dir: &'a Path,
114 turn: usize,
115 current_turns: usize,
116 total_tool_calls: usize,
117 initial_subagent_count: usize,
118}
119
120struct ToolCallOutcome {
121 output: String,
122 nested_tool_calls: usize,
123 repeated_tool_call_blocked: bool,
124 status: &'static str,
125 spawned_agent: Option<String>,
126 subagent_input_tokens: u64,
127 subagent_output_tokens: u64,
128 subagent_total_tokens: u64,
129}
130
131struct PreparedSubagent {
132 task: String,
133 spawned_agent: String,
134 config: AgentConfig,
135}
136
137struct SubagentOutcome {
138 output: String,
139 tool_calls: usize,
140 spawned_agent: Option<String>,
141 input_tokens: u64,
142 output_tokens: u64,
143 total_tokens: u64,
144}
145
146impl Tool for FinishTool {
147 fn name(&self) -> String {
148 "finish".to_string()
149 }
150
151 fn definition(&self) -> rig_core::completion::ToolDefinition {
152 rig_core::completion::ToolDefinition {
153 name: "finish".to_string(),
154 description:
155 "Finish the assigned subtask and return the final result to the parent agent."
156 .to_string(),
157 parameters: json!({
158 "type": "object",
159 "properties": {
160 "result": {
161 "type": "string",
162 "description": "Concise final result for the parent agent"
163 }
164 },
165 "required": ["result"],
166 "additionalProperties": false
167 }),
168 }
169 }
170
171 fn call(
172 &self,
173 args: Value,
174 _work_dir: PathBuf,
175 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
176 let result_store = Arc::clone(&self.result);
177 Box::pin(async move {
178 let result = args
179 .get("result")
180 .and_then(|value| value.as_str())
181 .ok_or_else(|| eyre::eyre!("missing result"))?
182 .to_string();
183 *result_store.lock().unwrap_or_else(|e| e.into_inner()) = Some(result);
184 Ok("ok".to_string())
185 })
186 }
187}
188
189pub async fn run_agent(
190 config: AgentConfig,
191 initial_message: &str,
192 tools_map: &HashMap<String, Arc<dyn Tool>>,
193 work_dir: &Path,
194) -> Result<AgentResult> {
195 let finish_store = Arc::new(Mutex::new(None));
196 let mut runtime_tools = tools_map.clone();
197 if config.depth.is_subagent() {
198 let finish_tool = Arc::new(FinishTool {
199 result: Arc::clone(&finish_store),
200 });
201 runtime_tools.insert("finish".to_string(), finish_tool as Arc<dyn Tool>);
202 }
203
204 let mut effective_system_prompt = config.system_prompt.clone();
205 if let Some(ref ctx) = config.project_context {
206 if !ctx.is_empty() {
207 effective_system_prompt.push_str("\n\n");
208 effective_system_prompt.push_str(ctx);
209 }
210 }
211
212 let mut history = Vec::new();
213 let mut prompt = Message::user(initial_message.to_string());
214 history.push(prompt.clone());
215 let mut total_input_tokens = 0u64;
216 let mut total_output_tokens = 0u64;
217 let mut total_tokens = 0u64;
218 let mut conversation_usage = ConversationUsageWindow::new(config.compact_threshold);
219 let mut total_tool_calls = 0usize;
220 let mut empty_response_count = 0usize;
221 let mut tool_call_history: VecDeque<String> = VecDeque::new();
222 let initial_subagent_count = config.subagent_counter.load(Ordering::Relaxed);
223 let mut consecutive_blocked_count = 0usize;
224 let mut last_subagent: Option<String> = None;
225
226 for turn in 0..config.max_turns {
227 let is_final_turn = turn + 1 == config.max_turns;
228 let mut available_tools = runtime_tools.clone();
229 if !config.depth.can_spawn_subagent() || is_final_turn {
230 available_tools.remove("spawn_subagent");
231 }
232
233 if !is_final_turn && conversation_usage.should_compact() {
234 let usage_before_compaction = conversation_usage.usage();
235 info!(
236 agent = %config.name,
237 turn,
238 compact_threshold = config.compact_threshold,
239 window_input_tokens = usage_before_compaction.input_tokens,
240 window_output_tokens = usage_before_compaction.output_tokens,
241 window_total_tokens = usage_before_compaction.total_tokens,
242 "compaction triggered"
243 );
244 let compaction = compact_history(
245 &config.llm_semaphore,
246 Arc::clone(&config.client),
247 &config.model,
248 &effective_system_prompt,
249 &mut history,
250 &mut prompt,
251 turn + 1,
252 usage_before_compaction,
253 )
254 .await?;
255 if let Some(ref c) = compaction {
256 total_input_tokens = total_input_tokens.saturating_add(c.usage.input_tokens);
257 total_output_tokens = total_output_tokens.saturating_add(c.usage.output_tokens);
258 total_tokens = total_tokens.saturating_add(c.usage.total_tokens);
259 }
260 conversation_usage.reset();
261 log_compaction(&config, turn, "threshold", compaction.as_ref()).await;
262 }
263
264 if is_final_turn {
265 available_tools.retain(|name, _| {
266 config
267 .terminal_tools
268 .iter()
269 .any(|terminal| terminal == name)
270 || (config.depth.is_subagent() && name == "finish")
271 });
272 let wrap_up_prompt = Message::user(FINAL_TURN_WRAP_UP_PROMPT.to_string());
273 history.push(wrap_up_prompt.clone());
274 prompt = wrap_up_prompt;
275 }
276
277 let completion = Completion {
278 model: config.model.clone(),
279 prompt: prompt.clone(),
280 preamble: Some(effective_system_prompt.clone()),
281 history: history[..history.len().saturating_sub(1)].to_vec(),
282 tools: tool_definitions(&available_tools),
283 tool_choice: None,
284 max_tokens: Some(8192),
285 additional_params: None,
286 };
287
288 let response =
291 throttled_completion(&config.llm_semaphore, &config.client, completion).await?;
292 total_input_tokens = total_input_tokens.saturating_add(response.usage.input_tokens);
293 total_output_tokens = total_output_tokens.saturating_add(response.usage.output_tokens);
294 total_tokens = total_tokens.saturating_add(response.usage.total_tokens);
295 conversation_usage.record(response.usage);
296 let selected_model = response.selected_model.clone();
297 let assistant_message = response.message();
298 history.push(assistant_message.clone());
299
300 if let Some(tool_calls) = response.tool_calls() {
301 empty_response_count = 0;
302 total_tool_calls += tool_calls.len();
303 report_progress(
304 &config,
305 turn + 1,
306 total_tool_calls,
307 initial_subagent_count,
308 last_subagent.clone(),
309 );
310
311 let mut should_terminate = false;
314 let mut cycle_lens = Vec::with_capacity(tool_calls.len());
315 for call in &tool_calls {
316 let tool_name = &call.function.name;
317 let args = &call.function.arguments;
318 let tool_call_key = format!("{tool_name}:{args}");
319 tool_call_history.push_back(tool_call_key);
320 if tool_call_history.len() > TOOL_CALL_HISTORY_WINDOW {
321 tool_call_history.pop_front();
322 }
323 cycle_lens.push(detect_tool_call_cycle(&tool_call_history));
324 if tool_name == "spawn_subagent" {
325 if let Some(task) = args.get("task").and_then(|v| v.as_str()) {
326 last_subagent = Some(first_line(task));
327 }
328 }
329 match &selected_model {
330 Some(m) => info!(agent = %config.name, tool = %tool_name, args = %args, turn, model = %m, "tool call"),
331 None => info!(agent = %config.name, tool = %tool_name, args = %args, turn, "tool call"),
332 }
333 }
334
335 let outcomes = join_all(tool_calls.iter().zip(&cycle_lens).map(|(call, &cycle_len)| {
338 execute_tool_call(
339 ToolCallContext {
340 config: &config,
341 runtime_tools: &available_tools,
342 tools_map,
343 work_dir,
344 turn,
345 current_turns: turn + 1,
346 total_tool_calls,
347 initial_subagent_count,
348 },
349 call.function.name.as_str(),
350 call.function.arguments.clone(),
351 cycle_len,
352 )
353 }))
354 .await;
355
356 let mut results = Vec::with_capacity(tool_calls.len());
359 for (call, outcome) in tool_calls.iter().zip(outcomes) {
360 let outcome = outcome?;
361 let blocked = outcome.repeated_tool_call_blocked;
362 if blocked {
363 consecutive_blocked_count += 1;
364 } else {
365 consecutive_blocked_count = 0;
366 }
367 if !blocked
371 && outcome.status != "error"
372 && config
373 .terminal_tools
374 .iter()
375 .any(|name| name == &call.function.name)
376 {
377 should_terminate = true;
378 }
379 let ToolCallOutcome {
380 mut output,
381 nested_tool_calls,
382 repeated_tool_call_blocked: _,
383 status: _,
384 spawned_agent: _,
385 subagent_input_tokens,
386 subagent_output_tokens,
387 subagent_total_tokens,
388 } = outcome;
389 total_tool_calls += nested_tool_calls;
390 total_input_tokens = total_input_tokens.saturating_add(subagent_input_tokens);
391 total_output_tokens = total_output_tokens.saturating_add(subagent_output_tokens);
392 total_tokens = total_tokens.saturating_add(subagent_total_tokens);
393 if call.function.name == "spawn_subagent" {
394 last_subagent = None;
395 }
396 if config.depth.is_subagent() && !blocked && call.function.name == "finish" {
400 if let Some(result) =
401 call.function.arguments.get("result").and_then(|v| v.as_str())
402 {
403 *finish_store.lock().unwrap_or_else(|e| e.into_inner()) =
404 Some(result.to_string());
405 }
406 }
407 if output.len() > MAX_TOOL_RESULT_BYTES {
408 let original_len = output.len();
409 let boundary = floor_char_boundary(&output, MAX_TOOL_RESULT_BYTES);
410 output.truncate(boundary);
411 output.push_str(&format!(
412 "\n... truncated after 50,000 chars; {} chars omitted",
413 original_len.saturating_sub(boundary)
414 ));
415 }
416 results.push(ToolResult {
417 id: call.id.clone(),
418 call_id: call.call_id.clone(),
419 content: OneOrMany::one(ToolResultContent::text(output)),
420 });
421 }
422 report_progress(
423 &config,
424 turn + 1,
425 total_tool_calls,
426 initial_subagent_count,
427 last_subagent.clone(),
428 );
429
430 if config.depth.is_subagent() {
431 if let Some(result) = finish_store
432 .lock()
433 .unwrap_or_else(|e| e.into_inner())
434 .take()
435 {
436 info!(
437 agent = %config.name,
438 turn,
439 response_input_tokens = response.usage.input_tokens,
440 response_output_tokens = response.usage.output_tokens,
441 response_total_tokens = response.usage.total_tokens,
442 total_input_tokens,
443 total_output_tokens,
444 total_tokens_so_far = total_tokens,
445 response_len = result.len(),
446 "subagent finished"
447 );
448 return Ok(AgentResult {
449 text: result,
450 turns: turn + 1,
451 tool_calls: total_tool_calls,
452 subagents_spawned: config.subagent_counter.load(Ordering::Relaxed)
453 - initial_subagent_count,
454 total_input_tokens,
455 total_output_tokens,
456 total_tokens,
457 });
458 }
459 }
460
461 if should_terminate {
462 info!(
463 agent = %config.name,
464 turn,
465 total_tool_calls,
466 total_input_tokens,
467 total_output_tokens,
468 total_tokens,
469 "terminal tool called"
470 );
471 return Ok(AgentResult {
472 text: String::new(),
473 turns: turn + 1,
474 tool_calls: total_tool_calls,
475 subagents_spawned: config.subagent_counter.load(Ordering::Relaxed)
476 - initial_subagent_count,
477 total_input_tokens,
478 total_output_tokens,
479 total_tokens,
480 });
481 }
482
483 let tool_message = Message::User {
484 content: OneOrMany::many(results.into_iter().map(UserContent::ToolResult))
485 .expect("tool results must not be empty"),
486 };
487
488 history.push(tool_message.clone());
489
490 if consecutive_blocked_count >= MAX_CONSECUTIVE_BLOCKED_TOOL_CALLS && !is_final_turn {
491 warn!(
492 agent = %config.name,
493 turn,
494 consecutive_blocked_count,
495 "forcing compaction to break tool-call cycle"
496 );
497 let usage = conversation_usage.usage();
498 let compaction = compact_history(
499 &config.llm_semaphore,
500 Arc::clone(&config.client),
501 &config.model,
502 &effective_system_prompt,
503 &mut history,
504 &mut prompt,
505 turn + 1,
506 usage,
507 )
508 .await?;
509 if let Some(ref c) = compaction {
510 total_input_tokens = total_input_tokens.saturating_add(c.usage.input_tokens);
511 total_output_tokens = total_output_tokens.saturating_add(c.usage.output_tokens);
512 total_tokens = total_tokens.saturating_add(c.usage.total_tokens);
513 }
514 conversation_usage.reset();
515 log_compaction(&config, turn, "cycle_break", compaction.as_ref()).await;
516 let cycle_break_msg = Message::user(
517 "Note: you were stuck in a repetitive tool-call loop. \
518 Avoid repeating the same tool calls. Try a different approach."
519 .to_string(),
520 );
521 if let Some(last) = history.last_mut() {
522 *last = cycle_break_msg.clone();
523 }
524 prompt = cycle_break_msg;
525 tool_call_history.clear();
526 consecutive_blocked_count = 0;
527 continue;
528 }
529 prompt = tool_message;
530 } else {
531 tool_call_history.clear();
532 let text = response.text();
533 report_progress(
534 &config,
535 turn + 1,
536 total_tool_calls,
537 initial_subagent_count,
538 last_subagent.clone(),
539 );
540 if text.is_empty() {
541 if let Some(nudge) = &config.empty_response_nudge {
542 empty_response_count += 1;
543 if empty_response_count <= config.max_empty_responses && !is_final_turn {
544 let nudge = Message::user(nudge.clone());
545 history.push(nudge.clone());
546 prompt = nudge;
547 continue;
548 }
549 }
550 eyre::bail!("empty response from model (no text, no tool calls)");
551 }
552 if config.depth.is_subagent() {
553 eyre::bail!("subagent returned text without calling finish")
554 }
555 info!(
556 agent = %config.name,
557 turn,
558 response_input_tokens = response.usage.input_tokens,
559 response_output_tokens = response.usage.output_tokens,
560 response_total_tokens = response.usage.total_tokens,
561 total_input_tokens,
562 total_output_tokens,
563 total_tokens_so_far = total_tokens,
564 response_len = text.len(),
565 "finished"
566 );
567 return Ok(AgentResult {
568 text,
569 turns: turn + 1,
570 tool_calls: total_tool_calls,
571 subagents_spawned: config.subagent_counter.load(Ordering::Relaxed)
572 - initial_subagent_count,
573 total_input_tokens,
574 total_output_tokens,
575 total_tokens,
576 });
577 }
578 }
579
580 if config.depth.is_subagent() {
581 eyre::bail!(
582 "subagent exhausted {} turns without calling finish",
583 config.max_turns
584 );
585 }
586
587 eyre::bail!(
588 "agent exhausted {} turns without producing a final answer after wrap-up prompt",
589 config.max_turns
590 )
591}
592
593fn report_progress(
594 config: &AgentConfig,
595 turns: usize,
596 tool_calls: usize,
597 initial_subagent_count: usize,
598 last_subagent: Option<String>,
599) {
600 if let Some(progress) = &config.progress {
601 progress(AgentProgress {
602 turns,
603 tool_calls,
604 subagents_spawned: config.subagent_counter.load(Ordering::Relaxed)
605 - initial_subagent_count,
606 last_subagent,
607 });
608 }
609}
610
611pub fn add_spawn_subagent_tool(tools_map: &mut HashMap<String, Arc<dyn Tool>>) {
612 tools_map.insert("spawn_subagent".to_string(), Arc::new(SpawnSubagentTool));
613}
614
615struct SpawnSubagentTool;
616
617impl Tool for SpawnSubagentTool {
618 fn name(&self) -> String {
619 "spawn_subagent".to_string()
620 }
621
622 fn definition(&self) -> rig_core::completion::ToolDefinition {
623 rig_core::completion::ToolDefinition {
624 name: "spawn_subagent".to_string(),
625 description:
626 "Delegate a complex multi-step investigation to a subagent. Only use when the task requires several tool calls (e.g. tracing logic across multiple files). Do NOT use for single file reads or simple lookups — call those tools directly instead.
627
628 Example of correct usage:
629 - Trace the usage of X across the codebase to gather evidence about how it's used in different contexts, report the findings that are relevant to performance.
630 - Verify if input of X is always sanitized.
631 - Explore the feature engineering code to find potential sources of data leakage, and report any suspicious patterns you find.
632
633 Example of incorrect usage:
634 - Read file X at lines 100-150 to check if function Y is called (too simple, should call file-reading tool directly).
635 - Find all the usages of function Y across the codebase (use grep instead);
636 - Review all the changes from the security, performance, and correctness perspective (too complex and underspecified, should break down into multiple sub-tasks).".to_string(),
637 parameters: json!({
638 "type": "object",
639 "properties": {
640 "task": {
641 "type": "string",
642 "description": "A compact self-contained task for the subagent"
643 }
644 },
645 "required": ["task"],
646 "additionalProperties": false
647 }),
648 }
649 }
650
651 fn call(
652 &self,
653 _args: Value,
654 _work_dir: PathBuf,
655 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
656 Box::pin(async { unreachable!("spawn_subagent is handled internally") })
657 }
658}
659
660fn prepare_subagent(
661 parent_config: &AgentConfig,
662 args: &Value,
663 parent_turns: usize,
664 parent_tool_calls: usize,
665 initial_subagent_count: usize,
666) -> Result<PreparedSubagent> {
667 let task = match args.get("task").and_then(|value| value.as_str()) {
668 Some(task) if !task.trim().is_empty() => task.to_string(),
669 _ => eyre::bail!("missing task"),
670 };
671
672 let subagent_id = parent_config
673 .subagent_counter
674 .fetch_add(1, Ordering::Relaxed)
675 + 1;
676 let spawned_agent = format!("subagent-{subagent_id}");
677 report_progress(
678 parent_config,
679 parent_turns,
680 parent_tool_calls,
681 initial_subagent_count,
682 Some(first_line(&task)),
683 );
684 let subagent_level = parent_config.depth.level() + 1;
685 let subagent_config = AgentConfig {
686 name: format!("{}/subagent-{subagent_id}", parent_config.name),
687 session_agent: spawned_agent.clone(),
688 model: parent_config.model.clone(),
689 max_turns: parent_config.max_turns,
690 compact_threshold: parent_config.compact_threshold,
691 system_prompt: parent_config
692 .subagent_system_prompt
693 .clone()
694 .unwrap_or_else(|| subagent_system_prompt().to_string()),
695 subagent_system_prompt: parent_config.subagent_system_prompt.clone(),
696 client: Arc::clone(&parent_config.client),
697 depth: AgentDepth::Subagent {
698 level: subagent_level,
699 },
700 terminal_tools: Vec::new(),
701 empty_response_nudge: None,
702 max_empty_responses: 0,
703 subagent_counter: Arc::clone(&parent_config.subagent_counter),
704 llm_semaphore: Arc::clone(&parent_config.llm_semaphore),
705 progress: None,
706 project_context: parent_config.project_context.clone(),
707 session_writer: parent_config.session_writer.clone(),
708 };
709
710 Ok(PreparedSubagent {
711 task,
712 spawned_agent,
713 config: subagent_config,
714 })
715}
716
717async fn run_subagent(
718 prepared: PreparedSubagent,
719 tools_map: &HashMap<String, Arc<dyn Tool>>,
720 work_dir: &Path,
721) -> SubagentOutcome {
722 let PreparedSubagent {
723 task,
724 spawned_agent,
725 config,
726 } = prepared;
727
728 match Box::pin(run_agent(config, &task, tools_map, work_dir)).await {
729 Ok(result) => SubagentOutcome {
730 output: result.text,
731 tool_calls: result.tool_calls,
732 spawned_agent: Some(spawned_agent),
733 input_tokens: result.total_input_tokens,
734 output_tokens: result.total_output_tokens,
735 total_tokens: result.total_tokens,
736 },
737 Err(err) => SubagentOutcome {
738 output: format!("Error: {err}"),
739 tool_calls: 0,
740 spawned_agent: Some(spawned_agent),
741 input_tokens: 0,
742 output_tokens: 0,
743 total_tokens: 0,
744 },
745 }
746}
747
748fn first_line(s: &str) -> String {
749 s.lines().next().unwrap_or(s).to_string()
750}
751
752fn detect_tool_call_cycle(history: &VecDeque<String>) -> usize {
755 let h: Vec<&str> = history.iter().map(String::as_str).collect();
756 let n = h.len();
757 for period in 1..=3 {
758 let reps = if period == 1 {
759 MAX_CONSECUTIVE_IDENTICAL_TOOL_CALLS
760 } else {
761 MAX_CYCLE_REPETITIONS
762 };
763 let needed = period * reps;
764 if n < needed {
765 continue;
766 }
767 let start = n - needed;
768 let pattern = &h[start..start + period];
769 if h[start..]
770 .chunks(period)
771 .take(reps)
772 .all(|chunk| chunk == pattern)
773 {
774 return period;
775 }
776 }
777 0
778}
779
780async fn execute_tool_call(
781 ctx: ToolCallContext<'_>,
782 tool_name: &str,
783 args: Value,
784 cycle_len: usize,
785) -> Result<ToolCallOutcome> {
786 if cycle_len > 0 {
787 warn!(
788 agent = %ctx.config.name,
789 tool = %tool_name,
790 args = %args,
791 turn = ctx.turn,
792 cycle_len,
793 "blocking cyclic tool call"
794 );
795 let msg = if cycle_len == 1 {
796 format!(
797 "Warning: repeated identical tool call blocked for {tool_name}. Think twice; try changing the arguments or using a different tool."
798 )
799 } else {
800 format!(
801 "Warning: tool call cycle of period {cycle_len} detected (e.g. A→B→A→B). You are looping without making progress. Try a different approach or tool."
802 )
803 };
804 let outcome = ToolCallOutcome {
805 output: msg,
806 nested_tool_calls: 0,
807 repeated_tool_call_blocked: true,
808 status: "blocked_cycle",
809 spawned_agent: None,
810 subagent_input_tokens: 0,
811 subagent_output_tokens: 0,
812 subagent_total_tokens: 0,
813 };
814 log_tool_call(
815 ctx.config,
816 ctx.turn + 1,
817 tool_name,
818 &args,
819 outcome.status,
820 outcome.spawned_agent.as_deref(),
821 None,
822 )
823 .await;
824 return Ok(outcome);
825 }
826
827 if tool_name == "spawn_subagent" {
828 if !ctx.config.depth.can_spawn_subagent()
829 || !ctx.runtime_tools.contains_key("spawn_subagent")
830 {
831 let outcome = ToolCallOutcome {
832 output: "Error: subagent depth limit reached; cannot spawn another subagent"
833 .to_string(),
834 nested_tool_calls: 0,
835 repeated_tool_call_blocked: false,
836 status: "error",
837 spawned_agent: None,
838 subagent_input_tokens: 0,
839 subagent_output_tokens: 0,
840 subagent_total_tokens: 0,
841 };
842 log_tool_call(
843 ctx.config,
844 ctx.turn + 1,
845 tool_name,
846 &args,
847 outcome.status,
848 outcome.spawned_agent.as_deref(),
849 None,
850 )
851 .await;
852 return Ok(outcome);
853 }
854 info!(agent = %ctx.config.name, turn = ctx.turn, "spawning subagent");
855 let prepared = match prepare_subagent(
856 ctx.config,
857 &args,
858 ctx.current_turns,
859 ctx.total_tool_calls,
860 ctx.initial_subagent_count,
861 ) {
862 Ok(prepared) => prepared,
863 Err(err) => {
864 let outcome = ToolCallOutcome {
865 output: format!("Error: {err}"),
866 nested_tool_calls: 0,
867 repeated_tool_call_blocked: false,
868 status: "error",
869 spawned_agent: None,
870 subagent_input_tokens: 0,
871 subagent_output_tokens: 0,
872 subagent_total_tokens: 0,
873 };
874 log_tool_call(
875 ctx.config,
876 ctx.turn + 1,
877 tool_name,
878 &args,
879 outcome.status,
880 outcome.spawned_agent.as_deref(),
881 None,
882 )
883 .await;
884 return Ok(outcome);
885 }
886 };
887 log_tool_call(
888 ctx.config,
889 ctx.turn + 1,
890 tool_name,
891 &args,
892 "started",
893 Some(&prepared.spawned_agent),
894 None,
895 )
896 .await;
897 let sub = run_subagent(prepared, ctx.tools_map, ctx.work_dir).await;
898 let status = if sub.output.starts_with("Error:") {
899 "error"
900 } else {
901 "ok"
902 };
903 let outcome = ToolCallOutcome {
904 output: sub.output,
905 nested_tool_calls: sub.tool_calls,
906 repeated_tool_call_blocked: false,
907 status,
908 spawned_agent: sub.spawned_agent,
909 subagent_input_tokens: sub.input_tokens,
910 subagent_output_tokens: sub.output_tokens,
911 subagent_total_tokens: sub.total_tokens,
912 };
913 return Ok(outcome);
914 }
915
916 let logged_args = args.clone();
917 let outcome = match ctx.runtime_tools.get(tool_name) {
918 Some(tool) => match tool.call(args, ctx.work_dir.to_path_buf()).await {
919 Ok(output) => ToolCallOutcome {
920 output,
921 nested_tool_calls: 0,
922 repeated_tool_call_blocked: false,
923 status: "ok",
924 spawned_agent: None,
925 subagent_input_tokens: 0,
926 subagent_output_tokens: 0,
927 subagent_total_tokens: 0,
928 },
929 Err(err) => {
930 debug!(agent = %ctx.config.name, tool = %tool_name, error = %err, "tool error");
931 ToolCallOutcome {
932 output: format!("Error: {err}"),
933 nested_tool_calls: 0,
934 repeated_tool_call_blocked: false,
935 status: "error",
936 spawned_agent: None,
937 subagent_input_tokens: 0,
938 subagent_output_tokens: 0,
939 subagent_total_tokens: 0,
940 }
941 }
942 },
943 None => {
944 let msg = format!("Error: unknown tool '{tool_name}'");
945 debug!(agent = %ctx.config.name, tool = %tool_name, "unknown tool");
946 ToolCallOutcome {
947 output: msg,
948 nested_tool_calls: 0,
949 repeated_tool_call_blocked: false,
950 status: "error",
951 spawned_agent: None,
952 subagent_input_tokens: 0,
953 subagent_output_tokens: 0,
954 subagent_total_tokens: 0,
955 }
956 }
957 };
958
959 log_tool_call(
960 ctx.config,
961 ctx.turn + 1,
962 tool_name,
963 &logged_args,
964 outcome.status,
965 outcome.spawned_agent.as_deref(),
966 None,
967 )
968 .await;
969
970 Ok(outcome)
971}
972
973async fn log_tool_call(
974 config: &AgentConfig,
975 turn: usize,
976 tool_name: &str,
977 args: &Value,
978 status: &'static str,
979 spawned_agent: Option<&str>,
980 result: Option<&str>,
981) {
982 let Some(session_writer) = config.session_writer.as_ref() else {
983 return;
984 };
985
986 let record = ToolCallRecord {
987 ts_unix_ms: now_unix_ms(),
988 agent: config.session_agent.clone(),
989 depth: config.depth.level(),
990 turn,
991 tool: tool_name.to_string(),
992 args: args.clone(),
993 status: status.to_string(),
994 spawned_agent: spawned_agent.map(str::to_string),
995 result: result.map(str::to_string),
996 };
997 if let Err(err) = session_writer.append_tool_call(&record).await {
998 warn!(tool = %tool_name, error = %err, "failed to write trajectory log");
999 }
1000}
1001
1002async fn log_compaction(
1003 config: &AgentConfig,
1004 turn: usize,
1005 reason: &'static str,
1006 outcome: Option<&CompactionOutcome>,
1007) {
1008 let result = outcome.map(|value| value.summary.as_str());
1009 log_tool_call(
1010 config,
1011 turn,
1012 "compact",
1013 &json!({ "reason": reason }),
1014 "ok",
1015 None,
1016 result,
1017 )
1018 .await;
1019}