echo_agent 0.1.4

Production-grade AI Agent framework for Rust — ReAct engine, multi-agent, memory, streaming, MCP, IM channels, workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Agent configuration

use crate::agent::AgentCallback;
use crate::llm::ResponseFormat;
use crate::tools::ToolExecutionConfig;
use std::path::PathBuf;
use std::sync::Arc;

/// Agent role enum, determining its responsibility scope in a multi-agent system.
///
/// # Current usage
///
/// - `Orchestrator`: Used in `TaskExecutor::build_execute_fn` (`react/planning.rs`).
///   The orchestrator prioritizes dispatching tasks to registered SubAgents
///   rather than calling the LLM directly.
///   Suitable for the "leader" role in multi-agent collaboration scenarios.
///
/// - `Worker` (default): Executes tasks directly via LLM without dispatching to SubAgents.
///   Suitable for agents that independently perform specific tasks.
///
/// # Note
///
/// This role field currently **only** affects behavior in the TaskExecutor's execution logic.
/// It has no additional effect in other modules (ReactAgent, PlanExecute, etc.).
#[derive(Default, Debug, Clone, PartialEq)]
pub enum AgentRole {
    /// Orchestrator: responsible for task planning, allocation, and coordinating sub-agents; does not hold business tools.
    /// Prioritizes dispatching to SubAgents in TaskExecutor.
    Orchestrator,
    /// Worker (default): focuses on specific task execution, only carries business tools,
    /// does not hold task management/sub-agent scheduling capabilities. Executes tasks directly via LLM.
    #[default]
    Worker,
}

/// Agent runtime configuration
///
/// Configure parameters via builder chain calls, then pass to `ReactAgent::new`.
pub struct AgentConfig {
    pub(crate) model_name: String,
    pub(crate) system_prompt: String,
    pub(crate) agent_name: String,
    /// Maximum iteration rounds, prevents infinite loops
    pub(crate) max_iterations: usize,
    /// Tool allowlist (empty = no restriction, all registered tools can be called)
    pub(crate) allowed_tools: Vec<String>,
    pub(crate) role: AgentRole,
    /// Whether to allow registering and calling business tools (e.g., math, weather, etc.)
    pub(crate) enable_tool: bool,
    /// Whether to enable task planning capability (plan/create_task/update_task tools)
    pub(crate) enable_task: bool,
    /// Whether to enable human-in-loop tool
    pub(crate) enable_human_in_loop: bool,
    /// Whether to enable subagent dispatch tool (agent_tool)
    pub(crate) enable_subagent: bool,
    /// Context token limit; auto-triggers compression when exceeded (`usize::MAX` means no limit)
    pub(crate) token_limit: usize,
    pub(crate) callbacks: Vec<Arc<dyn AgentCallback>>,
    /// Maximum retry count after LLM call failure (0 = no retry, default 3)
    pub(crate) llm_max_retries: usize,
    /// LLM retry initial delay (ms), doubles with exponential backoff (default 500)
    pub(crate) llm_retry_delay_ms: u64,
    /// On tool execution failure, feed the error back to the LLM instead of failing the Agent directly (default true)
    pub(crate) tool_error_feedback: bool,
    /// Enable chain-of-thought (CoT) system prompt injection (default true).
    pub(crate) enable_cot: bool,
    /// Tool execution config: timeout, retry strategy, parallel concurrency
    pub(crate) tool_execution: ToolExecutionConfig,
    /// Whether to enable long-term memory Store (remember/recall/forget tools + automatic context injection)
    pub(crate) enable_memory: bool,
    /// Long-term memory Store file path (default `~/.echo-agent/store.json`)
    pub(crate) memory_path: String,
    /// Session identifier, used by Checkpointer to restore historical context of the same conversation across process restarts.
    pub(crate) session_id: Option<String>,
    /// Conversation identifier, used by ConversationStore to persist transcript/history projections.
    pub(crate) conversation_id: Option<String>,
    /// Checkpointer file path (default `~/.echo-agent/checkpoints.json`)
    pub(crate) checkpointer_path: String,
    /// Structured output format (None = default text)
    pub(crate) response_format: Option<ResponseFormat>,
    /// Maximum token count for a single tool output (None = no limit).
    /// Automatically truncated when exceeded, with a `[Output truncated, N tokens total]` hint appended.
    pub(crate) max_tool_output_tokens: Option<usize>,
    /// When available token ratio falls below this threshold, proactively trigger compression before think().
    /// Value range 0.0–1.0, default 0.2 (i.e., triggers when less than 20% remains).
    pub(crate) compress_threshold_ratio: f64,
    /// LLM temperature parameter (0.0–2.0, None means use model default)
    pub(crate) temperature: Option<f32>,
    /// Maximum generation token count (None means use model default)
    pub(crate) max_tokens: Option<u32>,
    /// Whether to automatically load project rules file (`.echo-agent/AGENT.md`), default true
    pub(crate) auto_project_rules: bool,
    /// Working directory (for searching project rules files), None means use current directory
    pub(crate) working_dir: Option<PathBuf>,
}

