Fully Automated - 100% Backpressure - Pipeline runner 🏃 for AI workflows. 🚀

Commit 4f5bd755

4f5bd755bb96Merged

Scott Nixon <[email protected]> · 5 months ago · 35 files · +17 added · ~18 modified

Description

Merge pull request #6 from citadelgrad/reckoner/feat/reck-5e6ccd6b-implement-all-child-tasks-of

refactor: extract test code into separate *_tests.rs files (reck lint fix)

Details

Commit
4f5bd755bb96
Parent
2cdb9b65dc91
Merge parent
ac762bac0910

crates/attractor-agent/src/lib.rsmodifiedView file

@@ -16,7 +16,9 @@
1616
1717 use std::collections::VecDeque;
1818
19-use attractor_llm::{ContentPart, Message, Request, ToolCallResult};
19+use attractor_llm::{
20+ ContentPart, Message, Request, ToolCallResult,
21+};
2022 use attractor_tools::{ExecutionEnvironment, ToolRegistry};
2123 use attractor_types::AttractorError;
2224
@@ -39,8 +41,6 @@
3941 pub enable_loop_detection: bool,
4042 /// Window size for loop detection (consecutive identical calls).
4143 pub loop_detection_window: usize,
42- /// Fidelity mode for managing conversation context.
43- pub fidelity_mode: FidelityMode,
4444 }
4545
4646 impl Default for SessionConfig {
@@ -53,7 +53,6 @@
5353 default_command_timeout_ms: 10_000,
5454 enable_loop_detection: true,
5555 loop_detection_window: 10,
56- fidelity_mode: FidelityMode::default(),
5756 }
5857 }
5958 }
@@ -126,8 +125,6 @@
126125 followup_queue: VecDeque<String>,
127126 /// Running count of user turns (for max_turns enforcement).
128127 user_turn_count: usize,
129- /// Loop detector, active when `enable_loop_detection` is true.
130- loop_detector: Option<LoopDetector>,
131128 }
132129
133130 impl AgentSession {
@@ -140,11 +137,6 @@
140137 ) -> Self {
141138 let id = uuid::Uuid::new_v4().to_string();
142139 tracing::info!(session_id = %id, model = %config.model, "Agent session created");
143- let loop_detector = if config.enable_loop_detection {
144- Some(LoopDetector::new(config.loop_detection_window))
145- } else {
146- None
147- };
148140 Self {
149141 id,
150142 llm_client,
@@ -156,7 +148,6 @@
156148 steering_queue: Vec::new(),
157149 followup_queue: VecDeque::new(),
158150 user_turn_count: 0,
159- loop_detector,
160151 }
161152 }
162153
@@ -177,15 +168,13 @@
177168
178169 /// Push a steering message to be injected at the next tool round boundary.
179170 pub fn steer(&mut self, message: String) {
180- let preview: String = message.chars().take(80).collect();
181- tracing::debug!("Steering message queued: {}", preview);
171+ tracing::debug!("Steering message queued: {}", &message[..message.len().min(80)]);
182172 self.steering_queue.push(message);
183173 }
184174
185175 /// Push a follow-up input to be processed after the current input completes.
186176 pub fn follow_up(&mut self, message: String) {
187- let preview: String = message.chars().take(80).collect();
188- tracing::debug!("Follow-up queued: {}", preview);
177+ tracing::debug!("Follow-up queued: {}", &message[..message.len().min(80)]);
189178 self.followup_queue.push_back(message);
190179 }
191180
@@ -208,13 +197,7 @@
208197 let mut current_input = user_input.to_string();
209198
210199 loop {
211- let result = match self.process_single_input(&current_input).await {
212- Ok(r) => r,
213- Err(e) => {
214- self.state = SessionState::Idle;
215- return Err(e);
216- }
217- };
200+ let result = self.process_single_input(&current_input).await?;
218201
219202 // Check for follow-up messages
220203 if let Some(followup) = self.followup_queue.pop_front() {
@@ -282,46 +265,17 @@
282265 break;
283266 }
284267
285- // Execute each tool call
286- let results = self.execute_tool_calls(&response.tool_calls).await;
287-
288- // Check if this is the last allowed round (after executing tools
289- // so results are not silently dropped from history)
268+ // Check if this is the last allowed round
290269 if round + 1 >= self.config.max_tool_rounds {
291270 tracing::info!(
292271 max_rounds = self.config.max_tool_rounds,
293272 "Max tool rounds reached, stopping loop"
294273 );
295- self.history.push(Turn::ToolResults { results });
296274 break;
297275 }
298276
299- // Check for tool-call loops before appending results
300- if let Some(ref mut detector) = self.loop_detector {
301- // Check each tool call; if any triggers a loop, inject steering and break
302- let mut loop_detected = false;
303- let mut loop_tool_name = String::new();
304- for tc in &response.tool_calls {
305- if detector.record_and_check(&tc.name, &tc.arguments) {
306- loop_detected = true;
307- loop_tool_name = tc.name.clone();
308- break;
309- }
310- }
311- if loop_detected {
312- let window = self.config.loop_detection_window;
313- let msg = SteeringInjector::loop_detected_message(&loop_tool_name, window);
314- tracing::warn!(
315- tool = %loop_tool_name,
316- window,
317- "Loop detected — injecting steering and breaking tool loop"
318- );
319- detector.reset();
320- self.history.push(Turn::ToolResults { results });
321- self.history.push(Turn::Steering { content: msg });
322- break;
323- }
324- }
277+ // Execute each tool call
278+ let results = self.execute_tool_calls(&response.tool_calls).await;
325279
326280 // Append tool results turn
327281 self.history.push(Turn::ToolResults { results });
@@ -392,9 +346,6 @@
392346 }
393347 }
394348
395- // Apply fidelity mode to trim/compact the message list before sending
396- let messages = apply_fidelity(&messages, &self.config.fidelity_mode);
397-
398349 // Convert tool definitions from tools crate to LLM crate format
399350 let tools: Vec<attractor_llm::ToolDefinition> = self
400351 .tool_registry
@@ -429,30 +380,27 @@
429380 tracing::debug!(tool = %tc.name, id = %tc.id, "Executing tool call");
430381
431382 let (content, is_error) = match self.tool_registry.get(&tc.name) {
432- Some(tool) => match tool.execute(tc.arguments.clone(), self.env.as_ref()).await {
433- Ok(output) => {
434- let truncated = if output.len() > MAX_TOOL_OUTPUT_LEN {
435- // Find a char-boundary-safe split point
436- let mut split = MAX_TOOL_OUTPUT_LEN;
437- while split > 0 && !output.is_char_boundary(split) {
438- split -= 1;
439- }
440- let mut t = output[..split].to_string();
441- t.push_str(&format!(
442- "\n\n[WARNING: Output truncated. {} bytes removed.]",
443- output.len() - split
444- ));
445- t
446- } else {
447- output
448- };
449- (truncated, false)
383+ Some(tool) => {
384+ match tool.execute(tc.arguments.clone(), self.env.as_ref()).await {
385+ Ok(output) => {
386+ let truncated = if output.len() > MAX_TOOL_OUTPUT_LEN {
387+ let mut t = output[..MAX_TOOL_OUTPUT_LEN].to_string();
388+ t.push_str(&format!(
389+ "\n\n[WARNING: Output truncated. {} characters removed.]",
390+ output.len() - MAX_TOOL_OUTPUT_LEN
391+ ));
392+ t
393+ } else {
394+ output
395+ };
396+ (truncated, false)
397+ }
398+ Err(e) => {
399+ tracing::debug!(tool = %tc.name, error = %e, "Tool execution failed");
400+ (format!("Error: {}", e), true)
401+ }
450402 }
451- Err(e) => {
452- tracing::debug!(tool = %tc.name, error = %e, "Tool execution failed");
453- (format!("Error: {}", e), true)
454- }
455- },
403+ }
456404 None => {
457405 let msg = format!("Unknown tool: {}", tc.name);
458406 tracing::debug!("{}", msg);
@@ -477,407 +425,5 @@
477425 // ---------------------------------------------------------------------------
478426
479427 #[cfg(test)]
480-mod tests {
481- use super::*;
482- use crate::test_utils::{make_client, EchoTool, MockEnv, SequenceMockProvider};
483- use async_trait::async_trait;
484- use attractor_llm::{FinishReason, Response, Usage};
485- use attractor_tools::{Tool, ToolDefinition as ToolsToolDef};
486-
487- // -----------------------------------------------------------------------
488- // Test 1: Session creation with config
489- // -----------------------------------------------------------------------
490-
491- #[test]
492- fn session_creation_with_config() {
493- let client = make_client(SequenceMockProvider::single_text("hello"));
494- let registry = ToolRegistry::new();
495- let env = Box::new(MockEnv);
496- let config = SessionConfig {
497- model: "test-model".to_string(),
498- system_prompt: "You are helpful.".to_string(),
499- max_turns: 10,
500- max_tool_rounds: 50,
501- ..Default::default()
502- };
503-
504- let session = AgentSession::new(client, registry, env, config);
505-
506- assert!(!session.id().is_empty());
507- assert_eq!(*session.state(), SessionState::Idle);
508- assert!(session.history().is_empty());
509- }
510-
511- // -----------------------------------------------------------------------
512- // Test 2: Process input with no tools -> returns LLM text
513- // -----------------------------------------------------------------------
514-
515- #[tokio::test]
516- async fn process_input_no_tools_returns_text() {
517- let provider = SequenceMockProvider::single_text("Hello, world!");
518- let client = make_client(provider);
519- let registry = ToolRegistry::new();
520- let env = Box::new(MockEnv);
521- let config = SessionConfig::default();
522-
523- let mut session = AgentSession::new(client, registry, env, config);
524- let result = session.process_input("Hi there").await.unwrap();
525-
526- assert_eq!(result, "Hello, world!");
527- assert_eq!(session.history().len(), 2); // User + Assistant
528- assert!(matches!(&session.history()[0], Turn::User { content } if content == "Hi there"));
529- assert!(
530- matches!(&session.history()[1], Turn::Assistant { content, tool_calls } if content == "Hello, world!" && tool_calls.is_empty())
531- );
532- }
533-
534- // -----------------------------------------------------------------------
535- // Test 3: Process input with tool call -> executes tool and returns
536- // -----------------------------------------------------------------------
537-
538- #[tokio::test]
539- async fn process_input_with_tool_call() {
540- // First response: tool call. Second response: final text.
541- let responses = vec![
542- Response {
543- id: "resp-1".into(),
544- text: String::new(),
545- tool_calls: vec![ToolCallResult {
546- id: "tc-1".into(),
547- name: "echo".into(),
548- arguments: serde_json::json!({"text": "ping"}),
549- }],
550- reasoning: None,
551- usage: Usage::default(),
552- model: "mock-model".into(),
553- finish_reason: FinishReason::ToolUse,
554- },
555- Response {
556- id: "resp-2".into(),
557- text: "The echo returned: ping".into(),
558- tool_calls: vec![],
559- reasoning: None,
560- usage: Usage::default(),
561- model: "mock-model".into(),
562- finish_reason: FinishReason::EndTurn,
563- },
564- ];
565-
566- let client = make_client(SequenceMockProvider::new(responses));
567- let mut registry = ToolRegistry::new();
568- registry.register(EchoTool);
569- let env = Box::new(MockEnv);
570- let config = SessionConfig::default();
571-
572- let mut session = AgentSession::new(client, registry, env, config);
573- let result = session.process_input("Echo ping for me").await.unwrap();
574-
575- assert_eq!(result, "The echo returned: ping");
576-
577- // History: User, Assistant(tool_call), ToolResults, Assistant(final)
578- assert_eq!(session.history().len(), 4);
579- assert!(matches!(&session.history()[0], Turn::User { .. }));
580- assert!(matches!(
581- &session.history()[1],
582- Turn::Assistant { tool_calls, .. } if tool_calls.len() == 1
583- ));
584- assert!(
585- matches!(&session.history()[2], Turn::ToolResults { results } if results.len() == 1 && !results[0].is_error && results[0].content == "ping")
586- );
587- assert!(
588- matches!(&session.history()[3], Turn::Assistant { content, .. } if content == "The echo returned: ping")
589- );
590- }
591-
592- // -----------------------------------------------------------------------
593- // Test 4: Steering queue drained between rounds
594- // -----------------------------------------------------------------------
595-
596- #[tokio::test]
597- async fn steering_queue_drained_between_rounds() {
598- // Response sequence: tool call -> final text
599- let responses = vec![
600- Response {
601- id: "resp-1".into(),
602- text: String::new(),
603- tool_calls: vec![ToolCallResult {
604- id: "tc-1".into(),
605- name: "echo".into(),
606- arguments: serde_json::json!({"text": "hello"}),
607- }],
608- reasoning: None,
609- usage: Usage::default(),
610- model: "mock-model".into(),
611- finish_reason: FinishReason::ToolUse,
612- },
613- Response {
614- id: "resp-2".into(),
615- text: "Done".into(),
616- tool_calls: vec![],
617- reasoning: None,
618- usage: Usage::default(),
619- model: "mock-model".into(),
620- finish_reason: FinishReason::EndTurn,
621- },
622- ];
623-
624- let client = make_client(SequenceMockProvider::new(responses));
625- let mut registry = ToolRegistry::new();
626- registry.register(EchoTool);
627- let env = Box::new(MockEnv);
628- let config = SessionConfig::default();
629-
630- let mut session = AgentSession::new(client, registry, env, config);
631-
632- // Queue steering before processing
633- session.steer("Focus on security.".to_string());
634-
635- let result = session.process_input("Do something").await.unwrap();
636- assert_eq!(result, "Done");
637-
638- // Verify steering turns appear in history.
639- // History should be: User, Steering("Focus on security."), Assistant(tool), ToolResults, Assistant(final)
640- let steering_count = session
641- .history()
642- .iter()
643- .filter(|t| matches!(t, Turn::Steering { .. }))
644- .count();
645- assert!(
646- steering_count >= 1,
647- "Expected at least 1 steering turn, found {}",
648- steering_count
649- );
650-
651- // The first steering should be right after the user turn (drained before loop starts)
652- assert!(matches!(
653- &session.history()[1],
654- Turn::Steering { content } if content == "Focus on security."
655- ));
656- }
657-
658- // -----------------------------------------------------------------------
659- // Test 5: Max tool rounds limit stops loop
660- // -----------------------------------------------------------------------
661-
662- #[tokio::test]
663- async fn max_tool_rounds_stops_loop() {
664- // Provider always returns a tool call, never stops on its own.
665- let infinite_tool_calls: Vec<Response> = (0..10)
666- .map(|i| Response {
667- id: format!("resp-{}", i),
668- text: format!("round {}", i),
669- tool_calls: vec![ToolCallResult {
670- id: format!("tc-{}", i),
671- name: "echo".into(),
672- arguments: serde_json::json!({"text": "loop"}),
673- }],
674- reasoning: None,
675- usage: Usage::default(),
676- model: "mock-model".into(),
677- finish_reason: FinishReason::ToolUse,
678- })
679- .collect();
680-
681- let client = make_client(SequenceMockProvider::new(infinite_tool_calls));
682- let mut registry = ToolRegistry::new();
683- registry.register(EchoTool);
684- let env = Box::new(MockEnv);
685- let config = SessionConfig {
686- max_tool_rounds: 3,
687- ..Default::default()
688- };
689-
690- let mut session = AgentSession::new(client, registry, env, config);
691- let result = session.process_input("Loop forever").await.unwrap();
692-
693- // Should have stopped after 3 rounds. The last response's text is returned.
694- assert_eq!(result, "round 2"); // 0-indexed: rounds 0, 1, 2
695-
696- // Count assistant turns to verify we only had 3 LLM calls
697- let assistant_count = session
698- .history()
699- .iter()
700- .filter(|t| matches!(t, Turn::Assistant { .. }))
701- .count();
702- assert_eq!(assistant_count, 3);
703- }
704-
705- // -----------------------------------------------------------------------
706- // Test 6: Unknown tool returns error result
707- // -----------------------------------------------------------------------
708-
709- #[tokio::test]
710- async fn unknown_tool_returns_error_result() {
711- let responses = vec![
712- Response {
713- id: "resp-1".into(),
714- text: String::new(),
715- tool_calls: vec![ToolCallResult {
716- id: "tc-1".into(),
717- name: "nonexistent_tool".into(),
718- arguments: serde_json::json!({}),
719- }],
720- reasoning: None,
721- usage: Usage::default(),
722- model: "mock-model".into(),
723- finish_reason: FinishReason::ToolUse,
724- },
725- Response {
726- id: "resp-2".into(),
727- text: "Tool not found, sorry.".into(),
728- tool_calls: vec![],
729- reasoning: None,
730- usage: Usage::default(),
731- model: "mock-model".into(),
732- finish_reason: FinishReason::EndTurn,
733- },
734- ];
735-
736- let client = make_client(SequenceMockProvider::new(responses));
737- let registry = ToolRegistry::new(); // No tools registered
738- let env = Box::new(MockEnv);
739- let config = SessionConfig::default();
740-
741- let mut session = AgentSession::new(client, registry, env, config);
742- let result = session.process_input("Use nonexistent tool").await.unwrap();
743-
744- assert_eq!(result, "Tool not found, sorry.");
745-
746- // Check the tool result was an error
747- let tool_results = session.history().iter().find_map(|t| {
748- if let Turn::ToolResults { results } = t {
749- Some(results)
750- } else {
751- None
752- }
753- });
754- let results = tool_results.expect("Expected ToolResults turn");
755- assert_eq!(results.len(), 1);
756- assert!(results[0].is_error);
757- assert!(results[0].content.contains("Unknown tool"));
758- }
759-
760- // -----------------------------------------------------------------------
761- // Test 7: Turn limit enforcement
762- // -----------------------------------------------------------------------
763-
764- #[tokio::test]
765- async fn turn_limit_enforcement() {
766- let provider = SequenceMockProvider::new(vec![
767- Response {
768- id: "r1".into(),
769- text: "first".into(),
770- tool_calls: vec![],
771- reasoning: None,
772- usage: Usage::default(),
773- model: "m".into(),
774- finish_reason: FinishReason::EndTurn,
775- },
776- Response {
777- id: "r2".into(),
778- text: "second".into(),
779- tool_calls: vec![],
780- reasoning: None,
781- usage: Usage::default(),
782- model: "m".into(),
783- finish_reason: FinishReason::EndTurn,
784- },
785- ]);
786- let client = make_client(provider);
787- let registry = ToolRegistry::new();
788- let env = Box::new(MockEnv);
789- let config = SessionConfig {
790- max_turns: 1,
791- ..Default::default()
792- };
793-
794- let mut session = AgentSession::new(client, registry, env, config);
795-
796- // First turn should work
797- let r1 = session.process_input("first").await.unwrap();
798- assert_eq!(r1, "first");
799-
800- // Second turn should fail with TurnLimitReached
801- let r2 = session.process_input("second").await;
802- assert!(r2.is_err());
803- assert!(matches!(
804- r2.unwrap_err(),
805- AttractorError::TurnLimitReached { .. }
806- ));
807- }
808-
809- // -----------------------------------------------------------------------
810- // Test 8: Tool output truncation
811- // -----------------------------------------------------------------------
812-
813- #[tokio::test]
814- async fn tool_output_truncation() {
815- // Create a tool that returns a very long output
816- struct BigOutputTool;
817-
818- #[async_trait]
819- impl Tool for BigOutputTool {
820- fn definition(&self) -> ToolsToolDef {
821- ToolsToolDef {
822- name: "big_output".to_string(),
823- description: "Returns a large output".to_string(),
824- parameters: serde_json::json!({"type": "object"}),
825- }
826- }
827- async fn execute(
828- &self,
829- _arguments: serde_json::Value,
830- _env: &dyn ExecutionEnvironment,
831- ) -> attractor_types::Result<String> {
832- Ok("x".repeat(50_000))
833- }
834- }
835-
836- let responses = vec![
837- Response {
838- id: "r1".into(),
839- text: String::new(),
840- tool_calls: vec![ToolCallResult {
841- id: "tc-1".into(),
842- name: "big_output".into(),
843- arguments: serde_json::json!({}),
844- }],
845- reasoning: None,
846- usage: Usage::default(),
847- model: "m".into(),
848- finish_reason: FinishReason::ToolUse,
849- },
850- Response {
851- id: "r2".into(),
852- text: "Got it".into(),
853- tool_calls: vec![],
854- reasoning: None,
855- usage: Usage::default(),
856- model: "m".into(),
857- finish_reason: FinishReason::EndTurn,
858- },
859- ];
860-
861- let client = make_client(SequenceMockProvider::new(responses));
862- let mut registry = ToolRegistry::new();
863- registry.register(BigOutputTool);
864- let env = Box::new(MockEnv);
865- let config = SessionConfig::default();
866-
867- let mut session = AgentSession::new(client, registry, env, config);
868- let result = session.process_input("big output").await.unwrap();
869- assert_eq!(result, "Got it");
870-
871- // Verify the tool result was truncated
872- let tool_results = session.history().iter().find_map(|t| {
873- if let Turn::ToolResults { results } = t {
874- Some(results)
875- } else {
876- None
877- }
878- });
879- let results = tool_results.unwrap();
880- assert!(results[0].content.contains("[WARNING: Output truncated."));
881- assert!(results[0].content.contains("20000 bytes removed"));
882- }
883-}
428+#[path = "tests.rs"]
429+mod tests;