-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathagent_api.rs
More file actions
3986 lines (3605 loc) · 153 KB
/
Copy pathagent_api.rs
File metadata and controls
3986 lines (3605 loc) · 153 KB
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Agent Facade API
//!
//! High-level, ergonomic API for using A3S Code as an embedded library.
//!
//! ## Example
//!
//! ```rust,no_run
//! use a3s_code_core::Agent;
//!
//! # async fn run() -> anyhow::Result<()> {
//! let agent = Agent::new("agent.hcl").await?;
//! let session = agent.session("/my-project", None)?;
//! let result = session.send("Explain the auth module", None).await?;
//! println!("{}", result.text);
//! # Ok(())
//! # }
//! ```
use crate::agent::{AgentConfig, AgentEvent, AgentLoop, AgentResult};
use crate::commands::{
CommandAction, CommandContext, CommandRegistry, CronCancelCommand, CronListCommand, LoopCommand,
};
use crate::config::CodeConfig;
use crate::error::{read_or_recover, write_or_recover, CodeError, Result};
use crate::hitl::PendingConfirmationInfo;
use crate::llm::{LlmClient, Message};
use crate::prompts::{PlanningMode, SystemPromptSlots};
use crate::queue::{
ExternalTask, ExternalTaskResult, LaneHandlerConfig, SessionLane, SessionQueueConfig,
SessionQueueStats,
};
use crate::scheduler::{CronScheduler, ScheduledFire};
use crate::session_lane_queue::SessionLaneQueue;
use crate::task::{ProgressTracker, TaskManager};
use crate::text::truncate_utf8;
use crate::tools::{ToolContext, ToolExecutor};
use a3s_lane::{DeadLetter, MetricsSnapshot};
use a3s_memory::{FileMemoryStore, MemoryStore};
use anyhow::Context;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
use tokio::sync::{broadcast, mpsc};
use tokio::task::JoinHandle;
/// Canonicalize a path, stripping the Windows `\\?\` UNC prefix to avoid
/// polluting workspace strings throughout the system (prompts, session data, etc.).
fn safe_canonicalize(path: &Path) -> PathBuf {
match std::fs::canonicalize(path) {
Ok(p) => strip_unc_prefix(p),
Err(_) => path.to_path_buf(),
}
}
/// Strip the Windows extended-length path prefix (`\\?\`) that `canonicalize()` adds.
/// On non-Windows this is a no-op.
fn strip_unc_prefix(path: PathBuf) -> PathBuf {
#[cfg(windows)]
{
let s = path.to_string_lossy();
if let Some(stripped) = s.strip_prefix(r"\\?\") {
return PathBuf::from(stripped);
}
}
path
}
// ============================================================================
// ToolCallResult
// ============================================================================
/// Result of a direct tool execution (no LLM).
#[derive(Debug, Clone)]
pub struct ToolCallResult {
pub name: String,
pub output: String,
pub exit_code: i32,
pub metadata: Option<serde_json::Value>,
}
// ============================================================================
// SessionOptions
// ============================================================================
/// Optional per-session overrides.
#[derive(Clone, Default)]
pub struct SessionOptions {
/// Override the default model. Format: `"provider/model"` (e.g., `"openai/gpt-4o"`).
pub model: Option<String>,
/// Extra directories to scan for agent files.
/// Merged with any global `agent_dirs` from [`CodeConfig`].
pub agent_dirs: Vec<PathBuf>,
/// Optional queue configuration for lane-based tool execution.
///
/// When set, enables priority-based tool scheduling with parallel execution
/// of read-only (Query-lane) tools, DLQ, metrics, and external task handling.
pub queue_config: Option<SessionQueueConfig>,
/// Optional security provider for taint tracking and output sanitization
pub security_provider: Option<Arc<dyn crate::security::SecurityProvider>>,
/// Optional context providers for RAG
pub context_providers: Vec<Arc<dyn crate::context::ContextProvider>>,
/// Optional confirmation manager for HITL
pub confirmation_manager: Option<Arc<dyn crate::hitl::ConfirmationProvider>>,
/// Optional permission checker
pub permission_checker: Option<Arc<dyn crate::permissions::PermissionChecker>>,
/// Enable planning
pub planning_mode: PlanningMode,
/// Enable goal tracking
pub goal_tracking: bool,
/// Extra directories to scan for skill files (*.md).
/// Merged with any global `skill_dirs` from [`CodeConfig`].
pub skill_dirs: Vec<PathBuf>,
/// Optional skill registry for instruction injection
pub skill_registry: Option<Arc<crate::skills::SkillRegistry>>,
/// Optional memory store for long-term memory persistence
pub memory_store: Option<Arc<dyn MemoryStore>>,
/// Deferred file memory directory — constructed async in `build_session()`
pub(crate) file_memory_dir: Option<PathBuf>,
/// Optional session store for persistence
pub session_store: Option<Arc<dyn crate::store::SessionStore>>,
/// Explicit session ID (auto-generated if not set)
pub session_id: Option<String>,
/// Auto-save after each `send()` call
pub auto_save: bool,
/// Max consecutive parse errors before aborting (overrides default of 2).
/// `None` uses the `AgentConfig` default.
pub max_parse_retries: Option<u32>,
/// Per-tool execution timeout in milliseconds.
/// `None` = no timeout (default).
pub tool_timeout_ms: Option<u64>,
/// Circuit-breaker threshold: max consecutive LLM API failures before
/// aborting in non-streaming mode (overrides default of 3).
/// `None` uses the `AgentConfig` default.
pub circuit_breaker_threshold: Option<u32>,
/// Optional sandbox configuration (kept for backward compatibility).
///
/// Setting this alone has no effect; the host application must also supply
/// a concrete [`BashSandbox`] implementation via [`with_sandbox_handle`].
///
/// [`BashSandbox`]: crate::sandbox::BashSandbox
/// [`with_sandbox_handle`]: Self::with_sandbox_handle
pub sandbox_config: Option<crate::sandbox::SandboxConfig>,
/// Optional concrete sandbox implementation.
///
/// When set, `bash` tool commands are routed through this sandbox instead
/// of `std::process::Command`. The host application constructs and owns
/// the implementation (e.g., an A3S Box–backed handle).
pub sandbox_handle: Option<Arc<dyn crate::sandbox::BashSandbox>>,
/// Enable auto-compaction when context usage exceeds threshold.
pub auto_compact: bool,
/// Context usage percentage threshold for auto-compaction (0.0 - 1.0).
/// Default: 0.80 (80%).
pub auto_compact_threshold: Option<f32>,
/// Inject a continuation message when the LLM stops without completing the task.
/// `None` uses the `AgentConfig` default (true).
pub continuation_enabled: Option<bool>,
/// Maximum continuation injections per execution.
/// `None` uses the `AgentConfig` default (3).
pub max_continuation_turns: Option<u32>,
/// Optional MCP manager for connecting to external MCP servers.
///
/// When set, all tools from connected MCP servers are registered and
/// available during agent execution with names like `mcp__server__tool`.
pub mcp_manager: Option<Arc<crate::mcp::manager::McpManager>>,
/// Sampling temperature (0.0–1.0). Overrides the provider default.
pub temperature: Option<f32>,
/// Extended thinking budget in tokens (Anthropic only).
pub thinking_budget: Option<usize>,
/// Per-session tool round limit override.
///
/// When set, overrides the agent-level `max_tool_rounds` for this session only.
/// Maps directly from [`AgentDefinition::max_steps`] when creating sessions
/// via [`Agent::session_for_agent`].
pub max_tool_rounds: Option<usize>,
/// Slot-based system prompt customization.
///
/// When set, overrides the agent-level prompt slots for this session.
/// Users can customize role, guidelines, response style, and extra instructions
/// without losing the core agentic capabilities.
pub prompt_slots: Option<SystemPromptSlots>,
/// Optional external hook executor (e.g. an AHP harness server).
///
/// When set, **replaces** the built-in `HookEngine` for this session.
/// All 11 lifecycle events are forwarded to the executor instead of being
/// dispatched locally. The executor is also propagated to sub-agents via
/// the sentinel hook mechanism.
pub hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
/// Plugins to mount onto this session.
///
/// Each plugin is loaded in order after the core tools are registered.
/// Use [`PluginManager`] or add plugins directly via [`SessionOptions::with_plugin`].
///
/// Built-in tools such as `agentic_search` and `agentic_parse` are no longer
/// mounted via plugins; plugins are reserved for custom extensions such as
/// skill-only bundles.
pub plugins: Vec<std::sync::Arc<dyn crate::plugin::Plugin>>,
}
impl std::fmt::Debug for SessionOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionOptions")
.field("model", &self.model)
.field("agent_dirs", &self.agent_dirs)
.field("skill_dirs", &self.skill_dirs)
.field("queue_config", &self.queue_config)
.field("security_provider", &self.security_provider.is_some())
.field("context_providers", &self.context_providers.len())
.field("confirmation_manager", &self.confirmation_manager.is_some())
.field("permission_checker", &self.permission_checker.is_some())
.field("planning_mode", &self.planning_mode)
.field("goal_tracking", &self.goal_tracking)
.field(
"skill_registry",
&self
.skill_registry
.as_ref()
.map(|r| format!("{} skills", r.len())),
)
.field("memory_store", &self.memory_store.is_some())
.field("session_store", &self.session_store.is_some())
.field("session_id", &self.session_id)
.field("auto_save", &self.auto_save)
.field("max_parse_retries", &self.max_parse_retries)
.field("tool_timeout_ms", &self.tool_timeout_ms)
.field("circuit_breaker_threshold", &self.circuit_breaker_threshold)
.field("sandbox_config", &self.sandbox_config)
.field("auto_compact", &self.auto_compact)
.field("auto_compact_threshold", &self.auto_compact_threshold)
.field("continuation_enabled", &self.continuation_enabled)
.field("max_continuation_turns", &self.max_continuation_turns)
.field(
"plugins",
&self.plugins.iter().map(|p| p.name()).collect::<Vec<_>>(),
)
.field("mcp_manager", &self.mcp_manager.is_some())
.field("temperature", &self.temperature)
.field("thinking_budget", &self.thinking_budget)
.field("max_tool_rounds", &self.max_tool_rounds)
.field("prompt_slots", &self.prompt_slots.is_some())
.finish()
}
}
impl SessionOptions {
pub fn new() -> Self {
Self::default()
}
/// Mount a plugin onto this session.
///
/// The plugin's tools are registered after the core tools, in the order
/// plugins are added.
pub fn with_plugin(mut self, plugin: impl crate::plugin::Plugin + 'static) -> Self {
self.plugins.push(std::sync::Arc::new(plugin));
self
}
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
pub fn with_agent_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.agent_dirs.push(dir.into());
self
}
pub fn with_queue_config(mut self, config: SessionQueueConfig) -> Self {
self.queue_config = Some(config);
self
}
/// Enable default security provider with taint tracking and output sanitization
pub fn with_default_security(mut self) -> Self {
self.security_provider = Some(Arc::new(crate::security::DefaultSecurityProvider::new()));
self
}
/// Set a custom security provider
pub fn with_security_provider(
mut self,
provider: Arc<dyn crate::security::SecurityProvider>,
) -> Self {
self.security_provider = Some(provider);
self
}
/// Add a file system context provider for simple RAG
pub fn with_fs_context(mut self, root_path: impl Into<PathBuf>) -> Self {
let config = crate::context::FileSystemContextConfig::new(root_path);
self.context_providers
.push(Arc::new(crate::context::FileSystemContextProvider::new(
config,
)));
self
}
/// Add a custom context provider
pub fn with_context_provider(
mut self,
provider: Arc<dyn crate::context::ContextProvider>,
) -> Self {
self.context_providers.push(provider);
self
}
/// Set a confirmation manager for HITL
pub fn with_confirmation_manager(
mut self,
manager: Arc<dyn crate::hitl::ConfirmationProvider>,
) -> Self {
self.confirmation_manager = Some(manager);
self
}
/// Set a permission checker
pub fn with_permission_checker(
mut self,
checker: Arc<dyn crate::permissions::PermissionChecker>,
) -> Self {
self.permission_checker = Some(checker);
self
}
/// Allow all tool execution without confirmation (permissive mode).
///
/// Use this for automated scripts, demos, and CI environments where
/// human-in-the-loop confirmation is not needed. Without this (or a
/// custom permission checker), the default is `Ask`, which requires a
/// HITL confirmation manager to be configured.
pub fn with_permissive_policy(self) -> Self {
self.with_permission_checker(Arc::new(crate::permissions::PermissionPolicy::permissive()))
}
/// Set planning mode
pub fn with_planning_mode(mut self, mode: PlanningMode) -> Self {
self.planning_mode = mode;
self
}
/// Enable planning (shortcut for `with_planning_mode(PlanningMode::Enabled)`)
pub fn with_planning(mut self, enabled: bool) -> Self {
self.planning_mode = if enabled {
PlanningMode::Enabled
} else {
PlanningMode::Disabled
};
self
}
/// Enable goal tracking
pub fn with_goal_tracking(mut self, enabled: bool) -> Self {
self.goal_tracking = enabled;
self
}
/// Add a skill registry with built-in skills
pub fn with_builtin_skills(mut self) -> Self {
self.skill_registry = Some(Arc::new(crate::skills::SkillRegistry::with_builtins()));
self
}
/// Add a custom skill registry
pub fn with_skill_registry(mut self, registry: Arc<crate::skills::SkillRegistry>) -> Self {
self.skill_registry = Some(registry);
self
}
/// Add skill directories to scan for skill files (*.md).
/// Merged with any global `skill_dirs` from [`CodeConfig`] at session build time.
pub fn with_skill_dirs(mut self, dirs: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
self.skill_dirs.extend(dirs.into_iter().map(Into::into));
self
}
/// Load skills from a directory (eager — scans immediately into a registry).
pub fn with_skills_from_dir(mut self, dir: impl AsRef<std::path::Path>) -> Self {
let registry = self
.skill_registry
.unwrap_or_else(|| Arc::new(crate::skills::SkillRegistry::new()));
if let Err(e) = registry.load_from_dir(&dir) {
tracing::warn!(
dir = %dir.as_ref().display(),
error = %e,
"Failed to load skills from directory — continuing without them"
);
}
self.skill_registry = Some(registry);
self
}
/// Set a custom memory store
pub fn with_memory(mut self, store: Arc<dyn MemoryStore>) -> Self {
self.memory_store = Some(store);
self
}
/// Use a file-based memory store at the given directory.
///
/// The store is created lazily when the session is built (requires async).
/// This stores the directory path; `FileMemoryStore::new()` is called during
/// session construction.
pub fn with_file_memory(mut self, dir: impl Into<PathBuf>) -> Self {
self.file_memory_dir = Some(dir.into());
self
}
/// Set a session store for persistence
pub fn with_session_store(mut self, store: Arc<dyn crate::store::SessionStore>) -> Self {
self.session_store = Some(store);
self
}
/// Use a file-based session store at the given directory
pub fn with_file_session_store(mut self, dir: impl Into<PathBuf>) -> Self {
let dir = dir.into();
match tokio::runtime::Handle::try_current() {
Ok(handle) => {
match tokio::task::block_in_place(|| {
handle.block_on(crate::store::FileSessionStore::new(dir))
}) {
Ok(store) => {
self.session_store =
Some(Arc::new(store) as Arc<dyn crate::store::SessionStore>);
}
Err(e) => {
tracing::warn!("Failed to create file session store: {}", e);
}
}
}
Err(_) => {
tracing::warn!(
"No async runtime available for file session store — persistence disabled"
);
}
}
self
}
/// Set an explicit session ID (auto-generated UUID if not set)
pub fn with_session_id(mut self, id: impl Into<String>) -> Self {
self.session_id = Some(id.into());
self
}
/// Enable auto-save after each `send()` call
pub fn with_auto_save(mut self, enabled: bool) -> Self {
self.auto_save = enabled;
self
}
/// Set the maximum number of consecutive malformed-tool-args errors before
/// the agent loop bails.
///
/// Default: 2 (the LLM gets two chances to self-correct before the session
/// is aborted).
pub fn with_parse_retries(mut self, max: u32) -> Self {
self.max_parse_retries = Some(max);
self
}
/// Set a per-tool execution timeout.
///
/// When set, each tool execution is wrapped in `tokio::time::timeout`.
/// A timeout produces an error message that is fed back to the LLM
/// (the session continues).
pub fn with_tool_timeout(mut self, timeout_ms: u64) -> Self {
self.tool_timeout_ms = Some(timeout_ms);
self
}
/// Set the circuit-breaker threshold.
///
/// In non-streaming mode, the agent retries transient LLM API failures up
/// to this many times (with exponential backoff) before aborting.
/// Default: 3 attempts.
pub fn with_circuit_breaker(mut self, threshold: u32) -> Self {
self.circuit_breaker_threshold = Some(threshold);
self
}
/// Enable all resilience defaults with sensible values:
///
/// - `max_parse_retries = 2`
/// - `tool_timeout_ms = 120_000` (2 minutes)
/// - `circuit_breaker_threshold = 3`
pub fn with_resilience_defaults(self) -> Self {
self.with_parse_retries(2)
.with_tool_timeout(120_000)
.with_circuit_breaker(3)
}
/// Route `bash` tool execution through an A3S Box MicroVM sandbox.
///
/// The workspace directory is mounted read-write at `/workspace` inside
/// the sandbox. Requires the `sandbox` Cargo feature; without it a warning
/// is logged and bash commands continue to run locally.
///
/// # Example
///
/// ```rust,no_run
/// use a3s_code_core::{SessionOptions, SandboxConfig};
///
/// SessionOptions::new().with_sandbox(SandboxConfig {
/// image: "ubuntu:22.04".into(),
/// memory_mb: 512,
/// network: false,
/// ..SandboxConfig::default()
/// });
/// ```
pub fn with_sandbox(mut self, config: crate::sandbox::SandboxConfig) -> Self {
self.sandbox_config = Some(config);
self
}
/// Provide a concrete [`BashSandbox`] implementation for this session.
///
/// When set, `bash` tool commands are routed through the given sandbox
/// instead of `std::process::Command`. The host application is responsible
/// for constructing and lifecycle-managing the sandbox.
///
/// [`BashSandbox`]: crate::sandbox::BashSandbox
pub fn with_sandbox_handle(mut self, handle: Arc<dyn crate::sandbox::BashSandbox>) -> Self {
self.sandbox_handle = Some(handle);
self
}
/// Enable auto-compaction when context usage exceeds threshold.
///
/// When enabled, the agent loop automatically prunes large tool outputs
/// and summarizes old messages when context usage exceeds the threshold.
pub fn with_auto_compact(mut self, enabled: bool) -> Self {
self.auto_compact = enabled;
self
}
/// Set the auto-compact threshold (0.0 - 1.0). Default: 0.80 (80%).
pub fn with_auto_compact_threshold(mut self, threshold: f32) -> Self {
self.auto_compact_threshold = Some(threshold.clamp(0.0, 1.0));
self
}
/// Enable or disable continuation injection (default: enabled).
///
/// When enabled, the loop injects a continuation message when the LLM stops
/// calling tools before the task appears complete, nudging it to keep working.
pub fn with_continuation(mut self, enabled: bool) -> Self {
self.continuation_enabled = Some(enabled);
self
}
/// Set the maximum number of continuation injections per execution (default: 3).
pub fn with_max_continuation_turns(mut self, turns: u32) -> Self {
self.max_continuation_turns = Some(turns);
self
}
/// Set an MCP manager to connect to external MCP servers.
///
/// All tools from connected servers will be available during execution
/// with names like `mcp__<server>__<tool>`.
pub fn with_mcp(mut self, manager: Arc<crate::mcp::manager::McpManager>) -> Self {
self.mcp_manager = Some(manager);
self
}
pub fn with_temperature(mut self, temperature: f32) -> Self {
self.temperature = Some(temperature);
self
}
pub fn with_thinking_budget(mut self, budget: usize) -> Self {
self.thinking_budget = Some(budget);
self
}
/// Override the maximum number of tool execution rounds for this session.
///
/// Useful when binding a markdown-defined agent to a [`TeamRunner`] member —
/// pass the agent's `max_steps` value here to enforce its step budget.
pub fn with_max_tool_rounds(mut self, rounds: usize) -> Self {
self.max_tool_rounds = Some(rounds);
self
}
/// Set slot-based system prompt customization for this session.
///
/// Allows customizing role, guidelines, response style, and extra instructions
/// without overriding the core agentic capabilities.
pub fn with_prompt_slots(mut self, slots: SystemPromptSlots) -> Self {
self.prompt_slots = Some(slots);
self
}
/// Replace the built-in hook engine with an external hook executor.
///
/// Use this to attach an AHP harness server (or any custom `HookExecutor`)
/// to the session. All lifecycle events will be forwarded to the executor
/// instead of the in-process `HookEngine`.
pub fn with_hook_executor(mut self, executor: Arc<dyn crate::hooks::HookExecutor>) -> Self {
self.hook_executor = Some(executor);
self
}
}
// ============================================================================
// Agent
// ============================================================================
/// High-level agent facade.
///
/// Holds the LLM client and agent config. Workspace-independent.
/// Use [`Agent::session()`] to bind to a workspace.
pub struct Agent {
llm_client: Arc<dyn LlmClient>,
code_config: CodeConfig,
config: AgentConfig,
/// Global MCP manager loaded from config.mcp_servers
global_mcp: Option<Arc<crate::mcp::manager::McpManager>>,
/// Pre-fetched MCP tool definitions from global_mcp (cached at creation time).
/// Wrapped in Mutex so `refresh_mcp_tools()` can update the cache without `&mut self`.
global_mcp_tools: std::sync::Mutex<Vec<(String, crate::mcp::McpTool)>>,
}
impl std::fmt::Debug for Agent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Agent").finish()
}
}
impl Agent {
/// Create from a config file path or inline ACL-compatible string.
///
/// Auto-detects: `.acl`/legacy `.hcl` file path vs inline ACL-compatible config.
pub async fn new(config_source: impl Into<String>) -> Result<Self> {
let source = config_source.into();
// Expand leading `~/` to the user's home directory (cross-platform)
let expanded = if let Some(rest) = source.strip_prefix("~/") {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
if let Some(home) = home {
PathBuf::from(home).join(rest).display().to_string()
} else {
source.clone()
}
} else {
source.clone()
};
let path = Path::new(&expanded);
let config = if matches!(
path.extension().and_then(|ext| ext.to_str()),
Some("acl" | "hcl")
) {
if !path.exists() {
return Err(CodeError::Config(format!(
"Config file not found: {}",
path.display()
)));
}
CodeConfig::from_file(path)
.with_context(|| format!("Failed to load config: {}", path.display()))?
} else if source.trim().starts_with('{') {
return Err(CodeError::Config(
"JSON config is not supported; use ACL-compatible .acl/.hcl config".into(),
));
} else if matches!(path.extension().and_then(|ext| ext.to_str()), Some("json")) {
return Err(CodeError::Config(
"JSON config files are not supported; use .acl or legacy .hcl".into(),
));
} else {
CodeConfig::from_acl(&source).context("Failed to parse config as ACL string")?
};
Self::from_config(config).await
}
/// Create from a config file path or inline ACL-compatible string.
///
/// Alias for [`Agent::new()`] — provides a consistent API with
/// the Python and Node.js SDKs.
pub async fn create(config_source: impl Into<String>) -> Result<Self> {
Self::new(config_source).await
}
/// Create from a [`CodeConfig`] struct.
pub async fn from_config(config: CodeConfig) -> Result<Self> {
let llm_config = config
.default_llm_config()
.context("default_model must be set in 'provider/model' format with a valid API key")?;
let llm_client = crate::llm::create_client_with_config(llm_config);
let agent_config = AgentConfig {
max_tool_rounds: config
.max_tool_rounds
.unwrap_or(AgentConfig::default().max_tool_rounds),
..AgentConfig::default()
};
// Load global MCP servers from config
let (global_mcp, global_mcp_tools) = if config.mcp_servers.is_empty() {
(None, vec![])
} else {
let manager = Arc::new(crate::mcp::manager::McpManager::new());
for server in &config.mcp_servers {
if !server.enabled {
continue;
}
manager.register_server(server.clone()).await;
if let Err(e) = manager.connect(&server.name).await {
tracing::warn!(
server = %server.name,
error = %e,
"Failed to connect to MCP server — skipping"
);
}
}
// Pre-fetch tool definitions while we're in async context
let tools = manager.get_all_tools().await;
(Some(manager), tools)
};
let mut agent = Agent {
llm_client,
code_config: config,
config: agent_config,
global_mcp,
global_mcp_tools: std::sync::Mutex::new(global_mcp_tools),
};
// Always initialize the skill registry with built-in skills, then load any user-defined dirs
let registry = Arc::new(crate::skills::SkillRegistry::with_builtins());
for dir in &agent.code_config.skill_dirs.clone() {
if let Err(e) = registry.load_from_dir(dir) {
tracing::warn!(
dir = %dir.display(),
error = %e,
"Failed to load skills from directory — skipping"
);
}
}
agent.config.skill_registry = Some(registry);
Ok(agent)
}
/// Re-fetch tool definitions from all connected global MCP servers and
/// update the internal cache.
///
/// Call this when an MCP server has added or removed tools since the
/// agent was created. The refreshed tools will be visible to all
/// **new** sessions created after this call; existing sessions are
/// unaffected (their `ToolExecutor` snapshot is already built).
pub async fn refresh_mcp_tools(&self) -> Result<()> {
if let Some(ref mcp) = self.global_mcp {
let fresh = mcp.get_all_tools().await;
*self
.global_mcp_tools
.lock()
.expect("global_mcp_tools lock poisoned") = fresh;
}
Ok(())
}
/// Bind to a workspace directory, returning an [`AgentSession`].
///
/// Pass `None` for defaults, or `Some(SessionOptions)` to override
/// the model, agent directories for this session.
pub fn session(
&self,
workspace: impl Into<String>,
options: Option<SessionOptions>,
) -> Result<AgentSession> {
let opts = options.unwrap_or_default();
// Merge global MCP manager with any session-level one from opts.
// If both exist, session-level servers are added into the global manager.
let mut merged_opts = match (&self.global_mcp, &opts.mcp_manager) {
(Some(global), Some(session)) => {
let global = Arc::clone(global);
let session_mgr = Arc::clone(session);
match tokio::runtime::Handle::try_current() {
Ok(handle) => {
let global_for_merge = Arc::clone(&global);
tokio::task::block_in_place(|| {
handle.block_on(async move {
for config in session_mgr.all_configs().await {
let name = config.name.clone();
global_for_merge.register_server(config).await;
if let Err(e) = global_for_merge.connect(&name).await {
tracing::warn!(
server = %name,
error = %e,
"Failed to connect session-level MCP server — skipping"
);
}
}
})
});
}
Err(_) => {
tracing::warn!(
"No async runtime available to merge session-level MCP servers \
into global manager — session MCP servers will not be available"
);
}
}
SessionOptions {
mcp_manager: Some(Arc::clone(&global)),
..opts
}
}
(Some(global), None) => SessionOptions {
mcp_manager: Some(Arc::clone(global)),
..opts
},
_ => opts,
};
let session_id = merged_opts
.session_id
.clone()
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
merged_opts.session_id = Some(session_id.clone());
let llm_client = self.resolve_session_llm_client(&merged_opts, Some(&session_id))?;
self.build_session(workspace.into(), llm_client, &merged_opts)
}
/// Create a session pre-configured from an [`AgentDefinition`].
///
/// Maps the definition's `permissions`, `prompt`, `model`, and `max_steps`
/// directly into [`SessionOptions`], so markdown/YAML-defined subagents can
/// be used as [`crate::agent_teams::TeamRunner`] members without manual wiring.
///
/// The mapping follows the same logic as the built-in `task` tool:
/// - `permissions` → `permission_checker`
/// - `prompt` → `prompt_slots.extra`
/// - `max_steps` → `max_tool_rounds`
/// - `model` → `model` (as `"provider/model"` string)
///
/// `extra` can supply additional overrides (e.g. `planning_enabled`) that
/// take precedence over the definition's values.
pub fn session_for_agent(
&self,
workspace: impl Into<String>,
def: &crate::subagent::AgentDefinition,
extra: Option<SessionOptions>,
) -> Result<AgentSession> {
let mut opts = extra.unwrap_or_default();
// Apply permission policy unless the caller supplied a custom one.
if opts.permission_checker.is_none()
&& (!def.permissions.allow.is_empty() || !def.permissions.deny.is_empty())
{
opts.permission_checker = Some(Arc::new(def.permissions.clone()));
}
// Apply max_steps unless the caller already set max_tool_rounds.
if opts.max_tool_rounds.is_none() {
if let Some(steps) = def.max_steps {
opts.max_tool_rounds = Some(steps);
}
}
// Apply model override unless the caller already chose a model.
if opts.model.is_none() {
if let Some(ref m) = def.model {
let provider = m.provider.as_deref().unwrap_or("anthropic");
opts.model = Some(format!("{}/{}", provider, m.model));
}
}
// Inject agent system prompt into the extra slot.
//
// Merge slot-by-slot rather than all-or-nothing: if the caller already
// set some slots (e.g. `role`), only fill in `extra` from the definition
// if the caller left it unset. This lets per-member overrides coexist
// with per-role prompts defined in the agent file.
if let Some(ref prompt) = def.prompt {
let slots = opts
.prompt_slots
.get_or_insert_with(crate::prompts::SystemPromptSlots::default);
if slots.extra.is_none() {
slots.extra = Some(prompt.clone());
}
}
self.session(workspace, Some(opts))
}
/// Resume a previously saved session by ID.
///
/// Loads the session data from the store, rebuilds the `AgentSession` with
/// the saved conversation history, and returns it ready for continued use.
///
/// The `options` must include a `session_store` (or `with_file_session_store`)
/// that contains the saved session.
pub fn resume_session(
&self,
session_id: &str,
options: SessionOptions,
) -> Result<AgentSession> {
let store = options.session_store.as_ref().ok_or_else(|| {
crate::error::CodeError::Session(
"resume_session requires a session_store in SessionOptions".to_string(),
)
})?;
// Load session data from store
let data = match tokio::runtime::Handle::try_current() {
Ok(handle) => tokio::task::block_in_place(|| handle.block_on(store.load(session_id)))
.map_err(|e| {
crate::error::CodeError::Session(format!(
"Failed to load session {}: {}",
session_id, e
))
})?,
Err(_) => {
return Err(crate::error::CodeError::Session(
"No async runtime available for session resume".to_string(),
))
}
};
let data = data.ok_or_else(|| {
crate::error::CodeError::Session(format!("Session not found: {}", session_id))
})?;
// Build session with the saved workspace
let mut opts = options;
opts.session_id = Some(data.id.clone());
let llm_client = self.resolve_session_llm_client(&opts, Some(&data.id))?;
let session = self.build_session(data.config.workspace.clone(), llm_client, &opts)?;
// Restore conversation history
*write_or_recover(&session.history) = data.messages;
Ok(session)
}
fn resolve_session_llm_client(
&self,
opts: &SessionOptions,
session_id: Option<&str>,
) -> Result<Arc<dyn LlmClient>> {
let model_ref = if let Some(ref model) = opts.model {
model.as_str()
} else {
if opts.temperature.is_some() || opts.thinking_budget.is_some() {
tracing::warn!(
"temperature/thinking_budget set without model override — these will be ignored. \
Use with_model() to apply LLM parameter overrides."
);
}
self.code_config
.default_model
.as_deref()
.context("default_model must be set in 'provider/model' format")?
};
let (provider_name, model_id) = model_ref
.split_once('/')
.context("model format must be 'provider/model' (e.g., 'openai/gpt-4o')")?;
let mut llm_config = self
.code_config
.llm_config(provider_name, model_id)
.with_context(|| {
format!("provider '{provider_name}' or model '{model_id}' not found in config")
})?;
if opts.model.is_some() {
if let Some(temp) = opts.temperature {
llm_config = llm_config.with_temperature(temp);
}
if let Some(budget) = opts.thinking_budget {
llm_config = llm_config.with_thinking_budget(budget);
}
}
if let Some(session_id) = session_id {
llm_config = llm_config.with_session_id(session_id);
}
Ok(crate::llm::create_client_with_config(llm_config))
}
fn build_session(
&self,
workspace: String,
llm_client: Arc<dyn LlmClient>,
opts: &SessionOptions,
) -> Result<AgentSession> {
let canonical = safe_canonicalize(Path::new(&workspace));