impl AgentConfig {
    /// Create a new Agent configuration
    ///
    /// # Parameters
    /// * `model_name` - LLM model name to use (corresponds to model identifier in config)
    /// * `agent_name` - Agent name, used for identification and logging
    /// * `system_prompt` - System prompt, defines the Agent's role and capabilities
    ///
    /// # Returns
    /// Returns a default AgentConfig instance; further configuration via chain calls
    pub fn new(model_name: &str, agent_name: &str, system_prompt: &str) -> Self {
        Self {
            model_name: model_name.to_string(),
            system_prompt: system_prompt.to_string(),
            agent_name: agent_name.to_string(),
            max_iterations: 10,
            allowed_tools: Vec::new(),
            role: AgentRole::default(),
            enable_tool: false,
            enable_task: false,
            enable_human_in_loop: false,
            enable_subagent: false,
            token_limit: usize::MAX,
            callbacks: Vec::new(),
            llm_max_retries: 3,
            llm_retry_delay_ms: 500,
            tool_error_feedback: true,
            enable_cot: true,
            tool_execution: ToolExecutionConfig::default(),
            enable_memory: false,
            memory_path: "~/.echo-agent/store.json".to_string(),
            session_id: None,
            conversation_id: None,
            checkpointer_path: "~/.echo-agent/checkpoints.json".to_string(),
            response_format: None,
            max_tool_output_tokens: None,
            compress_threshold_ratio: 0.2,
            temperature: None,
            max_tokens: None,
            auto_project_rules: true,
            working_dir: None,
        }
    }

    // ── Preset Configurations (usability optimizations) ───────────────────────────────

    /// Create a minimal Agent (no tools, no memory)
    ///
    /// Suitable for simple conversation scenarios.
    pub fn minimal(model_name: &str, system_prompt: &str) -> Self {
        Self::new(model_name, "assistant", system_prompt)
            .enable_tool(false)
            .enable_memory(false)
            .enable_cot(false)
    }

    /// Create a standard Agent (tools + chain-of-thought enabled)
    ///
    /// Suitable for most Agent scenarios.
    pub fn standard(model_name: &str, agent_name: &str, system_prompt: &str) -> Self {
        Self::new(model_name, agent_name, system_prompt)
            .enable_tool(true)
            .enable_cot(true)
    }

    /// Create a full-featured Agent (tools, memory, planning)
    ///
    /// Suitable for complex autonomous Agent scenarios.
    pub fn full_featured(model_name: &str, agent_name: &str, system_prompt: &str) -> Self {
        Self::new(model_name, agent_name, system_prompt)
            .enable_tool(true)
            .enable_memory(true)
            .enable_task(true)
            .enable_cot(true)
    }

    /// Enable all features (tools, memory, planning) - Builder chain call version
    pub fn with_full_features(mut self) -> Self {
        self.enable_tool = true;
        self.enable_memory = true;
        self.enable_task = true;
        self.enable_cot = true;
        self
    }

    /// Enable basic tool features (tools + chain-of-thought) - Builder chain call version
    pub fn with_tools(mut self) -> Self {
        self.enable_tool = true;
        self.enable_cot = true;
        self
    }

