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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Builder for constructing agents with custom configuration.
//!
//! The builder pattern allows fluent configuration of agents with
//! tools, hooks, and various settings.
#[cfg(feature = "skills")]
use std::sync::Arc;
use aither_core::{
LanguageModel,
llm::{Tool, tool::ToolDefinition},
};
use aither_sandbox::{BackgroundTaskReceiver, JobRegistry, PermissionEventReceiver};
#[cfg(feature = "skills")]
use aither_skills::SkillRegistry;
use askama::Template;
use crate::{
agent::Agent,
config::{AgentConfig, AgentKind},
context::{AnyContextSource, Context, ContextPolicy, ContextSource},
hook::{HCons, Hook},
model_group::ModelTier,
tools::AgentTools,
};
#[cfg(feature = "mcp")]
use aither_mcp::McpConnection;
/// Builder for constructing agents with custom configuration.
///
/// Supports tiered LLM configuration:
/// - Advanced: Primary model for main reasoning (most capable)
/// - Balanced: Model for moderate tasks like subagents (defaults to advanced)
/// - Fast: Model for quick tasks like compaction (defaults to balanced)
///
/// # Example
///
/// ```rust,ignore
/// // Simple: all tiers use the same model
/// let agent = Agent::builder(claude).build();
///
/// // Tiered: different models for different tasks
/// let agent = Agent::builder(opus) // Advanced
/// .balanced_model(sonnet) // Balanced
/// .fast_model(haiku) // Fast
/// .system_prompt("You are a helpful assistant.")
/// .tool(FileSystemTool::read_only("."))
/// .build();
/// ```
#[must_use]
pub struct AgentBuilder<
Advanced,
Balanced = Advanced,
Fast = Balanced,
H = (),
Compactor = Advanced,
> {
advanced: Advanced,
balanced: Balanced,
fast: Fast,
compaction_model: Option<Compactor>,
tier: ModelTier,
tools: AgentTools,
hooks: H,
config: AgentConfig,
context: Context,
prompt_cache: crate::context::PromptCache,
clock: crate::AnyClock,
connectivity: crate::connectivity::Watch,
background_receiver: Option<BackgroundTaskReceiver>,
permission_receiver: Option<PermissionEventReceiver>,
job_registry: Option<JobRegistry>,
context_sources: Vec<AnyContextSource>,
/// Directory whose working documents (`tasks.md`) the agent supervises:
/// the main agent's sandbox.
sandbox_dir: Option<std::path::PathBuf>,
/// Resolves `BLOCKING` marks in `tasks.md`; a mark it reports dead no
/// longer holds the item.
blocker_resolver: Option<crate::working_docs::AnyTaskBlockerResolver>,
/// Directory files are restored from after a forked compaction: the
/// directory the agent's terminal works in.
restore_dir: Option<std::path::PathBuf>,
/// Where the built agent publishes each request for a fork to start from.
fork_source: Option<crate::fork::ForkSource>,
/// The window state a fork inherits, which replaces initialization.
inherited: Option<Inherited>,
#[cfg(feature = "skills")]
skill_registry: Option<Arc<SkillRegistry>>,
}
/// What a fork carries over from the main agent besides its context.
#[derive(Clone)]
struct Inherited {
budget: crate::context::ContextBudget,
profile: Option<aither_core::llm::model::Profile>,
}
impl<Advanced, Balanced, Fast, H, Compactor> std::fmt::Debug
for AgentBuilder<Advanced, Balanced, Fast, H, Compactor>
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AgentBuilder")
.field("tier", &self.tier)
.field("config", &self.config)
.finish_non_exhaustive()
}
}
impl<LLM: LanguageModel + Clone> AgentBuilder<LLM, LLM, LLM, (), LLM> {
/// Creates a new agent builder with default configuration.
///
/// All model tiers (advanced/balanced/fast) use the same model.
pub fn new(llm: LLM) -> Self {
Self {
advanced: llm.clone(),
balanced: llm.clone(),
fast: llm,
compaction_model: None,
tier: ModelTier::default(),
tools: AgentTools::new(),
hooks: (),
config: AgentConfig::default(),
context: Context::default(),
prompt_cache: crate::context::PromptCache::new(uuid::Uuid::new_v4().to_string()),
clock: crate::AnyClock::default(),
connectivity: crate::connectivity::Watch::default(),
background_receiver: None,
permission_receiver: None,
job_registry: None,
context_sources: Vec::new(),
sandbox_dir: None,
blocker_resolver: None,
restore_dir: None,
fork_source: None,
inherited: None,
#[cfg(feature = "skills")]
skill_registry: None,
}
}
}
impl<Advanced, Balanced, Fast, H, Compactor> AgentBuilder<Advanced, Balanced, Fast, H, Compactor>
where
Advanced: LanguageModel,
Balanced: LanguageModel,
Fast: LanguageModel,
Compactor: LanguageModel,
H: Hook,
{
/// Sets the balanced model for moderate tasks (e.g., subagents).
///
/// This model is used when spawning subagents that don't need
/// the full capabilities of the advanced model.
pub fn balanced_model<B2: LanguageModel>(
self,
model: B2,
) -> AgentBuilder<Advanced, B2, Fast, H, Compactor> {
AgentBuilder {
advanced: self.advanced,
balanced: model,
fast: self.fast,
compaction_model: self.compaction_model,
tier: self.tier,
tools: self.tools,
hooks: self.hooks,
config: self.config,
context: self.context,
prompt_cache: self.prompt_cache,
clock: self.clock,
connectivity: self.connectivity,
background_receiver: self.background_receiver,
permission_receiver: self.permission_receiver,
job_registry: self.job_registry,
context_sources: self.context_sources,
sandbox_dir: self.sandbox_dir,
blocker_resolver: self.blocker_resolver.clone(),
restore_dir: self.restore_dir,
fork_source: self.fork_source,
inherited: self.inherited,
#[cfg(feature = "skills")]
skill_registry: self.skill_registry,
}
}
/// Sets the fast model for quick tasks (e.g., compaction, ask command).
///
/// This model is used for tasks where speed and cost matter more
/// than capability, such as context compression.
pub fn fast_model<F2: LanguageModel>(
self,
model: F2,
) -> AgentBuilder<Advanced, Balanced, F2, H, Compactor> {
AgentBuilder {
advanced: self.advanced,
balanced: self.balanced,
fast: model,
compaction_model: self.compaction_model,
tier: self.tier,
tools: self.tools,
hooks: self.hooks,
config: self.config,
context: self.context,
prompt_cache: self.prompt_cache,
clock: self.clock,
connectivity: self.connectivity,
background_receiver: self.background_receiver,
permission_receiver: self.permission_receiver,
job_registry: self.job_registry,
context_sources: self.context_sources,
sandbox_dir: self.sandbox_dir,
blocker_resolver: self.blocker_resolver.clone(),
restore_dir: self.restore_dir,
fork_source: self.fork_source,
inherited: self.inherited,
#[cfg(feature = "skills")]
skill_registry: self.skill_registry,
}
}
/// Sets the model compaction runs on, instead of the session's own.
///
/// Without one, compaction reads the conversation's prompt cache on the
/// session's model, and an idle session is compacted shortly before the
/// cache expires ([`Agent::compact_when_idle`]). A different model cannot
/// read that cache, so with one set compaction requests go to it, idle
/// compaction never runs, and an idle gap past the cache lifetime
/// reassembles the window instead.
pub fn compaction_model<C2: LanguageModel>(
self,
model: C2,
) -> AgentBuilder<Advanced, Balanced, Fast, H, C2> {
AgentBuilder {
advanced: self.advanced,
balanced: self.balanced,
fast: self.fast,
compaction_model: Some(model),
tier: self.tier,
tools: self.tools,
hooks: self.hooks,
config: self.config,
context: self.context,
prompt_cache: self.prompt_cache,
clock: self.clock,
connectivity: self.connectivity,
background_receiver: self.background_receiver,
permission_receiver: self.permission_receiver,
job_registry: self.job_registry,
context_sources: self.context_sources,
sandbox_dir: self.sandbox_dir,
blocker_resolver: self.blocker_resolver.clone(),
restore_dir: self.restore_dir,
fork_source: self.fork_source,
inherited: self.inherited,
#[cfg(feature = "skills")]
skill_registry: self.skill_registry,
}
}
/// Sets which model tier to use for the agent's main reasoning loop.
///
/// This allows creating subagents that use different capability levels:
/// - `ModelTier::Advanced`: Use the most capable model (default)
/// - `ModelTier::Balanced`: Use the balanced model (good for subagents)
/// - `ModelTier::Fast`: Use the fast model (for quick tasks)
///
/// # Example
///
/// ```rust,ignore
/// // Create an explore subagent using the balanced model
/// let explore_agent = Agent::builder(opus)
/// .balanced_model(sonnet)
/// .fast_model(haiku)
/// .tier(ModelTier::Balanced) // Use sonnet for reasoning
/// .build();
/// ```
pub const fn tier(mut self, tier: ModelTier) -> Self {
self.tier = tier;
self
}
/// Registers an eager (always-loaded) tool.
///
/// Eager tools are included in every LLM request.
///
/// # Panics
///
/// Panics if the tool cannot be registered: another tool already uses
/// its name, or it carries no description for the model to read. Both
/// are mistakes in the calling program.
pub fn tool<T: Tool + 'static>(mut self, tool: T) -> Self {
self.tools
.register(tool)
.expect("tool registration must succeed: duplicate name or missing description");
self
}
/// Registers a dynamic terminal tool (type-erased).
///
/// This is used for child terminal capability bundles in subagents where the
/// concrete terminal type is not known at compile time.
///
/// # Panics
///
/// Panics if the `knowledge_and_time` prompt template fails to render.
pub fn dyn_terminal(mut self, dyn_tool: aither_sandbox::DynTerminalTool) -> Self {
self.context.insert_system_text(
"prepared_tools",
dyn_tool
.prepared_tools()
.render()
.expect("prepared tool catalog must render"),
);
// Seed knowledge/time guidance against the shared command registry so
// subagents are not told to run commands that were never registered
// (e.g. `websearch` when a provider-hosted search tool is active).
if !self.context.has_system_block("knowledge_and_time") {
let websearch_command = dyn_tool.has_command("websearch");
self.context.insert_system_named(
"knowledge_and_time",
crate::agent::KnowledgeAndTimeTemplate { websearch_command }
.render()
.expect("failed to render knowledge_and_time template"),
);
}
self.background_receiver = Some(dyn_tool.background_receiver());
self.permission_receiver = Some(dyn_tool.permission_receiver());
self.job_registry = Some(dyn_tool.job_registry());
// Files are restored after compaction from wherever the terminal
// works; working-document supervision (`tasks.md`) belongs to the
// main agent's terminal alone.
self.restore_dir = Some(dyn_tool.working_dir().clone());
if dyn_tool.role() == aither_sandbox::CommandRole::Main {
self.sandbox_dir = Some(dyn_tool.working_dir().clone());
}
self.tools.register_dyn_terminal(dyn_tool);
self
}
/// Publishes every request the built agent sends to `source`, which is
/// where the `fork` subagent kind starts from.
///
/// Take the source from
/// [`SubagentTool::fork_source`](crate::specialized::SubagentTool::fork_source).
pub fn fork_source(mut self, source: crate::fork::ForkSource) -> Self {
self.fork_source = Some(source);
self
}
/// Makes the built agent a fork of the main agent that sent `fork`.
///
/// The agent starts from the main agent's request: its window, with the
/// live tail as the last message, its tool definitions as the model saw
/// them, its request parameters and its prompt-cache identity, so its
/// first request is the main agent's followed by the prompt it is given
/// and reads the main agent's cache. Nothing is initialized on top of
/// that, since initialization would rewrite the window.
///
/// The tools run in `terminal`, the fork's own terminal. A tool of the
/// main agent that `terminal` does not provide stays in the definitions,
/// to keep the request identical, and refuses when called.
pub fn forked_from(
mut self,
fork: &crate::fork::ForkSnapshot,
terminal: aither_sandbox::DynTerminalTool,
) -> Self {
self.context = fork.context.clone();
self.prompt_cache = fork.prompt_cache.clone();
self.config.request_parameters = fork.request_parameters.clone();
self.config.context_policy = fork.context_policy;
self.inherited = Some(Inherited {
budget: fork.budget,
profile: Some(fork.profile.clone()),
});
self.background_receiver = Some(terminal.background_receiver());
self.permission_receiver = Some(terminal.permission_receiver());
self.job_registry = Some(terminal.job_registry());
self.restore_dir = Some(terminal.working_dir().clone());
self.tools = AgentTools::forked(&fork.definitions, terminal);
self
}
/// Adds a hook to intercept agent operations.
///
/// Hooks are composed using the `HCons` pattern, allowing multiple
/// hooks to be chained at compile time.
///
/// # Example
///
/// ```rust,ignore
/// let agent = Agent::builder(llm)
/// .hook(LoggingHook)
/// .hook(ConfirmationHook)
/// .build();
/// // Type: Agent<LLM, HCons<ConfirmationHook, HCons<LoggingHook, ()>>>
/// ```
pub fn hook<NH: Hook>(
self,
hook: NH,
) -> AgentBuilder<Advanced, Balanced, Fast, HCons<NH, H>, Compactor> {
AgentBuilder {
advanced: self.advanced,
balanced: self.balanced,
fast: self.fast,
compaction_model: self.compaction_model,
tier: self.tier,
tools: self.tools,
hooks: HCons::new(hook, self.hooks),
config: self.config,
context: self.context,
prompt_cache: self.prompt_cache,
clock: self.clock,
connectivity: self.connectivity,
background_receiver: self.background_receiver,
permission_receiver: self.permission_receiver,
job_registry: self.job_registry,
context_sources: self.context_sources,
sandbox_dir: self.sandbox_dir,
blocker_resolver: self.blocker_resolver.clone(),
restore_dir: self.restore_dir,
fork_source: self.fork_source,
inherited: self.inherited,
#[cfg(feature = "skills")]
skill_registry: self.skill_registry,
}
}
/// Sets the system prompt.
///
/// The system prompt is prepended to every conversation and
/// remains stable for prompt caching.
pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.config.system_prompt = Some(prompt.into());
self
}
/// Sets the maximum number of iterations (turns).
///
/// The agent will stop and return an error if this limit is exceeded.
pub const fn max_iterations(mut self, limit: usize) -> Self {
self.config.max_iterations = limit;
self
}
/// Sets the context management policy.
pub const fn context_policy(mut self, policy: ContextPolicy) -> Self {
self.config.context_policy = policy;
self
}
/// Registers a source rendered into the tail of every request.
///
/// Sources are rendered in registration order, after the built-in ones,
/// and each is told when the request it contributed to was sent.
pub fn context_source<S: ContextSource>(mut self, source: S) -> Self {
self.context_sources.push(AnyContextSource::new(source));
self
}
/// Sets an optional persona overlay prompt.
pub fn persona_prompt(mut self, prompt: impl Into<String>) -> Self {
self.config.persona_prompt = Some(prompt.into());
self
}
/// Sets agent kind (coding or chatbot).
pub const fn agent_kind(mut self, kind: AgentKind) -> Self {
self.config.agent_kind = kind;
self
}
/// Sets the main agent's sandbox directory: its working documents are
/// supervised and its files restored after compaction.
pub fn sandbox_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
let path = path.into();
self.restore_dir = Some(path.clone());
self.sandbox_dir = Some(path);
self
}
/// Resolves `BLOCKING` mark payloads in `tasks.md`: a mark it reports
/// dead no longer holds the item — the work counts as runnable and the
/// turn cannot stop on it. Without a resolver every mark is trusted.
pub fn blocker_resolver(
mut self,
resolver: impl crate::working_docs::TaskBlockerResolver,
) -> Self {
self.blocker_resolver = Some(crate::working_docs::AnyTaskBlockerResolver::new(resolver));
self
}
/// Sets the skill registry used for runtime skill matching and activation.
#[cfg(feature = "skills")]
pub fn skill_registry(mut self, registry: Arc<SkillRegistry>) -> Self {
self.skill_registry = Some(registry);
self
}
/// Inserts or replaces a typed persistent system block.
pub fn system<T: askama::Template>(mut self, value: T) -> Self {
self.context.insert_system(&value);
self
}
/// Inserts or replaces a persistent system block with an explicit tag.
pub fn system_named(mut self, tag: impl Into<String>, content: impl Into<String>) -> Self {
self.context.insert_system_named(tag, content);
self
}
/// Whether a persistent system block with `tag` is already set.
pub(crate) fn has_system_named(&self, tag: &str) -> bool {
self.context.has_system_block(tag)
}
/// Inserts or replaces a persistent system block with raw text.
///
/// Unlike [`system`](Self::system) and [`system_named`](Self::system_named),
/// the `content` is stored verbatim without any XML wrapping. This is the
/// preferred entry point for prose system blocks (workspace descriptions,
/// runtime metadata, environment hints) where XML structure adds tokens
/// without providing semantic value.
pub fn system_text(mut self, tag: impl Into<String>, content: impl Into<String>) -> Self {
self.context.insert_system_text(tag, content);
self
}
/// Registers an MCP connection.
///
/// All tools from the MCP server will be available for the agent to use.
/// You can call this method multiple times to register multiple MCP servers.
///
/// # Example
///
/// ```rust,ignore
/// use aither_mcp::McpConnection;
///
/// // Connect to an MCP server
/// let conn = McpConnection::spawn("npx", &["-y", "@modelcontextprotocol/server-filesystem", "/"]).await?;
///
/// let agent = Agent::builder(llm)
/// .mcp(conn)
/// .build();
/// ```
///
/// # Multiple Servers
///
/// ```rust,ignore
/// let filesystem = McpConnection::spawn("npx", &["-y", "@modelcontextprotocol/server-filesystem", "/"]).await?;
/// let github = McpConnection::spawn("npx", &["-y", "@modelcontextprotocol/server-github"]).await?;
///
/// let agent = Agent::builder(llm)
/// .mcp(filesystem)
/// .mcp(github)
/// .build();
/// ```
///
/// # Loading from Configuration
///
/// ```rust,ignore
/// use aither_mcp::{McpConnection, McpServersConfig};
///
/// let config: McpServersConfig = serde_json::from_str(&config_json)?;
/// let connections = McpConnection::from_configs(&config).await?;
///
/// let mut builder = Agent::builder(llm);
/// for (_name, conn) in connections {
/// builder = builder.mcp(conn);
/// }
/// let agent = builder.build();
/// ```
#[cfg(feature = "mcp")]
pub fn mcp(mut self, conn: McpConnection) -> Self {
self.tools.register_mcp(conn);
self
}
/// Registers the terminal tool for command execution in a sandbox.
///
/// The terminal tool enables command execution with configurable permission modes
/// (sandboxed, network, unsafe). It creates its own working directory with
/// four random words and manages output storage internally.
///
/// This also captures the background task receiver for polling completed
/// background tasks during the agent loop.
///
/// # Example
///
/// ```rust,ignore
/// use aither_sandbox::{TerminalTool, ToolRegistryBuilder, permission::DenyUnsafe};
/// use std::sync::Arc;
///
/// // Create terminal tool (creates random working dir like amber-forest-thunder-pearl/)
/// let terminal_tool = TerminalTool::new_in(parent, DenyUnsafe, executor).await?;
/// let registry = Arc::new(ToolRegistryBuilder::new().build(terminal_tool.outputs_dir()));
/// let terminal_tool = terminal_tool.with_registry(registry);
///
/// let agent = Agent::builder(llm)
/// .terminal(terminal_tool)
/// .build();
/// ```
///
/// # Panics
///
/// Panics if the tool cannot be registered: another tool already uses
/// its name, or it carries no description for the model to read. Both
/// are mistakes in the calling program.
pub fn terminal<P, E>(
mut self,
terminal_tool: aither_sandbox::TerminalTool<P, E, aither_sandbox::Configured>,
) -> Self
where
P: aither_sandbox::PermissionHandler + 'static,
E: executor_core::Executor + Clone + 'static,
{
self.context.insert_system_text(
"prepared_tools",
terminal_tool
.prepared_tools_context()
.expect("terminal tools must be initialized before agent construction"),
);
let background_receiver = terminal_tool.background_receiver();
let permission_receiver = terminal_tool.permission_receiver();
let job_registry = terminal_tool.job_registry();
self.sandbox_dir = Some(terminal_tool.working_dir().clone());
self.restore_dir = Some(terminal_tool.working_dir().clone());
self.tools
.register(terminal_tool)
.expect("tool registration must succeed: duplicate name or missing description");
self.background_receiver = Some(background_receiver);
self.permission_receiver = Some(permission_receiver);
self.job_registry = Some(job_registry);
self
}
/// Sets the full agent configuration.
pub fn config(mut self, config: AgentConfig) -> Self {
self.config = config;
self
}
/// Overrides the session's prompt-cache controller.
///
/// The default derives a fresh session key per agent and retains Claude
/// breakpoints for one hour; a host with its own session identity or a
/// provider that retains prompts differently supplies the
/// [`PromptCache`](crate::context::PromptCache) it wants here.
pub fn prompt_cache(mut self, cache: crate::context::PromptCache) -> Self {
self.prompt_cache = cache;
self
}
/// Sets the Claude cache retention of the session's prompt cache,
/// keeping its session key; the cache lifetime follows the retention.
pub fn claude_cache_ttl(mut self, ttl: aither_core::llm::model::ClaudePromptCacheTtl) -> Self {
self.prompt_cache = self.prompt_cache.with_ttl(ttl);
self
}
/// Sets the conversation's cache lifetime, keeping the rest of its
/// prompt cache. Idle compaction, idle reassembly and keep-alive follow it.
pub fn cache_lifetime(mut self, lifetime: crate::context::CacheLifetime) -> Self {
self.prompt_cache = self.prompt_cache.with_lifetime(lifetime);
self
}
/// Sets the time source idle compaction, idle reassembly and cache
/// keep-alive read; the system clock by default.
pub fn clock(mut self, clock: impl crate::Clock) -> Self {
self.clock = crate::AnyClock::new(clock);
self
}
/// Ends a provider response stream in flight when the machine wakes from
/// sleep or loses its network.
///
/// The attempt fails with an [`AgentError::Llm`](crate::AgentError::Llm)
/// whose failure is
/// [`FailureKind::Network`](aither_core::llm::FailureKind::Network), so the
/// caller retries instead of sitting on a dead socket. Nothing about the
/// change reaches the agent's context.
#[cfg(feature = "connectivity")]
pub fn connectivity(mut self, connectivity: aither_connectivity::Connectivity) -> Self {
self.connectivity = crate::connectivity::Watch::new(connectivity);
self
}
/// Enables prompt-cache keep-alive while the run waits on its own
/// background commands.
///
/// `SubagentTool` sets this on child agents; ordinary agents leave it
/// off. It is a no-op unless the run's model is an Anthropic one.
pub const fn cache_keep_alive(mut self, keep_alive: crate::config::CacheKeepAlive) -> Self {
self.config.cache_keep_alive = Some(keep_alive);
self
}
/// Sets what a run does with background commands still running when the
/// model ends its turn; [`BackgroundJobPolicy::Await`] by default.
///
/// [`BackgroundJobPolicy::Await`]: crate::BackgroundJobPolicy::Await
pub const fn background_jobs(mut self, policy: crate::BackgroundJobPolicy) -> Self {
self.config.background_jobs = policy;
self
}
/// Connects the agent to an external background-task channel pair.
///
/// [`terminal`](Self::terminal) and [`dyn_terminal`](Self::dyn_terminal)
/// wire these for sandboxed execution; hosts driving an execution
/// environment of their own (or simulating one) attach the pair here so
/// the run loop waits on it the same way.
pub fn background_channels(
mut self,
receiver: BackgroundTaskReceiver,
job_registry: JobRegistry,
) -> Self {
self.background_receiver = Some(receiver);
self.job_registry = Some(job_registry);
self
}
/// Returns the definitions of the tools registered on this builder so far.
///
/// These are the definitions the built agent sends to the model, in the
/// order the tool registry holds them.
#[must_use]
pub fn tool_definitions(&self) -> Vec<ToolDefinition> {
self.tools.active_definitions()
}
/// Builds the agent.
pub fn build(self) -> Agent<Advanced, Balanced, Fast, H, Compactor> {
Agent {
warmth: crate::CacheWarmth::new(self.prompt_cache.lifetime(), self.clock.clone()),
advanced: std::sync::Arc::new(self.advanced),
balanced: std::sync::Arc::new(self.balanced),
fast: std::sync::Arc::new(self.fast),
compaction_model: self.compaction_model.map(std::sync::Arc::new),
idle_compacted: false,
session: crate::agent::SessionPhase::NotStarted,
tier: self.tier,
tools: self.tools,
hooks: self.hooks,
budget: self
.inherited
.as_ref()
.map_or_else(crate::context::ContextBudget::default, |inherited| {
inherited.budget
}),
prompt_cache: self.prompt_cache,
context_sources: self.context_sources,
reassembled: false,
pending_compaction: None,
completed_compaction: None,
tool_results: std::collections::VecDeque::new(),
config: self.config,
context: self.context,
initialized: self.inherited.is_some(),
profile: self.inherited.and_then(|inherited| inherited.profile),
background_receiver: self.background_receiver,
permission_receiver: self.permission_receiver,
job_registry: self.job_registry,
detached_task_ids: std::collections::HashSet::new(),
sandbox_dir: self.sandbox_dir,
blocker_resolver: self.blocker_resolver.clone(),
restore_dir: self.restore_dir,
fork_source: self.fork_source,
connectivity: self.connectivity,
last_request: None,
cache_keep_alive: crate::agent::CacheKeepAliveState::default(),
cache_stats: crate::CacheStats::new(),
#[cfg(feature = "skills")]
skill_registry: self.skill_registry,
#[cfg(feature = "skills")]
active_skills: crate::context::ActiveSkills::new(),
#[cfg(feature = "skills")]
active_allowed_tools: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Cow;
#[cfg(feature = "skills")]
use aither_skills::{Skill, SkillRegistry};
use schemars::JsonSchema;
use serde::Deserialize;
use futures_core::Stream;
// Mock error type for testing
#[derive(Debug)]
struct MockError;
impl std::fmt::Display for MockError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "mock error")
}
}
impl std::error::Error for MockError {}
impl aither_core::llm::Classify for MockError {
fn failure(&self) -> aither_core::llm::Failure {
aither_core::llm::Failure::permanent()
}
}
// Mock LLM for testing
#[derive(Clone)]
struct MockLlm;
impl LanguageModel for MockLlm {
type Error = MockError;
fn respond(
&self,
_request: aither_core::llm::LLMRequest,
) -> impl Stream<Item = Result<aither_core::llm::Event, Self::Error>> + Send {
futures_lite::stream::empty()
}
fn profile(
&self,
) -> impl std::future::Future<
Output = Result<aither_core::llm::model::Profile, Self::Error>,
> + Send {
std::future::ready(Ok(aither_core::llm::model::Profile::new(
"mock",
"test",
"mock-model",
"A mock model for testing",
100_000,
)))
}
}
// Mock tool
struct MockTool;
/// Does nothing, for tests that only care that a tool was registered.
#[derive(Debug, JsonSchema, Deserialize)]
struct MockArgs;
impl Tool for MockTool {
fn name(&self) -> Cow<'static, str> {
"mock_tool".into()
}
type Arguments = MockArgs;
type Res = aither_core::llm::ToolResult;
fn call(
&self,
_args: Self::Arguments,
_cx: aither_core::llm::ToolContext,
) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
std::future::ready(Ok(aither_core::llm::ToolResult::text("ok")))
}
}
// Mock hook
struct MockHook;
impl Hook for MockHook {}
#[test]
fn test_builder_basic() {
let agent = AgentBuilder::new(MockLlm).build();
assert_eq!(agent.tools.definitions(), []);
}
#[test]
fn public_model_tier_configures_agent_builder() {
let agent = AgentBuilder::new(MockLlm)
.tier(crate::ModelTier::Balanced)
.build();
assert_eq!(agent.tier, crate::ModelTier::Balanced);
}
#[test]
fn test_builder_with_tool() {
let agent = AgentBuilder::new(MockLlm).tool(MockTool).build();
assert_eq!(agent.tools.definitions().len(), 1);
}
#[test]
fn test_builder_with_system_prompt() {
let agent = AgentBuilder::new(MockLlm)
.system_prompt("You are helpful.")
.build();
assert_eq!(
agent.config.system_prompt,
Some("You are helpful.".to_string())
);
}
#[test]
fn test_builder_with_hook() {
let _agent = AgentBuilder::new(MockLlm).hook(MockHook).build();
// Type check: agent has HCons<MockHook, ()> as hook type
}
#[test]
fn test_builder_with_multiple_hooks() {
let _agent = AgentBuilder::new(MockLlm)
.hook(MockHook)
.hook(MockHook)
.build();
// Type check: agent has HCons<MockHook, HCons<MockHook, ()>>
}
#[test]
fn test_builder_max_iterations() {
let agent = AgentBuilder::new(MockLlm).max_iterations(100).build();
assert_eq!(agent.config.max_iterations, 100);
}
#[test]
fn test_builder_default_config() {
let agent = AgentBuilder::new(MockLlm).build();
assert_eq!(
agent.config.max_iterations,
AgentConfig::default().max_iterations
);
}
#[cfg(feature = "skills")]
#[test]
fn test_builder_preserves_skill_registry() {
let mut registry = SkillRegistry::new();
registry.register(Skill {
name: "code-review".to_string(),
description: "Review code carefully".to_string(),
instructions: "Use a review checklist.".to_string(),
allowed_tools: Some(vec!["mock_tool".to_string()]),
resources: std::collections::HashMap::new(),
});
let agent = AgentBuilder::new(MockLlm)
.skill_registry(Arc::new(registry))
.build();
assert!(agent.skill_registry.is_some());
}
#[cfg(feature = "skills")]
#[test]
fn test_runtime_skill_activation_is_disabled() {
let mut registry = SkillRegistry::new();
registry.register(Skill {
name: "code-review".to_string(),
description: "Review code carefully".to_string(),
instructions: "Use a review checklist.".to_string(),
allowed_tools: Some(vec!["mock_tool".to_string()]),
resources: std::collections::HashMap::new(),
});
let mut agent = AgentBuilder::new(MockLlm)
.skill_registry(Arc::new(registry))
.build();
let events = agent.activate_skills_for_prompt("please review this patch");
assert!(events.is_empty());
assert!(agent.active_skills.is_empty());
assert!(agent.active_allowed_tools.is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_subagent_gets_no_working_document_supervision_but_keeps_file_restore() {
use aither_sandbox::permission::NoopPermissionHandler;
use aither_sandbox::{SubagentGrant, TerminalTool, ToolRegistryBuilder};
use executor_core::tokio::TokioGlobal;
let source = tempfile::tempdir().unwrap();
let cache = tempfile::tempdir().unwrap();
let session = tempfile::tempdir().unwrap();
let binary = crate::test_support::compile_baseline_fixture(source.path()).await;
let distribution = crate::test_support::fixture_distribution(&binary, "1.0.0").await;
let terminal = TerminalTool::new_exact(session.path(), NoopPermissionHandler, TokioGlobal)
.await
.unwrap()
.initialize_tools(&distribution, cache.path())
.await
.unwrap();
let registry =
std::sync::Arc::new(ToolRegistryBuilder::new().build(terminal.outputs_dir()));
let terminal = terminal.with_registry(registry);
let subagent = terminal
.binding()
.launcher()
.create(SubagentGrant::new(), None, None)
.await
.unwrap();
let space = subagent.working_dir().clone();
let main = AgentBuilder::new(MockLlm).dyn_terminal(terminal.clone().to_dyn());
assert!(
main.sandbox_dir.is_some(),
"the main agent supervises its working documents"
);
let main = AgentBuilder::new(MockLlm).terminal(terminal);
assert!(main.sandbox_dir.is_some());
let child = AgentBuilder::new(MockLlm).dyn_terminal(subagent);
assert!(
child.sandbox_dir.is_none(),
"a subagent's space is not supervised like the main agent's"
);
assert_eq!(
child.restore_dir,
Some(space),
"a subagent's files are restored after compaction"
);
}
}