1use crate::agent::Harness;
68use crate::agents_def::Specialties;
69use crate::approval::ApprovalGate;
70use crate::config::{builtin_config, LimitsConfig, McpServerConfig, ObservabilityConfig};
71use crate::guardrails::Guardrails;
72use crate::mcp::{var_ref_names, McpManager};
73use crate::observability::Recorder;
74use crate::router::{RoutedModel, Router};
75use crate::secrets::NoSecretStore;
76use crate::session::{AgentState, SessionStore};
77use crate::specialty_turn::TurnKind;
78use crate::tools::sandbox::Executor;
79use crate::tools::{exec, files, search, web, ToolRegistry};
80use crate::turn::final_answer;
81use crate::types::Message;
82use indexmap::IndexMap;
83use serde_json::{json, Map, Value};
84use std::collections::HashMap;
85use std::path::{Path, PathBuf};
86use std::sync::Arc;
87use std::time::Duration;
88
89pub use crate::agent::{CancelToken, HarnessError, TurnEvent};
93pub use crate::approval::ApprovalPreview;
94pub use crate::config::{EgressMode, GuardrailsConfig, IngressMode};
95pub use crate::limits::{LimitHit, LimitKind};
96pub use crate::memory::embeddings::Embedder;
97pub use crate::tools::{Tool, ToolContext, ToolError};
98pub use crate::turn::TurnSummary;
99pub use crate::types::{ApprovalMode, Role, ToolCall, ToolResult, ToolSpec, Usage};
100pub use crate::vault::SecretRequest;
101pub use providers::Provider;
102
103#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
106pub enum Builtins {
107 #[default]
109 None,
110 ReadOnly,
112 Files,
114 All,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
121pub enum BuildError {
122 #[error("no provider was given; call AgentBuilder::provider")]
123 MissingProvider,
124 #[error("no workspace was given; call AgentBuilder::workspace")]
125 MissingWorkspace,
126 #[error("could not open the workspace {path}: {detail}")]
127 Workspace { path: String, detail: String },
128 #[error("could not register a tool: {0}")]
129 Tool(String),
130 #[error("could not open the trace directory: {0}")]
131 Trace(String),
132 #[error("MCP server '{name}' failed to start: {reason}")]
133 Mcp { name: String, reason: String },
134 #[error("a session to resume needs memory; call AgentBuilder::memory")]
135 SessionWithoutMemory,
136 #[error("no session '{0}' in memory")]
137 SessionNotFound(String),
138 #[error("memory could not be read: {0}")]
139 Memory(String),
140 #[error("no model named '{0}'; add it with AgentBuilder::model")]
141 UnknownModel(String),
142 #[error("the secret {name} was refused: {reason}")]
145 Secret { name: String, reason: String },
146}
147
148#[derive(Debug, Clone, PartialEq, thiserror::Error)]
150pub enum RunError {
151 #[error(transparent)]
153 Harness(#[from] HarnessError),
154 #[error("no skill named '{0}'")]
156 UnknownSkill(String),
157 #[error("no specialist named '{0}'")]
160 UnknownSpecialist(String),
161}
162
163type Approver = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
166
167type SecretAsker = Box<dyn Fn(&SecretRequest) -> Option<String> + Send + Sync>;
169
170pub struct AgentBuilder {
172 provider: Option<Arc<dyn Provider>>,
173 workspace: Option<PathBuf>,
174 system: Option<String>,
175 builtins: Builtins,
176 tools: Vec<Box<dyn Tool>>,
177 approval: ApprovalMode,
178 approver: Option<Approver>,
179 limits: LimitsConfig,
180 guardrails: GuardrailsConfig,
181 context_window: u64,
182 max_output_tokens: u32,
183 trace_dir: Option<PathBuf>,
184 tool_timeout: Duration,
185 mcp_servers: Vec<(String, McpServer)>,
186 memory: Option<Memory>,
187 session: Option<String>,
188 skill_dirs: Vec<PathBuf>,
189 subagents: Option<SubAgents>,
190 models: IndexMap<String, Model>,
191 triage: Option<(String, String)>,
192 otel: Option<Otel>,
193 on_limit: Option<crate::limits::LimitPrompt>,
194 on_secret: Option<SecretAsker>,
195 secrets: Vec<(String, String)>,
197}
198
199impl Default for AgentBuilder {
200 fn default() -> Self {
201 let config = builtin_config();
202 Self {
203 provider: None,
204 workspace: None,
205 system: None,
206 builtins: Builtins::None,
207 tools: Vec::new(),
208 approval: ApprovalMode::Ask,
209 approver: None,
210 max_output_tokens: config.limits.max_output_tokens,
211 tool_timeout: Duration::from_secs(config.limits.tool_timeout_s),
212 limits: config.limits,
213 guardrails: config.guardrails,
214 context_window: DEFAULT_CONTEXT_WINDOW,
215 trace_dir: None,
216 mcp_servers: Vec::new(),
217 memory: None,
218 session: None,
219 skill_dirs: Vec::new(),
220 subagents: None,
221 models: IndexMap::new(),
222 triage: None,
223 otel: None,
224 on_limit: None,
225 on_secret: None,
226 secrets: Vec::new(),
227 }
228 }
229}
230
231pub const DEFAULT_CONTEXT_WINDOW: u64 = 128_000;
234
235impl AgentBuilder {
236 pub fn provider(mut self, provider: Arc<dyn Provider>) -> Self {
239 self.provider = Some(provider);
240 self
241 }
242
243 pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
246 self.workspace = Some(path.into());
247 self
248 }
249
250 pub fn system_prompt(mut self, text: impl Into<String>) -> Self {
253 self.system = Some(text.into());
254 self
255 }
256
257 pub fn builtins(mut self, builtins: Builtins) -> Self {
259 self.builtins = builtins;
260 self
261 }
262
263 pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
265 self.tools.push(Box::new(tool));
266 self
267 }
268
269 pub fn approval(mut self, mode: ApprovalMode) -> Self {
273 self.approval = mode;
274 self
275 }
276
277 pub fn approver(
281 mut self,
282 approver: impl Fn(&str, &ApprovalPreview) -> bool + Send + Sync + 'static,
283 ) -> Self {
284 self.approver = Some(Box::new(approver));
285 self
286 }
287
288 pub fn max_steps(mut self, steps: u32) -> Self {
290 self.limits.max_steps = steps;
291 self
292 }
293
294 pub fn max_cost_usd(mut self, usd: f64) -> Self {
297 self.limits.max_cost_usd = usd;
298 self
299 }
300
301 pub fn max_wall_clock_s(mut self, seconds: u64) -> Self {
303 self.limits.max_wall_clock_s = seconds;
304 self
305 }
306
307 pub fn tool_timeout(mut self, timeout: Duration) -> Self {
309 self.tool_timeout = timeout;
310 self
311 }
312
313 pub fn context_window(mut self, tokens: u64) -> Self {
315 self.context_window = tokens;
316 self
317 }
318
319 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
321 self.max_output_tokens = tokens;
322 self
323 }
324
325 pub fn guardrails(mut self, guardrails: GuardrailsConfig) -> Self {
328 self.guardrails = guardrails;
329 self
330 }
331
332 pub fn trace_dir(mut self, dir: impl Into<PathBuf>) -> Self {
335 self.trace_dir = Some(dir.into());
336 self
337 }
338
339 pub fn mcp_server(mut self, name: impl Into<String>, server: McpServer) -> Self {
344 self.mcp_servers.push((name.into(), server));
345 self
346 }
347
348 pub fn memory(mut self, memory: Memory) -> Self {
353 self.memory = Some(memory);
354 self
355 }
356
357 pub fn session(mut self, id: impl Into<String>) -> Self {
360 self.session = Some(id.into());
361 self
362 }
363
364 pub fn skills_dir(mut self, dir: impl Into<PathBuf>) -> Self {
371 self.skill_dirs.push(dir.into());
372 self
373 }
374
375 pub fn subagents(mut self, subagents: SubAgents) -> Self {
377 self.subagents = Some(subagents);
378 self
379 }
380
381 pub fn model(mut self, name: impl Into<String>, model: Model) -> Self {
385 self.models.insert(name.into(), model);
386 self
387 }
388
389 pub fn triage(mut self, cheap: impl Into<String>, frontier: impl Into<String>) -> Self {
395 self.triage = Some((cheap.into(), frontier.into()));
396 self
397 }
398
399 pub fn otel(mut self, otel: Otel) -> Self {
405 self.otel = Some(otel);
406 self
407 }
408
409 pub fn on_limit(
416 mut self,
417 decide: impl Fn(&LimitHit) -> Option<u32> + Send + Sync + 'static,
418 ) -> Self {
419 self.on_limit = Some(Box::new(decide));
420 self
421 }
422
423 pub fn on_secret_request(
431 mut self,
432 answer: impl Fn(&SecretRequest) -> Option<String> + Send + Sync + 'static,
433 ) -> Self {
434 self.on_secret = Some(Box::new(answer));
435 self
436 }
437
438 pub fn secret(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
445 self.secrets.push((name.into(), value.into()));
446 self
447 }
448
449 pub fn build(self) -> Result<Agent, BuildError> {
453 let router = self.router()?;
454 let provider = self.provider.ok_or(BuildError::MissingProvider)?;
455 let workspace = self.workspace.ok_or(BuildError::MissingWorkspace)?;
456 let mut context = ToolContext::new(&workspace).map_err(|error| BuildError::Workspace {
457 path: workspace.display().to_string(),
458 detail: error.to_string(),
459 })?;
460 context.policy.timeout = self.tool_timeout;
461 context.executor = Executor::Subprocess;
462 for (name, value) in &self.secrets {
463 let refused = |reason: &str| BuildError::Secret {
464 name: name.clone(),
465 reason: reason.to_owned(),
466 };
467 if !crate::vault::valid_name(name) {
468 return Err(refused("not a valid environment variable name"));
469 }
470 let answer = crate::vault::SecretAnswer {
471 value: value.clone(),
472 remember: false,
473 };
474 context.secrets.accept(name, answer).map_err(|_| {
475 refused(&format!(
476 "shorter than {} characters",
477 crate::vault::MIN_SECRET_CHARS
478 ))
479 })?;
480 }
481
482 let registry = registry_for(self.builtins);
483 for tool in self.tools {
484 registry.register(tool).map_err(BuildError::Tool)?;
485 }
486
487 let store = self.memory.as_ref().map(|memory| memory.store.clone());
488 let state = match (&self.session, &store) {
489 (None, _) => AgentState::new(),
490 (Some(_), None) => return Err(BuildError::SessionWithoutMemory),
491 (Some(id), Some(store)) => store
492 .load(id)
493 .map_err(|error| BuildError::Memory(error.0))?
494 .ok_or_else(|| BuildError::SessionNotFound(id.clone()))?,
495 };
496 if let Some(memory) = &self.memory {
497 let (episodes, sessions, days) = memory.retention;
498 store
499 .as_ref()
500 .expect("memory gives a store")
501 .enforce_retention(episodes, sessions, days)
502 .map_err(|error| BuildError::Memory(error.0))?;
503 for tool in [
504 Box::new(crate::tools::memory::RememberTool) as Box<dyn Tool>,
505 Box::new(crate::tools::memory::RecallTool),
506 ] {
507 registry.register(tool).map_err(BuildError::Tool)?;
508 }
509 }
510 context.memory = store.clone();
511
512 let skills = Arc::new(crate::skills::discover_in(&self.skill_dirs));
515 if !skills.is_empty() {
516 context.policy.allow(
517 self.skill_dirs
518 .iter()
519 .filter(|dir| dir.is_dir())
520 .filter_map(|dir| std::fs::canonicalize(dir).ok())
521 .collect::<Vec<_>>(),
522 );
523 registry
524 .register(Box::new(crate::tools::skills::UseSkillTool))
525 .map_err(BuildError::Tool)?;
526 }
527 context.skills = Arc::clone(&skills);
528
529 let config = builtin_config();
531 let mut agents = crate::config::AgentsConfig {
532 enabled: false,
533 ..config.agents.clone()
534 };
535 let mut notices = Vec::new();
536 if let Some(subagents) = &self.subagents {
537 agents = crate::config::AgentsConfig {
538 enabled: true,
539 max_depth: subagents.max_depth,
540 max_steps: subagents.max_steps.min(self.limits.max_steps.max(1)),
541 max_parallel: subagents
542 .max_parallel
543 .clamp(1, crate::config::MAX_PARALLEL_CEILING),
544 };
545 let mut specialties = if subagents.built_ins {
546 Specialties::built_in()
547 } else {
548 Specialties::default()
549 };
550 for dir in &subagents.dirs {
551 specialties.add_user_dir(dir);
552 }
553 notices.extend(specialties.notices.iter().cloned());
554 context.specialties = Arc::new(specialties);
555 registry
556 .register(Box::new(crate::tools::delegate::DelegateTool))
557 .map_err(BuildError::Tool)?;
558 }
559
560 let tracer = self
561 .otel
562 .as_ref()
563 .map(|otel| crate::otel::Tracer::to(otel.destination.clone()))
564 .unwrap_or_default();
565
566 if let Some(answer) = self.on_secret {
567 context
568 .secrets
569 .set_prompt(Some(Box::new(move |request: &SecretRequest| {
570 answer(request).map(|value| crate::vault::SecretAnswer {
571 value,
572 remember: false,
573 })
574 })));
575 registry
576 .register(Box::new(crate::tools::secret::RequestSecretTool))
577 .map_err(BuildError::Tool)?;
578 }
579 let mut session_limits = crate::limits::SessionLimits::default();
580 session_limits.prompt = self.on_limit;
581
582 let mcp = start_mcp(&self.mcp_servers, ®istry)?;
583
584 let recorder = match &self.trace_dir {
585 None => Recorder::disabled(),
586 Some(dir) => {
587 std::fs::create_dir_all(dir)
588 .map_err(|error| BuildError::Trace(error.to_string()))?;
589 let defaults = builtin_config().observability;
590 Recorder::from_config(&ObservabilityConfig {
591 trace: true,
592 path: dir.display().to_string(),
593 otel: false,
594 ..defaults
595 })
596 }
597 }
598 .with_secrets(context.secrets.clone());
599
600 let mut limits = self.limits;
601 limits.max_output_tokens = self.max_output_tokens;
602 let mut system = self
603 .system
604 .unwrap_or_else(|| crate::prompt::BASE_IDENTITY.trim().to_owned());
605 system.push_str(&crate::prompt::skills_section(
606 skills.values().map(AsRef::as_ref),
607 ));
608 let mut harness = Harness {
609 provider,
610 router,
611 tracer,
612 registry,
613 context,
614 limits,
615 agents,
616 system: Message {
617 role: Role::System,
618 content: system,
619 tool_calls: Vec::new(),
620 tool_call_id: None,
621 name: None,
622 },
623 max_tokens: self.max_output_tokens,
624 session_limits,
625 context_window: self.context_window,
626 gate: ApprovalGate::new(self.approval, self.approver),
627 guardrails: Guardrails::new(&self.guardrails),
628 recorder,
629 mcp,
630 memory: store,
631 cancel: Default::default(),
632 subagents: Default::default(),
633 };
634 harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
635 harness.gate.queue.watch(harness.cancel.clone());
636 harness
637 .context
638 .secrets
639 .set_queue(harness.gate.queue.clone());
640 Ok(Agent {
641 harness,
642 conversation: Conversation(state),
643 notices,
644 })
645 }
646
647 fn router(&self) -> Result<Router, BuildError> {
650 if self.models.is_empty() {
651 return match &self.triage {
652 Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
653 None => Ok(Router::default()),
654 };
655 }
656 let (triage, cheap, frontier) = match &self.triage {
657 Some((cheap, frontier)) => {
658 for name in [cheap, frontier] {
659 if !self.models.contains_key(name) {
660 return Err(BuildError::UnknownModel(name.clone()));
661 }
662 }
663 (true, cheap.as_str(), frontier.as_str())
664 }
665 None => (false, "", ""),
666 };
667 let window = self.context_window;
668 let output = self.max_output_tokens;
669 let models: HashMap<String, RoutedModel> = self
670 .models
671 .iter()
672 .map(|(name, model)| {
673 (
674 name.clone(),
675 RoutedModel {
676 reference: name.clone(),
677 provider: Arc::clone(&model.provider),
678 max_tokens: model.max_output_tokens.unwrap_or(output),
679 context_window: model.context_window.unwrap_or(window),
680 output_setting: "max_output_tokens".to_owned(),
681 },
682 )
683 })
684 .collect();
685 Ok(Router::new(
686 triage,
687 cheap,
688 frontier,
689 Box::new(move |name| {
690 models
691 .get(name)
692 .cloned()
693 .ok_or_else(|| format!("no model named '{name}'"))
694 }),
695 ))
696 }
697}
698
699#[derive(Debug, Clone)]
709pub struct SubAgents {
710 max_depth: u32,
711 max_steps: u32,
712 max_parallel: u32,
713 built_ins: bool,
714 dirs: Vec<PathBuf>,
715}
716
717impl Default for SubAgents {
718 fn default() -> Self {
719 let agents = builtin_config().agents;
720 Self {
721 max_depth: agents.max_depth,
722 max_steps: agents.max_steps,
723 max_parallel: agents.max_parallel,
724 built_ins: true,
725 dirs: Vec::new(),
726 }
727 }
728}
729
730impl SubAgents {
731 pub fn new() -> Self {
734 Self::default()
735 }
736
737 pub fn max_depth(mut self, depth: u32) -> Self {
739 self.max_depth = depth;
740 self
741 }
742
743 pub fn max_steps(mut self, steps: u32) -> Self {
745 self.max_steps = steps;
746 self
747 }
748
749 pub fn max_parallel(mut self, parallel: u32) -> Self {
751 self.max_parallel = parallel;
752 self
753 }
754
755 pub fn without_built_ins(mut self) -> Self {
757 self.built_ins = false;
758 self
759 }
760
761 pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
767 self.dirs.push(dir.into());
768 self
769 }
770}
771
772#[derive(Clone)]
774pub struct Model {
775 provider: Arc<dyn Provider>,
776 context_window: Option<u64>,
777 max_output_tokens: Option<u32>,
778}
779
780impl std::fmt::Debug for Model {
781 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
782 f.debug_struct("Model")
783 .field("provider", &self.provider.name())
784 .field("model", &self.provider.model())
785 .field("context_window", &self.context_window)
786 .field("max_output_tokens", &self.max_output_tokens)
787 .finish()
788 }
789}
790
791impl Model {
792 pub fn new(provider: Arc<dyn Provider>) -> Self {
794 Self {
795 provider,
796 context_window: None,
797 max_output_tokens: None,
798 }
799 }
800
801 pub fn context_window(mut self, tokens: u64) -> Self {
803 self.context_window = Some(tokens);
804 self
805 }
806
807 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
809 self.max_output_tokens = Some(tokens);
810 self
811 }
812}
813
814#[derive(Debug, Clone)]
816pub struct Otel {
817 destination: crate::otel::Destination,
818}
819
820impl Otel {
821 pub fn otlp(traces_url: impl Into<String>) -> Self {
824 Self {
825 destination: crate::otel::Destination::Otlp {
826 url: traces_url.into(),
827 headers: Vec::new(),
828 timeout: Duration::from_secs(10),
829 },
830 }
831 }
832
833 pub fn console() -> Self {
835 Self {
836 destination: crate::otel::Destination::Console,
837 }
838 }
839
840 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
842 if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
843 headers.push((name.into(), value.into()));
844 }
845 self
846 }
847
848 pub fn timeout(mut self, timeout: Duration) -> Self {
850 if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
851 *limit = timeout;
852 }
853 self
854 }
855}
856
857fn start_mcp(
860 servers: &[(String, McpServer)],
861 registry: &ToolRegistry,
862) -> Result<Option<Arc<McpManager>>, BuildError> {
863 if servers.is_empty() {
864 return Ok(None);
865 }
866 let manager = Arc::new(McpManager::empty(&builtin_config()));
867 manager.attach(registry);
868 let mut seen: Vec<&str> = Vec::new();
869 for (name, server) in servers {
870 let failed = |reason: String| BuildError::Mcp {
871 name: name.clone(),
872 reason,
873 };
874 if seen.contains(&name.as_str()) {
875 return Err(failed("another server was given the same name".to_owned()));
876 }
877 seen.push(name);
878 let mut config = server.config.clone();
879 config.resolve_transport().map_err(failed)?;
880 manager
881 .start_server(
882 name,
883 &config,
884 &server.literal_refs(),
885 &NoSecretStore,
886 config.connect_timeout_s,
887 )
888 .map_err(failed)?;
889 let (_, collisions) = manager.mount(name);
890 if !collisions.is_empty() {
891 return Err(BuildError::Tool(format!(
892 "MCP server '{name}' offers tools already taken: {}",
893 collisions.join(", ")
894 )));
895 }
896 }
897 Ok(Some(manager))
898}
899
900#[derive(Debug, Clone)]
905pub struct McpServer {
906 config: McpServerConfig,
907}
908
909impl McpServer {
910 fn from(value: Value) -> Self {
911 Self {
912 config: serde_json::from_value(value).expect("a server config always deserializes"),
913 }
914 }
915
916 pub fn stdio<S: Into<String>>(
920 command: impl Into<String>,
921 args: impl IntoIterator<Item = S>,
922 ) -> Self {
923 let args: Vec<String> = args.into_iter().map(Into::into).collect();
924 Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
925 }
926
927 pub fn http(url: impl Into<String>) -> Self {
929 Self::from(json!({"url": url.into(), "transport": "http"}))
930 }
931
932 pub fn sse(url: impl Into<String>) -> Self {
934 Self::from(json!({"url": url.into(), "transport": "sse"}))
935 }
936
937 pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
939 self.config.env.insert(name.into(), value.into());
940 self
941 }
942
943 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
945 self.config.headers.insert(name.into(), value.into());
946 self
947 }
948
949 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
951 self.config.connect_timeout_s = timeout.as_secs_f64();
952 self
953 }
954
955 pub fn call_timeout(mut self, timeout: Duration) -> Self {
957 self.config.call_timeout_s = timeout.as_secs_f64();
958 self
959 }
960
961 pub fn max_result_chars(mut self, chars: usize) -> Self {
963 self.config.max_result_chars = chars;
964 self
965 }
966
967 fn literal_refs(&self) -> HashMap<String, String> {
970 let config = &self.config;
971 config
972 .args
973 .iter()
974 .chain(config.env.values())
975 .chain(config.url.iter())
976 .chain(config.headers.values())
977 .flat_map(|text| var_ref_names(text))
978 .map(|name| (name.clone(), format!("${{{name}}}")))
979 .collect()
980 }
981}
982
983#[derive(Clone)]
987pub struct Memory {
988 store: SessionStore,
989 retention: (i64, i64, f64),
990}
991
992impl std::fmt::Debug for Memory {
993 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
994 f.debug_struct("Memory")
995 .field("retention", &self.retention)
996 .finish_non_exhaustive()
997 }
998}
999
1000impl Memory {
1001 pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1004 Self::wrap(SessionStore::open(path.as_ref()))
1005 }
1006
1007 pub fn open_with(
1011 path: impl AsRef<Path>,
1012 embedder: Arc<dyn Embedder>,
1013 ) -> Result<Self, BuildError> {
1014 Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
1015 }
1016
1017 pub fn in_memory() -> Result<Self, BuildError> {
1019 Self::open(":memory:")
1020 }
1021
1022 fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
1023 let memory = builtin_config().memory;
1024 Ok(Self {
1025 store: store.map_err(|error| BuildError::Memory(error.0))?,
1026 retention: (
1027 memory.retention_max_episodes,
1028 memory.retention_max_sessions,
1029 memory.retention_max_age_days,
1030 ),
1031 })
1032 }
1033
1034 pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
1038 self.retention = (episodes, sessions, max_age_days);
1039 self
1040 }
1041
1042 pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
1044 Ok(self
1045 .store
1046 .recent_sessions(limit)
1047 .map_err(|error| BuildError::Memory(error.0))?
1048 .into_iter()
1049 .map(|session| (session.session_id, session.title))
1050 .collect())
1051 }
1052
1053 pub fn store(&self) -> &SessionStore {
1056 &self.store
1057 }
1058}
1059
1060fn registry_for(builtins: Builtins) -> ToolRegistry {
1061 let registry = ToolRegistry::new();
1062 let mut tools: Vec<Box<dyn Tool>> = Vec::new();
1063 if builtins != Builtins::None {
1064 tools.push(Box::new(files::ReadFileTool));
1065 tools.push(Box::new(files::ListDirTool));
1066 tools.push(Box::new(search::SearchFilesTool));
1067 tools.push(Box::new(search::FindFilesTool));
1068 }
1069 if matches!(builtins, Builtins::Files | Builtins::All) {
1070 tools.push(Box::new(files::WriteFileTool));
1071 tools.push(Box::new(files::EditFileTool));
1072 }
1073 if builtins == Builtins::All {
1074 tools.push(Box::new(exec::RunCommandTool));
1075 tools.push(Box::new(exec::PythonExecTool));
1076 tools.push(Box::new(web::WebFetchTool));
1077 }
1078 for tool in tools {
1079 registry
1080 .register(tool)
1081 .expect("built-in tool names are unique");
1082 }
1083 registry
1084}
1085
1086#[derive(Debug, Clone, PartialEq)]
1088pub struct RunResult {
1089 pub answer: String,
1092 pub output: String,
1095 pub turn: Option<TurnSummary>,
1097 pub usage: Usage,
1099}
1100
1101#[derive(Debug, Clone, PartialEq, Eq)]
1104pub enum Turn {
1105 Goal(String),
1107 Skill { name: String, task: String },
1110 Specialist {
1114 name: String,
1115 task: String,
1116 with_context: bool,
1117 },
1118}
1119
1120impl Turn {
1121 pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
1122 Self::Skill {
1123 name: name.into(),
1124 task: task.into(),
1125 }
1126 }
1127
1128 pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
1129 Self::Specialist {
1130 name: name.into(),
1131 task: task.into(),
1132 with_context: false,
1133 }
1134 }
1135
1136 pub fn with_context(mut self) -> Self {
1138 if let Self::Specialist { with_context, .. } = &mut self {
1139 *with_context = true;
1140 }
1141 self
1142 }
1143}
1144
1145impl From<&str> for Turn {
1146 fn from(goal: &str) -> Self {
1147 Self::Goal(goal.to_owned())
1148 }
1149}
1150
1151impl From<String> for Turn {
1152 fn from(goal: String) -> Self {
1153 Self::Goal(goal)
1154 }
1155}
1156
1157impl From<&String> for Turn {
1158 fn from(goal: &String) -> Self {
1159 Self::Goal(goal.clone())
1160 }
1161}
1162
1163pub struct Agent {
1166 harness: Harness,
1167 conversation: Conversation,
1168 notices: Vec<String>,
1170}
1171
1172impl Agent {
1173 pub fn builder() -> AgentBuilder {
1174 AgentBuilder::default()
1175 }
1176
1177 pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1179 self.run_with_events(turn, |_| {}).await
1180 }
1181
1182 pub async fn run_with_events(
1185 &mut self,
1186 turn: impl Into<Turn>,
1187 mut on_event: impl FnMut(TurnEvent<'_>),
1188 ) -> Result<RunResult, RunError> {
1189 let (kind, prompt, display) = match turn.into() {
1190 Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
1191 Turn::Skill { name, task } => {
1192 let skill = self
1193 .harness
1194 .context
1195 .skills
1196 .get(&name)
1197 .cloned()
1198 .ok_or(RunError::UnknownSkill(name.clone()))?;
1199 let display = format!("/{name} {task}").trim_end().to_owned();
1200 (TurnKind::Skill(skill), task, display)
1201 }
1202 Turn::Specialist {
1203 name,
1204 task,
1205 with_context,
1206 } => {
1207 if !self.harness.agents.enabled
1208 || self.harness.context.specialties.get(&name).is_none()
1209 {
1210 return Err(RunError::UnknownSpecialist(name));
1211 }
1212 let display = format!("/agent {name} {task}");
1213 (TurnKind::Agent { name, with_context }, task, display)
1214 }
1215 };
1216 let output = self
1217 .harness
1218 .run_kind(
1219 &mut self.conversation.0,
1220 &kind,
1221 &prompt,
1222 &display,
1223 &mut on_event,
1224 )
1225 .await;
1226 if let Some(store) = &self.harness.memory {
1229 let _ = store.persist(&self.conversation.0);
1230 }
1231 let output = output?;
1232 Ok(RunResult {
1233 answer: final_answer(&self.conversation.0.messages).to_owned(),
1234 output,
1235 turn: self.conversation.0.last_turn.clone(),
1236 usage: self.conversation.0.usage,
1237 })
1238 }
1239
1240 pub fn cancel_handle(&self) -> CancelToken {
1243 self.harness.cancel.clone()
1244 }
1245
1246 pub fn conversation(&self) -> &Conversation {
1248 &self.conversation
1249 }
1250
1251 pub fn with_conversation(mut self, conversation: Conversation) -> Self {
1253 self.conversation = conversation;
1254 self
1255 }
1256
1257 pub fn session_id(&self) -> &str {
1259 self.conversation.id()
1260 }
1261
1262 pub fn secret_names(&self) -> Vec<String> {
1264 self.harness.context.secrets.names()
1265 }
1266
1267 pub fn notes(&self) -> Vec<String> {
1271 let mut notes = self.notices.clone();
1272 if let Some(mcp) = &self.harness.mcp {
1273 notes.extend(mcp.notes());
1274 }
1275 notes.extend(self.harness.tracer.note());
1276 notes
1277 }
1278
1279 pub fn skills(&self) -> Vec<String> {
1281 self.harness.context.skills.keys().cloned().collect()
1282 }
1283
1284 pub fn specialists(&self) -> Vec<String> {
1286 if !self.harness.agents.enabled {
1287 return Vec::new();
1288 }
1289 self.harness
1290 .context
1291 .specialties
1292 .names()
1293 .into_iter()
1294 .map(str::to_owned)
1295 .collect()
1296 }
1297
1298 pub fn tool_names(&self) -> Vec<String> {
1300 self.harness.registry.names()
1301 }
1302
1303 pub fn harness(&self) -> &Harness {
1306 &self.harness
1307 }
1308}
1309
1310#[derive(Debug, Clone, Default, PartialEq)]
1315pub struct Conversation(AgentState);
1316
1317#[derive(Debug, Clone, PartialEq)]
1319pub struct ConversationMessage {
1320 pub role: Role,
1321 pub text: String,
1323 pub tool_calls: Vec<ToolCall>,
1325 pub answers: Option<String>,
1327}
1328
1329impl Conversation {
1330 pub fn new() -> Self {
1332 Self::default()
1333 }
1334
1335 pub fn id(&self) -> &str {
1337 &self.0.session_id
1338 }
1339
1340 pub fn messages(&self) -> Vec<ConversationMessage> {
1342 self.0
1343 .messages
1344 .iter()
1345 .map(|message| ConversationMessage {
1346 role: message.role,
1347 text: message.content.clone(),
1348 tool_calls: message.tool_calls.clone(),
1349 answers: message.tool_call_id.clone(),
1350 })
1351 .collect()
1352 }
1353
1354 pub fn steps(&self) -> usize {
1356 self.0.step_count()
1357 }
1358
1359 pub fn usage(&self) -> Usage {
1361 self.0.usage
1362 }
1363
1364 pub fn last_turn(&self) -> Option<&TurnSummary> {
1366 self.0.last_turn.as_ref()
1367 }
1368
1369 pub fn to_json(&self) -> String {
1371 serde_json::to_string(&self.0).expect("a conversation always serializes")
1372 }
1373
1374 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1377 serde_json::from_str(json).map(Self)
1378 }
1379}
1380
1381type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1385
1386pub struct FnTool {
1389 name: String,
1390 description: String,
1391 parameters: Value,
1392 side_effecting: bool,
1393 run: Box<ToolFn>,
1394}
1395
1396impl FnTool {
1397 pub fn new(
1400 name: impl Into<String>,
1401 description: impl Into<String>,
1402 parameters: Value,
1403 run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
1404 + Send
1405 + Sync
1406 + 'static,
1407 ) -> Self {
1408 Self {
1409 name: name.into(),
1410 description: description.into(),
1411 parameters,
1412 side_effecting: false,
1413 run: Box::new(run),
1414 }
1415 }
1416
1417 pub fn side_effecting(mut self) -> Self {
1420 self.side_effecting = true;
1421 self
1422 }
1423}
1424
1425impl Tool for FnTool {
1426 fn name(&self) -> &str {
1427 &self.name
1428 }
1429
1430 fn description(&self) -> &str {
1431 &self.description
1432 }
1433
1434 fn side_effecting(&self) -> bool {
1435 self.side_effecting
1436 }
1437
1438 fn parameters(&self) -> Value {
1439 self.parameters.clone()
1440 }
1441
1442 fn execute(
1443 &self,
1444 args: &Map<String, Value>,
1445 ctx: &ToolContext,
1446 ) -> Result<ToolResult, ToolError> {
1447 match (self.run)(args, ctx) {
1448 Ok(content) => Ok(ToolResult {
1449 call_id: String::new(),
1450 name: self.name.clone(),
1451 ok: true,
1452 content,
1453 error: None,
1454 metadata: Map::new(),
1455 }),
1456 Err(message) => Err(ToolError::Raised {
1457 exception: "ToolError".to_owned(),
1458 message,
1459 }),
1460 }
1461 }
1462}
1463
1464pub mod providers {
1469 pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
1470 pub use crate::provider::google::{GoogleConfig, GoogleProvider};
1471 pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
1472 pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
1473 pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
1474 pub use crate::types::{
1475 Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
1476 };
1477}