    // ── Original Builder Methods ─────────────────────────────────────────────────────

    /// Set Agent role
    ///
    /// # Parameters
    /// * `role` - Agent role (`AgentRole::Orchestrator` or `AgentRole::Worker`)
    ///
    /// # Description
    /// - `Orchestrator`: orchestrator role, responsible for task planning, allocation, and coordinating sub-agents
    /// - `Worker`: worker role, focused on specific task execution
    pub fn role(mut self, role: AgentRole) -> Self {
        self.role = role;
        self
    }

    /// Enable or disable tool calling
    ///
    /// # Parameters
    /// * `enabled` - `true` to enable tool calling, `false` to disable
    ///
    /// # Description
    /// When enabled, the Agent can call registered business tools (e.g., math, file operations, etc.)
    pub fn enable_tool(mut self, enabled: bool) -> Self {
        self.enable_tool = enabled;
        self
    }

    /// Enable or disable task planning capability
    ///
    /// # Parameters
    /// * `enabled` - `true` to enable task planning, `false` to disable
    ///
    /// # Description
    /// When enabled, the Agent can use task management tools such as `plan`, `create_task`, `update_task`
    pub fn enable_task(mut self, enabled: bool) -> Self {
        self.enable_task = enabled;
        self
    }

    /// Enable or disable Human-in-the-Loop functionality
    ///
    /// # Parameters
    /// * `enabled` - `true` to enable human interaction, `false` to disable
    ///
    /// # Description
    /// When enabled, the Agent can request human intervention via the `human_in_loop` tool when approval or confirmation is needed
    pub fn enable_human_in_loop(mut self, enabled: bool) -> Self {
        self.enable_human_in_loop = enabled;
        self
    }

    /// Enable or disable subagent dispatch
    ///
    /// # Parameters
    /// * `enabled` - `true` to enable subagent dispatch, `false` to disable
    ///
    /// # Description
    /// When enabled, the Agent can use the `agent_tool` tool to dispatch other sub-agents for task execution
    pub fn enable_subagent(mut self, enabled: bool) -> Self {
        self.enable_subagent = enabled;
        self
    }

    /// Set tool allowlist
    ///
    /// # Parameters
    /// * `tools` - List of allowed tool names
    ///
    /// # Description
    /// - If the list is empty, no restriction; all registered tools can be called
    /// - If the list is non-empty, only tools in the list can be called
    pub fn allowed_tools(mut self, tools: Vec<String>) -> Self {
        self.allowed_tools.extend(tools);
        self
    }

    /// Get tool allowlist
    ///
    /// # Returns
    /// Returns a slice of currently allowed tool names
    pub fn get_allowed_tools(&self) -> &[String] {
        &self.allowed_tools
    }

    /// Check if tool calling is enabled
    ///
    /// # Returns
    /// `true` if tool calling is enabled, `false` if disabled
    pub fn is_tool_enabled(&self) -> bool {
        self.enable_tool
    }

    /// Check if task planning is enabled
    ///
    /// # Returns
    /// `true` if task planning is enabled, `false` if disabled
    pub fn is_task_enabled(&self) -> bool {
        self.enable_task
    }

    /// Check if Human-in-the-Loop is enabled
    ///
    /// # Returns
    /// `true` if human-in-the-loop is enabled, `false` if disabled
    pub fn is_human_in_loop_enabled(&self) -> bool {
        self.enable_human_in_loop
    }

    /// Check if subagent dispatch is enabled
    ///
    /// # Returns
    /// `true` if subagent dispatch is enabled, `false` if disabled
    pub fn is_subagent_enabled(&self) -> bool {
        self.enable_subagent
    }

    /// Set maximum iteration rounds
    ///
    /// # Parameters
    /// * `max_iterations` - Maximum iteration count, prevents infinite loops
    ///
    /// # Description
    /// The Agent performs at most the specified number of iterations during execution; exceeding this limit terminates execution
    pub fn max_iterations(mut self, max_iterations: usize) -> Self {
        self.max_iterations = max_iterations;
        self
    }

    /// Set Agent name
    ///
    /// # Parameters
    /// * `agent_name` - Agent name, used for identification and logging
    pub fn agent_name(mut self, agent_name: &str) -> Self {
        self.agent_name = agent_name.to_string();
        self
    }

    /// Set LLM model name
    ///
    /// # Parameters
    /// * `model_name` - LLM model name to use (corresponds to model identifier in config)
    pub fn model_name(mut self, model_name: &str) -> Self {
        self.model_name = model_name.to_string();
        self
    }

    /// Set model name at runtime (mutable reference version)
    pub fn set_model_name(&mut self, model_name: &str) {
        self.model_name = model_name.to_string();
    }

    /// Set system prompt
    ///
    /// # Parameters
    /// * `system_prompt` - System prompt, defines the Agent's role and capabilities
    pub fn system_prompt(mut self, system_prompt: &str) -> Self {
        self.system_prompt = system_prompt.to_string();
        self
    }

    /// Set context token limit
    ///
    /// # Parameters
    /// * `limit` - Context token limit; auto-triggers compression when exceeded (`usize::MAX` means no limit)
    pub fn token_limit(mut self, limit: usize) -> Self {
        self.token_limit = limit;
        self
    }

    /// Add Agent callback
    ///
    /// # Parameters
    /// * `callback` - Callback instance implementing the `AgentCallback` trait
    ///
    /// # Description
    /// Callbacks are invoked when different events are triggered during Agent execution, for monitoring, logging, etc.
    pub fn with_callback(mut self, callback: Arc<dyn AgentCallback>) -> Self {
        self.callbacks.push(callback);
        self
    }

    /// Set maximum retry count after LLM call failure
    ///
    /// # Parameters
    /// * `retries` - Maximum retry count (0 = no retry, default 3)
    pub fn llm_max_retries(mut self, retries: usize) -> Self {
        self.llm_max_retries = retries;
        self
    }

    /// Set LLM retry initial delay
    ///
    /// # Parameters
    /// * `delay_ms` - Initial delay (milliseconds), doubles with exponential backoff (default 500)
    pub fn llm_retry_delay_ms(mut self, delay_ms: u64) -> Self {
        self.llm_retry_delay_ms = delay_ms;
        self
    }

    /// Enable or disable tool error feedback
    ///
    /// # Parameters
    /// * `enabled` - `true` to enable tool error feedback, `false` to disable
    ///
    /// # Description
    /// When enabled, tool execution failures feed the error back to the LLM instead of failing the Agent directly
    pub fn tool_error_feedback(mut self, enabled: bool) -> Self {
        self.tool_error_feedback = enabled;
        self
    }

    /// Get session identifier
    ///
    /// # Returns
    /// Reference to session identifier, or `None` if not set
    ///
    /// # Description
    /// The session identifier is used by Checkpointer to restore the same conversation's historical context across process restarts
    pub fn get_session_id(&self) -> Option<&str> {
        self.session_id.as_deref()
    }

    /// Get conversation identifier
    ///
    /// # Returns
    /// Reference to conversation identifier, or `None` if not set
    ///
    /// # Description
    /// The conversation identifier is used for `ConversationStore` transcript/history projections;
    /// it is a separate concept from `session_id`, which is used for restoring thread state.
    pub fn get_conversation_id(&self) -> Option<&str> {
        self.conversation_id.as_deref()
    }

    /// Get maximum retry count after LLM call failure
    ///
    /// # Returns
    /// Maximum retry count
    pub fn get_llm_max_retries(&self) -> usize {
        self.llm_max_retries
    }

    /// Get LLM retry initial delay
    ///
    /// # Returns
    /// Initial delay (milliseconds)
    pub fn get_llm_retry_delay_ms(&self) -> u64 {
        self.llm_retry_delay_ms
    }

    /// Get tool error feedback setting
    ///
    /// # Returns
    /// `true` if tool error feedback is enabled, `false` if disabled
    pub fn get_tool_error_feedback(&self) -> bool {
        self.tool_error_feedback
    }

    /// Get maximum iteration rounds
    ///
    /// # Returns
    /// Maximum iteration count
    pub fn get_max_iterations(&self) -> usize {
        self.max_iterations
    }

    /// Get context token limit
    ///
    /// # Returns
    /// Context token limit, `usize::MAX` means no limit
    pub fn get_token_limit(&self) -> usize {
        self.token_limit
    }

    /// Check if chain-of-thought (CoT) is enabled
    ///
    /// # Returns
    /// `true` if CoT is enabled, `false` if disabled
    pub fn is_cot_enabled(&self) -> bool {
        self.enable_cot
    }

    /// Check if long-term memory is enabled
    ///
    /// # Returns
    /// `true` if long-term memory is enabled, `false` if disabled
    pub fn is_memory_enabled(&self) -> bool {
        self.enable_memory
    }

    /// Get long-term memory store file path
    ///
    /// # Returns
    /// Long-term memory store file path
    pub fn get_memory_path(&self) -> &str {
        &self.memory_path
    }

    /// Get checkpointer file path
    ///
    /// # Returns
    /// Checkpointer file path
    pub fn get_checkpointer_path(&self) -> &str {
        &self.checkpointer_path
    }

    /// Get tool execution configuration
    ///
    /// # Returns
    /// Reference to tool execution configuration (includes timeout, retry strategy, parallel concurrency, etc.)
    pub fn get_tool_execution(&self) -> &crate::tools::ToolExecutionConfig {
        &self.tool_execution
    }

    /// Get structured output format
    ///
    /// # Returns
    /// Reference to structured output format, or `None` if not set
    pub fn get_response_format(&self) -> Option<&crate::llm::ResponseFormat> {
        self.response_format.as_ref()
    }

    /// Get LLM model name
    ///
    /// # Returns
    /// LLM model name
    pub fn get_model_name(&self) -> &str {
        &self.model_name
    }

    /// Get system prompt
    ///
    /// # Returns
    /// System prompt
    pub fn get_system_prompt(&self) -> &str {
        &self.system_prompt
    }

    /// Get Agent name
    ///
    /// # Returns
    /// Agent name
    pub fn get_agent_name(&self) -> &str {
        &self.agent_name
    }

    /// Enable or disable chain-of-thought (CoT)
    ///
    /// # Parameters
    /// * `enabled` - `true` to enable CoT, `false` to disable
    ///
    /// # Description
    /// When CoT is enabled, the Agent injects CoT-related instructions into the system prompt
    pub fn enable_cot(mut self, enabled: bool) -> Self {
        self.enable_cot = enabled;
        self
    }

    /// Enable or disable long-term memory
    ///
    /// # Parameters
    /// * `enabled` - `true` to enable long-term memory, `false` to disable
    ///
    /// # Description
    /// When enabled, the Agent can use remember/recall/forget tools, with automatic context injection support
    pub fn enable_memory(mut self, enabled: bool) -> Self {
        self.enable_memory = enabled;
        self
    }

    /// Set long-term memory store file path
    ///
    /// # Parameters
    /// * `path` - Long-term memory store file path
    pub fn memory_path(mut self, path: &str) -> Self {
        self.memory_path = path.to_string();
        self
    }

    /// Set session identifier
    ///
    /// # Parameters
    /// * `id` - Session identifier
    ///
    /// # Description
    /// The session identifier is used by Checkpointer to restore the same conversation's historical context across process restarts
    pub fn session_id(mut self, id: &str) -> Self {
        self.session_id = Some(id.to_string());
        self
    }

    /// Set conversation identifier
    ///
    /// # Parameters
    /// * `id` - Conversation identifier
    ///
    /// # Description
    /// The conversation identifier is used by `ConversationStore` to persist transcript/history projections.
    /// Unlike `session_id`, it does not handle thread state restoration.
    pub fn conversation_id(mut self, id: &str) -> Self {
        self.conversation_id = Some(id.to_string());
        self
    }

    /// Set checkpointer file path
    ///
    /// # Parameters
    /// * `path` - Checkpointer file path
    pub fn checkpointer_path(mut self, path: &str) -> Self {
        self.checkpointer_path = path.to_string();
        self
    }

    /// Set tool execution configuration
    ///
    /// # Parameters
    /// * `config` - Tool execution configuration (includes timeout, retry strategy, parallel concurrency, etc.)
    pub fn tool_execution(mut self, config: ToolExecutionConfig) -> Self {
        self.tool_execution = config;
        self
    }

    /// Set structured output format
    ///
    /// # Parameters
    /// * `fmt` - Structured output format
    pub fn response_format(mut self, fmt: ResponseFormat) -> Self {
        self.response_format = Some(fmt);
        self
    }

    /// Set maximum token count for a single tool output; automatically truncated when exceeded
    pub fn max_tool_output_tokens(mut self, max: usize) -> Self {
        self.max_tool_output_tokens = Some(max);
        self
    }

    /// Get maximum token count for a single tool output
    ///
    /// # Returns
    /// Maximum token count, `None` means no limit
    pub fn get_max_tool_output_tokens(&self) -> Option<usize> {
        self.max_tool_output_tokens
    }

    /// Set proactive compression threshold ratio (0.0–1.0), default 0.2
    pub fn compress_threshold_ratio(mut self, ratio: f64) -> Self {
        self.compress_threshold_ratio = ratio.clamp(0.0, 1.0);
        self
    }

    /// Get proactive compression threshold ratio
    ///
    /// # Returns
    /// Compression threshold ratio (0.0–1.0), default 0.2
    pub fn get_compress_threshold_ratio(&self) -> f64 {
        self.compress_threshold_ratio
    }

    /// Enable or disable automatic project rules loading
    ///
    /// # Parameters
    /// * `enabled` - `true` to automatically search for `.echo-agent/AGENT.md` in the working directory and inject into system prompt
    pub fn auto_project_rules(mut self, enabled: bool) -> Self {
        self.auto_project_rules = enabled;
        self
    }

    /// Set working directory (for searching project rules files)
    ///
    /// # Parameters
    /// * `path` - Working directory path, None means use current directory
    pub fn working_dir(mut self, path: Option<PathBuf>) -> Self {
        self.working_dir = path;
        self
    }

    /// Set LLM temperature parameter
    ///
    /// # Parameters
    /// * `temperature` - Temperature value (0.0–2.0, None means use model default)
    pub fn temperature(mut self, temperature: Option<f32>) -> Self {
        self.temperature = temperature;
        self
    }

    /// Get LLM temperature parameter
    ///
    /// # Returns
    /// Temperature value, `None` means use model default
    pub fn get_temperature(&self) -> Option<f32> {
        self.temperature
    }

    /// Set maximum generation token count
    ///
    /// # Parameters
    /// * `max_tokens` - Maximum token count (None means use model default)
    pub fn max_tokens(mut self, max_tokens: Option<u32>) -> Self {
        self.max_tokens = max_tokens;
        self
    }

    /// Get maximum generation token count
    ///
    /// # Returns
    /// Maximum token count, `None` means use model default
    pub fn get_max_tokens(&self) -> Option<u32> {
        self.max_tokens
    }
}

// ── Unit Tests ──────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_agent_config_new() {
        let config = AgentConfig::new("qwen3-max", "assistant", "You are a helpful assistant");

        assert_eq!(config.get_model_name(), "qwen3-max");
        assert_eq!(config.get_agent_name(), "assistant");
        assert_eq!(config.get_system_prompt(), "You are a helpful assistant");
        assert_eq!(config.get_max_iterations(), 10);
        assert_eq!(config.get_token_limit(), usize::MAX);
        assert!(!config.is_tool_enabled());
        assert!(!config.is_task_enabled());
        assert!(!config.is_human_in_loop_enabled());
        assert!(!config.is_subagent_enabled());
    }

    #[test]
    fn test_agent_config_minimal() {
        let config = AgentConfig::minimal("qwen3-max", "Be helpful");

        assert_eq!(config.get_model_name(), "qwen3-max");
        assert!(!config.is_tool_enabled());
        assert!(!config.is_memory_enabled());
        assert!(!config.is_cot_enabled());
    }

    #[test]
    fn test_agent_config_standard() {
        let config = AgentConfig::standard("qwen3-max", "agent1", "You are helpful");

        assert!(config.is_tool_enabled());
        assert!(config.is_cot_enabled());
    }

    #[test]
    fn test_agent_config_full_featured() {
        let config = AgentConfig::full_featured("qwen3-max", "agent1", "You are helpful");

        assert!(config.is_tool_enabled());
        assert!(config.is_memory_enabled());
        assert!(config.is_task_enabled());
        assert!(config.is_cot_enabled());
    }

    #[test]
    fn test_agent_config_builder_chain() {
        let config = AgentConfig::new("model", "agent", "prompt")
            .max_iterations(20)
            .token_limit(8000)
            .enable_tool(true)
            .enable_task(true)
            .enable_human_in_loop(true)
            .enable_subagent(true)
            .enable_memory(true)
            .enable_cot(false)
            .llm_max_retries(5)
            .llm_retry_delay_ms(1000)
            .tool_error_feedback(false);

        assert_eq!(config.get_max_iterations(), 20);
        assert_eq!(config.get_token_limit(), 8000);
        assert!(config.is_tool_enabled());
        assert!(config.is_task_enabled());
        assert!(config.is_human_in_loop_enabled());
        assert!(config.is_subagent_enabled());
        assert!(config.is_memory_enabled());
        assert!(!config.is_cot_enabled());
        assert_eq!(config.get_llm_max_retries(), 5);
        assert_eq!(config.get_llm_retry_delay_ms(), 1000);
        assert!(!config.get_tool_error_feedback());
    }

    #[test]
    fn test_agent_config_allowed_tools() {
        let config = AgentConfig::new("model", "agent", "prompt")
            .allowed_tools(vec!["tool1".to_string(), "tool2".to_string()]);

        assert_eq!(config.get_allowed_tools(), &["tool1", "tool2"]);
    }

    #[test]
    fn test_agent_config_session_id() {
        let config = AgentConfig::new("model", "agent", "prompt").session_id("session-123");

        assert_eq!(config.get_session_id(), Some("session-123"));
    }

    #[test]
    fn test_agent_config_conversation_id() {
        let config =
            AgentConfig::new("model", "agent", "prompt").conversation_id("conversation-123");

        assert_eq!(config.get_conversation_id(), Some("conversation-123"));
    }

    #[test]
    fn test_agent_config_role() {
        let config = AgentConfig::new("model", "agent", "prompt").role(AgentRole::Orchestrator);

        assert_eq!(config.role, AgentRole::Orchestrator);
    }

    #[test]
    fn test_agent_config_model_name_mutation() {
        let mut config = AgentConfig::new("model1", "agent", "prompt");

        config.set_model_name("model2");
        assert_eq!(config.get_model_name(), "model2");
    }

    #[test]
    fn test_agent_config_with_full_features() {
        let config = AgentConfig::new("model", "agent", "prompt").with_full_features();

        assert!(config.is_tool_enabled());
        assert!(config.is_memory_enabled());
        assert!(config.is_task_enabled());
        assert!(config.is_cot_enabled());
    }

    #[test]
    fn test_agent_config_with_tools() {
        let config = AgentConfig::new("model", "agent", "prompt").with_tools();

        assert!(config.is_tool_enabled());
        assert!(config.is_cot_enabled());
    }

    #[test]
    fn test_agent_config_memory_path() {
        let config =
            AgentConfig::new("model", "agent", "prompt").memory_path("/custom/path/store.json");

        assert_eq!(config.get_memory_path(), "/custom/path/store.json");
    }

    #[test]
    fn test_agent_config_checkpointer_path() {
        let config = AgentConfig::new("model", "agent", "prompt")
            .checkpointer_path("/custom/path/checkpoints.json");

        assert_eq!(
            config.get_checkpointer_path(),
            "/custom/path/checkpoints.json"
        );
    }

    #[test]
    fn test_agent_role_default() {
        assert_eq!(AgentRole::default(), AgentRole::Worker);
    }
}