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};
93#[cfg(feature = "agent86ui")]
94pub use crate::agent86ui::UiWait;
95pub use crate::approval::ApprovalPreview;
96pub use crate::config::{EgressMode, GuardrailsConfig, IngressMode};
97pub use crate::limits::{LimitHit, LimitKind};
98pub use crate::memory::embeddings::Embedder;
99pub use crate::tools::{Tool, ToolContext, ToolError};
100pub use crate::turn::TurnSummary;
101pub use crate::types::{ApprovalMode, Role, ToolCall, ToolResult, ToolSpec, Usage};
102pub use crate::vault::SecretRequest;
103#[cfg(feature = "agent86ui")]
106pub use agent86_ui;
107#[cfg(feature = "agent86ui")]
108pub use agent86_ui::{Action, AgentMessage, AgentMessageKind, Catalog};
109pub use providers::Provider;
110
111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
114pub enum Builtins {
115 #[default]
117 None,
118 ReadOnly,
120 Files,
122 All,
125}
126
127#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
132#[non_exhaustive]
133pub enum BuildError {
134 #[error("no provider was given; call AgentBuilder::provider")]
135 MissingProvider,
136 #[error("no workspace was given; call AgentBuilder::workspace")]
137 MissingWorkspace,
138 #[error("could not open the workspace {path}: {detail}")]
139 Workspace { path: String, detail: String },
140 #[error("could not register a tool: {0}")]
141 Tool(String),
142 #[error("could not open the trace directory: {0}")]
143 Trace(String),
144 #[error("MCP server '{name}' failed to start: {reason}")]
145 Mcp { name: String, reason: String },
146 #[error("a session to resume needs memory; call AgentBuilder::memory")]
147 SessionWithoutMemory,
148 #[error("no session '{0}' in memory")]
149 SessionNotFound(String),
150 #[error("memory could not be read: {0}")]
151 Memory(String),
152 #[error("no model named '{0}'; add it with AgentBuilder::model")]
153 UnknownModel(String),
154 #[error("the secret {name} was refused: {reason}")]
157 Secret { name: String, reason: String },
158 #[cfg(feature = "agent86ui")]
160 #[error("agent86UI could not be set up: {0}")]
161 Ui(String),
162}
163
164#[derive(Debug, Clone, PartialEq, thiserror::Error)]
169#[non_exhaustive]
170pub enum RunError {
171 #[error(transparent)]
173 Harness(#[from] HarnessError),
174 #[error("no skill named '{0}'")]
176 UnknownSkill(String),
177 #[error("no specialist named '{0}'")]
180 UnknownSpecialist(String),
181 #[cfg(feature = "agent86ui")]
185 #[error("the UI action was refused: {0}")]
186 UiAction(String),
187}
188
189type Approver = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
192
193type SecretAsker = Box<dyn Fn(&SecretRequest) -> Option<String> + Send + Sync>;
195
196pub struct AgentBuilder {
198 provider: Option<Arc<dyn Provider>>,
199 workspace: Option<PathBuf>,
200 system: Option<String>,
201 builtins: Builtins,
202 tools: Vec<Box<dyn Tool>>,
203 approval: ApprovalMode,
204 approver: Option<Approver>,
205 limits: LimitsConfig,
206 guardrails: GuardrailsConfig,
207 context_window: u64,
208 max_output_tokens: u32,
209 trace_dir: Option<PathBuf>,
210 tool_timeout: Duration,
211 mcp_servers: Vec<(String, McpServer)>,
212 memory: Option<Memory>,
213 session: Option<String>,
214 skill_dirs: Vec<PathBuf>,
215 subagents: Option<SubAgents>,
216 models: IndexMap<String, Model>,
217 triage: Option<(String, String)>,
218 otel: Option<Otel>,
219 on_limit: Option<crate::limits::LimitPrompt>,
220 on_secret: Option<SecretAsker>,
221 #[cfg(feature = "agent86ui")]
222 ui: Option<Ui>,
223 secrets: Vec<(String, String)>,
225}
226
227impl Default for AgentBuilder {
228 fn default() -> Self {
229 let config = builtin_config();
230 Self {
231 provider: None,
232 workspace: None,
233 system: None,
234 builtins: Builtins::None,
235 tools: Vec::new(),
236 approval: ApprovalMode::Ask,
237 approver: None,
238 max_output_tokens: config.limits.max_output_tokens,
239 tool_timeout: Duration::from_secs(config.limits.tool_timeout_s),
240 limits: config.limits,
241 guardrails: config.guardrails,
242 context_window: DEFAULT_CONTEXT_WINDOW,
243 trace_dir: None,
244 mcp_servers: Vec::new(),
245 memory: None,
246 session: None,
247 skill_dirs: Vec::new(),
248 subagents: None,
249 models: IndexMap::new(),
250 triage: None,
251 otel: None,
252 on_limit: None,
253 on_secret: None,
254 #[cfg(feature = "agent86ui")]
255 ui: None,
256 secrets: Vec::new(),
257 }
258 }
259}
260
261pub const DEFAULT_CONTEXT_WINDOW: u64 = 128_000;
264
265impl AgentBuilder {
266 pub fn provider(mut self, provider: Arc<dyn Provider>) -> Self {
269 self.provider = Some(provider);
270 self
271 }
272
273 pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
276 self.workspace = Some(path.into());
277 self
278 }
279
280 pub fn system_prompt(mut self, text: impl Into<String>) -> Self {
283 self.system = Some(text.into());
284 self
285 }
286
287 pub fn builtins(mut self, builtins: Builtins) -> Self {
289 self.builtins = builtins;
290 self
291 }
292
293 pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
295 self.tools.push(Box::new(tool));
296 self
297 }
298
299 pub fn approval(mut self, mode: ApprovalMode) -> Self {
303 self.approval = mode;
304 self
305 }
306
307 pub fn approver(
311 mut self,
312 approver: impl Fn(&str, &ApprovalPreview) -> bool + Send + Sync + 'static,
313 ) -> Self {
314 self.approver = Some(Box::new(approver));
315 self
316 }
317
318 pub fn max_steps(mut self, steps: u32) -> Self {
320 self.limits.max_steps = steps;
321 self
322 }
323
324 pub fn max_cost_usd(mut self, usd: f64) -> Self {
327 self.limits.max_cost_usd = usd;
328 self
329 }
330
331 pub fn max_wall_clock_s(mut self, seconds: u64) -> Self {
333 self.limits.max_wall_clock_s = seconds;
334 self
335 }
336
337 pub fn tool_timeout(mut self, timeout: Duration) -> Self {
339 self.tool_timeout = timeout;
340 self
341 }
342
343 pub fn context_window(mut self, tokens: u64) -> Self {
345 self.context_window = tokens;
346 self
347 }
348
349 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
351 self.max_output_tokens = tokens;
352 self
353 }
354
355 pub fn guardrails(mut self, guardrails: GuardrailsConfig) -> Self {
358 self.guardrails = guardrails;
359 self
360 }
361
362 pub fn trace_dir(mut self, dir: impl Into<PathBuf>) -> Self {
365 self.trace_dir = Some(dir.into());
366 self
367 }
368
369 pub fn mcp_server(mut self, name: impl Into<String>, server: McpServer) -> Self {
374 self.mcp_servers.push((name.into(), server));
375 self
376 }
377
378 pub fn memory(mut self, memory: Memory) -> Self {
383 self.memory = Some(memory);
384 self
385 }
386
387 pub fn session(mut self, id: impl Into<String>) -> Self {
390 self.session = Some(id.into());
391 self
392 }
393
394 pub fn skills_dir(mut self, dir: impl Into<PathBuf>) -> Self {
401 self.skill_dirs.push(dir.into());
402 self
403 }
404
405 pub fn subagents(mut self, subagents: SubAgents) -> Self {
407 self.subagents = Some(subagents);
408 self
409 }
410
411 pub fn model(mut self, name: impl Into<String>, model: Model) -> Self {
415 self.models.insert(name.into(), model);
416 self
417 }
418
419 pub fn triage(mut self, cheap: impl Into<String>, frontier: impl Into<String>) -> Self {
425 self.triage = Some((cheap.into(), frontier.into()));
426 self
427 }
428
429 pub fn otel(mut self, otel: Otel) -> Self {
435 self.otel = Some(otel);
436 self
437 }
438
439 pub fn on_limit(
446 mut self,
447 decide: impl Fn(&LimitHit) -> Option<u32> + Send + Sync + 'static,
448 ) -> Self {
449 self.on_limit = Some(Box::new(decide));
450 self
451 }
452
453 pub fn on_secret_request(
461 mut self,
462 answer: impl Fn(&SecretRequest) -> Option<String> + Send + Sync + 'static,
463 ) -> Self {
464 self.on_secret = Some(Box::new(answer));
465 self
466 }
467
468 #[cfg(feature = "agent86ui")]
476 pub fn ui(mut self, ui: Ui) -> Self {
477 self.ui = Some(ui);
478 self
479 }
480
481 pub fn secret(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
488 self.secrets.push((name.into(), value.into()));
489 self
490 }
491
492 pub fn build(self) -> Result<Agent, BuildError> {
496 let router = self.router()?;
497 let provider = self.provider.ok_or(BuildError::MissingProvider)?;
498 let workspace = self.workspace.ok_or(BuildError::MissingWorkspace)?;
499 let mut context = ToolContext::new(&workspace).map_err(|error| BuildError::Workspace {
500 path: workspace.display().to_string(),
501 detail: error.to_string(),
502 })?;
503 context.policy.timeout = self.tool_timeout;
504 context.executor = Executor::Subprocess;
505 for (name, value) in &self.secrets {
506 let refused = |reason: &str| BuildError::Secret {
507 name: name.clone(),
508 reason: reason.to_owned(),
509 };
510 if !crate::vault::valid_name(name) {
511 return Err(refused("not a valid environment variable name"));
512 }
513 let answer = crate::vault::SecretAnswer {
514 value: value.clone(),
515 remember: false,
516 };
517 context.secrets.accept(name, answer).map_err(|_| {
518 refused(&format!(
519 "shorter than {} characters",
520 crate::vault::MIN_SECRET_CHARS
521 ))
522 })?;
523 }
524
525 let registry = registry_for(self.builtins);
526 for tool in self.tools {
527 registry.register(tool).map_err(BuildError::Tool)?;
528 }
529
530 let store = self.memory.as_ref().map(|memory| memory.store.clone());
531 let state = match (&self.session, &store) {
532 (None, _) => AgentState::new(),
533 (Some(_), None) => return Err(BuildError::SessionWithoutMemory),
534 (Some(id), Some(store)) => store
535 .load(id)
536 .map_err(|error| BuildError::Memory(error.0))?
537 .ok_or_else(|| BuildError::SessionNotFound(id.clone()))?,
538 };
539 if let Some(memory) = &self.memory {
540 let (episodes, sessions, days) = memory.retention;
541 store
542 .as_ref()
543 .expect("memory gives a store")
544 .enforce_retention(episodes, sessions, days)
545 .map_err(|error| BuildError::Memory(error.0))?;
546 for tool in [
547 Box::new(crate::tools::memory::RememberTool) as Box<dyn Tool>,
548 Box::new(crate::tools::memory::RecallTool),
549 ] {
550 registry.register(tool).map_err(BuildError::Tool)?;
551 }
552 }
553 context.memory = store.clone();
554
555 let skills = Arc::new(crate::skills::discover_in(&self.skill_dirs));
558 if !skills.is_empty() {
559 context.policy.allow(
560 self.skill_dirs
561 .iter()
562 .filter(|dir| dir.is_dir())
563 .filter_map(|dir| std::fs::canonicalize(dir).ok())
564 .collect::<Vec<_>>(),
565 );
566 registry
567 .register(Box::new(crate::tools::skills::UseSkillTool))
568 .map_err(BuildError::Tool)?;
569 }
570 context.skills = Arc::clone(&skills);
571
572 let config = builtin_config();
574 let mut agents = crate::config::AgentsConfig {
575 enabled: false,
576 ..config.agents.clone()
577 };
578 let mut notices = Vec::new();
579 if let Some(subagents) = &self.subagents {
580 agents = crate::config::AgentsConfig {
581 enabled: true,
582 max_depth: subagents.max_depth,
583 max_steps: subagents.max_steps.min(self.limits.max_steps.max(1)),
584 max_parallel: subagents
585 .max_parallel
586 .clamp(1, crate::config::MAX_PARALLEL_CEILING),
587 };
588 let mut specialties = if subagents.built_ins {
589 Specialties::built_in()
590 } else {
591 Specialties::default()
592 };
593 for dir in &subagents.dirs {
594 specialties.add_user_dir(dir);
595 }
596 notices.extend(specialties.notices.iter().cloned());
597 context.specialties = Arc::new(specialties);
598 registry
599 .register(Box::new(crate::tools::delegate::DelegateTool))
600 .map_err(BuildError::Tool)?;
601 }
602
603 let tracer = self
604 .otel
605 .as_ref()
606 .map(|otel| crate::otel::Tracer::to(otel.destination.clone()))
607 .unwrap_or_default();
608
609 if let Some(answer) = self.on_secret {
610 context
611 .secrets
612 .set_prompt(Some(Box::new(move |request: &SecretRequest| {
613 answer(request).map(|value| crate::vault::SecretAnswer {
614 value,
615 remember: false,
616 })
617 })));
618 registry
619 .register(Box::new(crate::tools::secret::RequestSecretTool))
620 .map_err(BuildError::Tool)?;
621 }
622 #[cfg(feature = "agent86ui")]
623 let mut ui_session = None;
624 #[cfg(feature = "agent86ui")]
625 if let Some(ui) = self.ui {
626 if ui.catalogs.is_empty() {
627 return Err(BuildError::Ui(
628 "a renderer needs at least one catalog".into(),
629 ));
630 }
631 ui_session = Some(
632 crate::agent86ui::UiSession::new(ui.catalogs)
633 .map_err(|error| BuildError::Ui(error.to_string()))?
634 .with_egress(self.guardrails.egress)
635 .with_remote_media(ui.remote_media)
636 .with_waiter(ui.on_wait),
637 );
638 }
639 let mut session_limits = crate::limits::SessionLimits::default();
640 session_limits.prompt = self.on_limit;
641
642 let mcp = start_mcp(&self.mcp_servers, ®istry)?;
643
644 let recorder = match &self.trace_dir {
645 None => Recorder::disabled(),
646 Some(dir) => {
647 std::fs::create_dir_all(dir)
648 .map_err(|error| BuildError::Trace(error.to_string()))?;
649 let defaults = builtin_config().observability;
650 Recorder::from_config(&ObservabilityConfig {
651 trace: true,
652 path: dir.display().to_string(),
653 otel: false,
654 ..defaults
655 })
656 }
657 }
658 .with_secrets(context.secrets.clone());
659
660 let mut limits = self.limits;
661 limits.max_output_tokens = self.max_output_tokens;
662 let mut system = self
663 .system
664 .unwrap_or_else(|| crate::prompt::BASE_IDENTITY.trim().to_owned());
665 system.push_str(&crate::prompt::skills_section(
666 skills.values().map(AsRef::as_ref),
667 ));
668 let mut harness = Harness {
669 provider,
670 router,
671 tracer,
672 registry,
673 context,
674 limits,
675 agents,
676 system: Message {
677 role: Role::System,
678 content: system,
679 tool_calls: Vec::new(),
680 tool_call_id: None,
681 name: None,
682 },
683 max_tokens: self.max_output_tokens,
684 session_limits,
685 context_window: self.context_window,
686 gate: ApprovalGate::new(self.approval, self.approver),
687 guardrails: Guardrails::new(&self.guardrails),
688 recorder,
689 mcp,
690 memory: store,
691 cancel: Default::default(),
692 subagents: Default::default(),
693 };
694 #[cfg(feature = "agent86ui")]
695 if let Some(session) = ui_session {
696 harness.attach_ui(session).map_err(BuildError::Tool)?;
697 }
698 harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
699 harness.gate.queue.watch(harness.cancel.clone());
700 harness
701 .context
702 .secrets
703 .set_queue(harness.gate.queue.clone());
704 let agent = Agent {
705 harness,
706 conversation: Conversation(state),
707 notices,
708 };
709 #[cfg(feature = "agent86ui")]
711 agent.replay_surfaces();
712 Ok(agent)
713 }
714
715 fn router(&self) -> Result<Router, BuildError> {
718 if self.models.is_empty() {
719 return match &self.triage {
720 Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
721 None => Ok(Router::default()),
722 };
723 }
724 let (triage, cheap, frontier) = match &self.triage {
725 Some((cheap, frontier)) => {
726 for name in [cheap, frontier] {
727 if !self.models.contains_key(name) {
728 return Err(BuildError::UnknownModel(name.clone()));
729 }
730 }
731 (true, cheap.as_str(), frontier.as_str())
732 }
733 None => (false, "", ""),
734 };
735 let window = self.context_window;
736 let output = self.max_output_tokens;
737 let models: HashMap<String, RoutedModel> = self
738 .models
739 .iter()
740 .map(|(name, model)| {
741 (
742 name.clone(),
743 RoutedModel {
744 reference: name.clone(),
745 provider: Arc::clone(&model.provider),
746 max_tokens: model.max_output_tokens.unwrap_or(output),
747 context_window: model.context_window.unwrap_or(window),
748 output_setting: "max_output_tokens".to_owned(),
749 },
750 )
751 })
752 .collect();
753 Ok(Router::new(
754 triage,
755 cheap,
756 frontier,
757 Box::new(move |name| {
758 models
759 .get(name)
760 .cloned()
761 .ok_or_else(|| format!("no model named '{name}'"))
762 }),
763 ))
764 }
765}
766
767#[derive(Debug, Clone)]
777pub struct SubAgents {
778 max_depth: u32,
779 max_steps: u32,
780 max_parallel: u32,
781 built_ins: bool,
782 dirs: Vec<PathBuf>,
783}
784
785impl Default for SubAgents {
786 fn default() -> Self {
787 let agents = builtin_config().agents;
788 Self {
789 max_depth: agents.max_depth,
790 max_steps: agents.max_steps,
791 max_parallel: agents.max_parallel,
792 built_ins: true,
793 dirs: Vec::new(),
794 }
795 }
796}
797
798impl SubAgents {
799 pub fn new() -> Self {
802 Self::default()
803 }
804
805 pub fn max_depth(mut self, depth: u32) -> Self {
807 self.max_depth = depth;
808 self
809 }
810
811 pub fn max_steps(mut self, steps: u32) -> Self {
813 self.max_steps = steps;
814 self
815 }
816
817 pub fn max_parallel(mut self, parallel: u32) -> Self {
819 self.max_parallel = parallel;
820 self
821 }
822
823 pub fn without_built_ins(mut self) -> Self {
825 self.built_ins = false;
826 self
827 }
828
829 pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
835 self.dirs.push(dir.into());
836 self
837 }
838}
839
840#[derive(Clone)]
842pub struct Model {
843 provider: Arc<dyn Provider>,
844 context_window: Option<u64>,
845 max_output_tokens: Option<u32>,
846}
847
848impl std::fmt::Debug for Model {
849 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
850 f.debug_struct("Model")
851 .field("provider", &self.provider.name())
852 .field("model", &self.provider.model())
853 .field("context_window", &self.context_window)
854 .field("max_output_tokens", &self.max_output_tokens)
855 .finish()
856 }
857}
858
859impl Model {
860 pub fn new(provider: Arc<dyn Provider>) -> Self {
862 Self {
863 provider,
864 context_window: None,
865 max_output_tokens: None,
866 }
867 }
868
869 pub fn context_window(mut self, tokens: u64) -> Self {
871 self.context_window = Some(tokens);
872 self
873 }
874
875 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
877 self.max_output_tokens = Some(tokens);
878 self
879 }
880}
881
882#[cfg(feature = "agent86ui")]
885#[derive(Clone)]
886pub struct Ui {
887 catalogs: Vec<Catalog>,
888 remote_media: bool,
889 on_wait: Option<crate::agent86ui::UiWaiter>,
890}
891
892#[cfg(feature = "agent86ui")]
893impl std::fmt::Debug for Ui {
894 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
895 f.debug_struct("Ui")
896 .field(
897 "catalogs",
898 &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
899 )
900 .field("remote_media", &self.remote_media)
901 .field("on_wait", &self.on_wait.is_some())
902 .finish()
903 }
904}
905
906#[cfg(feature = "agent86ui")]
907impl Ui {
908 pub fn basic() -> Self {
911 Self::new([Catalog::basic().clone()])
912 }
913
914 pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
917 Self {
918 catalogs: catalogs.into_iter().collect(),
919 remote_media: false,
920 on_wait: None,
921 }
922 }
923
924 pub fn on_wait(
933 mut self,
934 answer: impl Fn(&UiWait) -> Option<Action> + Send + Sync + 'static,
935 ) -> Self {
936 self.on_wait = Some(std::sync::Arc::new(answer));
937 self
938 }
939
940 pub fn allow_remote_media(mut self) -> Self {
945 self.remote_media = true;
946 self
947 }
948
949 pub fn catalogs(&self) -> &[Catalog] {
951 &self.catalogs
952 }
953}
954
955#[derive(Debug, Clone)]
957pub struct Otel {
958 destination: crate::otel::Destination,
959}
960
961impl Otel {
962 pub fn otlp(traces_url: impl Into<String>) -> Self {
965 Self {
966 destination: crate::otel::Destination::Otlp {
967 url: traces_url.into(),
968 headers: Vec::new(),
969 timeout: Duration::from_secs(10),
970 },
971 }
972 }
973
974 pub fn console() -> Self {
976 Self {
977 destination: crate::otel::Destination::Console,
978 }
979 }
980
981 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
983 if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
984 headers.push((name.into(), value.into()));
985 }
986 self
987 }
988
989 pub fn timeout(mut self, timeout: Duration) -> Self {
991 if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
992 *limit = timeout;
993 }
994 self
995 }
996}
997
998fn start_mcp(
1001 servers: &[(String, McpServer)],
1002 registry: &ToolRegistry,
1003) -> Result<Option<Arc<McpManager>>, BuildError> {
1004 if servers.is_empty() {
1005 return Ok(None);
1006 }
1007 let manager = Arc::new(McpManager::empty(&builtin_config()));
1008 manager.attach(registry);
1009 let mut seen: Vec<&str> = Vec::new();
1010 for (name, server) in servers {
1011 let failed = |reason: String| BuildError::Mcp {
1012 name: name.clone(),
1013 reason,
1014 };
1015 if seen.contains(&name.as_str()) {
1016 return Err(failed("another server was given the same name".to_owned()));
1017 }
1018 seen.push(name);
1019 let mut config = server.config.clone();
1020 config.resolve_transport().map_err(failed)?;
1021 manager
1022 .start_server(
1023 name,
1024 &config,
1025 &server.literal_refs(),
1026 &NoSecretStore,
1027 config.connect_timeout_s,
1028 )
1029 .map_err(failed)?;
1030 let (_, collisions) = manager.mount(name);
1031 if !collisions.is_empty() {
1032 return Err(BuildError::Tool(format!(
1033 "MCP server '{name}' offers tools already taken: {}",
1034 collisions.join(", ")
1035 )));
1036 }
1037 }
1038 Ok(Some(manager))
1039}
1040
1041#[derive(Debug, Clone)]
1046pub struct McpServer {
1047 config: McpServerConfig,
1048}
1049
1050impl McpServer {
1051 fn from(value: Value) -> Self {
1052 Self {
1053 config: serde_json::from_value(value).expect("a server config always deserializes"),
1054 }
1055 }
1056
1057 pub fn stdio<S: Into<String>>(
1061 command: impl Into<String>,
1062 args: impl IntoIterator<Item = S>,
1063 ) -> Self {
1064 let args: Vec<String> = args.into_iter().map(Into::into).collect();
1065 Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
1066 }
1067
1068 pub fn http(url: impl Into<String>) -> Self {
1070 Self::from(json!({"url": url.into(), "transport": "http"}))
1071 }
1072
1073 pub fn sse(url: impl Into<String>) -> Self {
1075 Self::from(json!({"url": url.into(), "transport": "sse"}))
1076 }
1077
1078 pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1080 self.config.env.insert(name.into(), value.into());
1081 self
1082 }
1083
1084 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1086 self.config.headers.insert(name.into(), value.into());
1087 self
1088 }
1089
1090 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
1092 self.config.connect_timeout_s = timeout.as_secs_f64();
1093 self
1094 }
1095
1096 pub fn call_timeout(mut self, timeout: Duration) -> Self {
1098 self.config.call_timeout_s = timeout.as_secs_f64();
1099 self
1100 }
1101
1102 pub fn max_result_chars(mut self, chars: usize) -> Self {
1104 self.config.max_result_chars = chars;
1105 self
1106 }
1107
1108 fn literal_refs(&self) -> HashMap<String, String> {
1111 let config = &self.config;
1112 config
1113 .args
1114 .iter()
1115 .chain(config.env.values())
1116 .chain(config.url.iter())
1117 .chain(config.headers.values())
1118 .flat_map(|text| var_ref_names(text))
1119 .map(|name| (name.clone(), format!("${{{name}}}")))
1120 .collect()
1121 }
1122}
1123
1124#[derive(Clone)]
1128pub struct Memory {
1129 store: SessionStore,
1130 retention: (i64, i64, f64),
1131}
1132
1133impl std::fmt::Debug for Memory {
1134 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1135 f.debug_struct("Memory")
1136 .field("retention", &self.retention)
1137 .finish_non_exhaustive()
1138 }
1139}
1140
1141impl Memory {
1142 pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1145 Self::wrap(SessionStore::open(path.as_ref()))
1146 }
1147
1148 pub fn open_with(
1152 path: impl AsRef<Path>,
1153 embedder: Arc<dyn Embedder>,
1154 ) -> Result<Self, BuildError> {
1155 Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
1156 }
1157
1158 pub fn in_memory() -> Result<Self, BuildError> {
1160 Self::open(":memory:")
1161 }
1162
1163 fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
1164 let memory = builtin_config().memory;
1165 Ok(Self {
1166 store: store.map_err(|error| BuildError::Memory(error.0))?,
1167 retention: (
1168 memory.retention_max_episodes,
1169 memory.retention_max_sessions,
1170 memory.retention_max_age_days,
1171 ),
1172 })
1173 }
1174
1175 pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
1179 self.retention = (episodes, sessions, max_age_days);
1180 self
1181 }
1182
1183 pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
1185 Ok(self
1186 .store
1187 .recent_sessions(limit)
1188 .map_err(|error| BuildError::Memory(error.0))?
1189 .into_iter()
1190 .map(|session| (session.session_id, session.title))
1191 .collect())
1192 }
1193
1194 pub fn store(&self) -> &SessionStore {
1197 &self.store
1198 }
1199}
1200
1201fn registry_for(builtins: Builtins) -> ToolRegistry {
1202 let registry = ToolRegistry::new();
1203 let mut tools: Vec<Box<dyn Tool>> = Vec::new();
1204 if builtins != Builtins::None {
1205 tools.push(Box::new(files::ReadFileTool));
1206 tools.push(Box::new(files::ListDirTool));
1207 tools.push(Box::new(search::SearchFilesTool));
1208 tools.push(Box::new(search::FindFilesTool));
1209 }
1210 if matches!(builtins, Builtins::Files | Builtins::All) {
1211 tools.push(Box::new(files::WriteFileTool));
1212 tools.push(Box::new(files::EditFileTool));
1213 }
1214 if builtins == Builtins::All {
1215 tools.push(Box::new(exec::RunCommandTool));
1216 tools.push(Box::new(exec::PythonExecTool));
1217 tools.push(Box::new(web::WebFetchTool));
1218 }
1219 for tool in tools {
1220 registry
1221 .register(tool)
1222 .expect("built-in tool names are unique");
1223 }
1224 registry
1225}
1226
1227#[derive(Debug, Clone, PartialEq)]
1233#[non_exhaustive]
1234pub struct RunResult {
1235 pub answer: String,
1238 pub output: String,
1241 pub turn: Option<TurnSummary>,
1243 pub usage: Usage,
1245}
1246
1247#[derive(Debug, Clone, PartialEq, Eq)]
1250pub enum Turn {
1251 Goal(String),
1253 Skill { name: String, task: String },
1256 Specialist {
1260 name: String,
1261 task: String,
1262 with_context: bool,
1263 },
1264}
1265
1266impl Turn {
1267 pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
1268 Self::Skill {
1269 name: name.into(),
1270 task: task.into(),
1271 }
1272 }
1273
1274 pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
1275 Self::Specialist {
1276 name: name.into(),
1277 task: task.into(),
1278 with_context: false,
1279 }
1280 }
1281
1282 pub fn with_context(mut self) -> Self {
1284 if let Self::Specialist { with_context, .. } = &mut self {
1285 *with_context = true;
1286 }
1287 self
1288 }
1289}
1290
1291impl From<&str> for Turn {
1292 fn from(goal: &str) -> Self {
1293 Self::Goal(goal.to_owned())
1294 }
1295}
1296
1297impl From<String> for Turn {
1298 fn from(goal: String) -> Self {
1299 Self::Goal(goal)
1300 }
1301}
1302
1303impl From<&String> for Turn {
1304 fn from(goal: &String) -> Self {
1305 Self::Goal(goal.clone())
1306 }
1307}
1308
1309pub struct Agent {
1312 harness: Harness,
1313 conversation: Conversation,
1314 notices: Vec<String>,
1316}
1317
1318impl Agent {
1319 pub fn builder() -> AgentBuilder {
1320 AgentBuilder::default()
1321 }
1322
1323 pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1325 self.run_with_events(turn, |_| {}).await
1326 }
1327
1328 pub async fn run_with_events(
1331 &mut self,
1332 turn: impl Into<Turn>,
1333 mut on_event: impl FnMut(TurnEvent<'_>),
1334 ) -> Result<RunResult, RunError> {
1335 let (kind, prompt, display) = match turn.into() {
1336 Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
1337 Turn::Skill { name, task } => {
1338 let skill = self
1339 .harness
1340 .context
1341 .skills
1342 .get(&name)
1343 .cloned()
1344 .ok_or(RunError::UnknownSkill(name.clone()))?;
1345 let display = format!("/{name} {task}").trim_end().to_owned();
1346 (TurnKind::Skill(skill), task, display)
1347 }
1348 Turn::Specialist {
1349 name,
1350 task,
1351 with_context,
1352 } => {
1353 if !self.harness.agents.enabled
1354 || self.harness.context.specialties.get(&name).is_none()
1355 {
1356 return Err(RunError::UnknownSpecialist(name));
1357 }
1358 let display = format!("/agent {name} {task}");
1359 (TurnKind::Agent { name, with_context }, task, display)
1360 }
1361 };
1362 let output = self
1363 .harness
1364 .run_kind(
1365 &mut self.conversation.0,
1366 &kind,
1367 &prompt,
1368 &display,
1369 &mut on_event,
1370 )
1371 .await;
1372 if let Some(store) = &self.harness.memory {
1375 let _ = store.persist(&self.conversation.0);
1376 }
1377 let output = output?;
1378 Ok(RunResult {
1379 answer: final_answer(&self.conversation.0.messages).to_owned(),
1380 output,
1381 turn: self.conversation.0.last_turn.clone(),
1382 usage: self.conversation.0.usage,
1383 })
1384 }
1385
1386 #[cfg(feature = "agent86ui")]
1395 pub async fn ui_action(&mut self, action: Action) -> Result<RunResult, RunError> {
1396 self.ui_action_with_events(action, |_| {}).await
1397 }
1398
1399 #[cfg(feature = "agent86ui")]
1401 pub async fn ui_action_with_events(
1402 &mut self,
1403 action: Action,
1404 on_event: impl FnMut(TurnEvent<'_>),
1405 ) -> Result<RunResult, RunError> {
1406 let text = self
1407 .harness
1408 .accept_ui_action(&self.conversation.0.session_id, &action)
1409 .map_err(RunError::UiAction)?;
1410 self.run_with_events(Turn::Goal(text), on_event).await
1411 }
1412
1413 pub fn cancel_handle(&self) -> CancelToken {
1416 self.harness.cancel.clone()
1417 }
1418
1419 pub fn conversation(&self) -> &Conversation {
1421 &self.conversation
1422 }
1423
1424 pub fn with_conversation(mut self, conversation: Conversation) -> Self {
1428 self.conversation = conversation;
1429 #[cfg(feature = "agent86ui")]
1430 self.replay_surfaces();
1431 self
1432 }
1433
1434 #[cfg(feature = "agent86ui")]
1436 fn replay_surfaces(&self) {
1437 if let Some(ui) = &self.harness.context.ui {
1438 ui.replay(&self.conversation.0, &self.harness.context);
1439 }
1440 }
1441
1442 #[cfg(feature = "agent86ui")]
1450 pub fn surfaces(&self) -> Vec<AgentMessage> {
1451 self.harness
1452 .context
1453 .ui
1454 .as_ref()
1455 .map(|ui| ui.snapshot())
1456 .unwrap_or_default()
1457 }
1458
1459 pub fn session_id(&self) -> &str {
1461 self.conversation.id()
1462 }
1463
1464 pub fn secret_names(&self) -> Vec<String> {
1466 self.harness.context.secrets.names()
1467 }
1468
1469 pub fn notes(&self) -> Vec<String> {
1473 let mut notes = self.notices.clone();
1474 if let Some(mcp) = &self.harness.mcp {
1475 notes.extend(mcp.notes());
1476 }
1477 notes.extend(self.harness.tracer.note());
1478 notes
1479 }
1480
1481 pub fn skills(&self) -> Vec<String> {
1483 self.harness.context.skills.keys().cloned().collect()
1484 }
1485
1486 pub fn specialists(&self) -> Vec<String> {
1488 if !self.harness.agents.enabled {
1489 return Vec::new();
1490 }
1491 self.harness
1492 .context
1493 .specialties
1494 .names()
1495 .into_iter()
1496 .map(str::to_owned)
1497 .collect()
1498 }
1499
1500 pub fn tool_names(&self) -> Vec<String> {
1502 self.harness.registry.names()
1503 }
1504
1505 pub fn harness(&self) -> &Harness {
1508 &self.harness
1509 }
1510}
1511
1512#[derive(Debug, Clone, Default, PartialEq)]
1517pub struct Conversation(AgentState);
1518
1519#[derive(Debug, Clone, PartialEq)]
1521pub struct ConversationMessage {
1522 pub role: Role,
1523 pub text: String,
1525 pub tool_calls: Vec<ToolCall>,
1527 pub answers: Option<String>,
1529}
1530
1531impl Conversation {
1532 pub fn new() -> Self {
1534 Self::default()
1535 }
1536
1537 pub fn id(&self) -> &str {
1539 &self.0.session_id
1540 }
1541
1542 pub fn messages(&self) -> Vec<ConversationMessage> {
1544 self.0
1545 .messages
1546 .iter()
1547 .map(|message| ConversationMessage {
1548 role: message.role,
1549 text: message.content.clone(),
1550 tool_calls: message.tool_calls.clone(),
1551 answers: message.tool_call_id.clone(),
1552 })
1553 .collect()
1554 }
1555
1556 pub fn steps(&self) -> usize {
1558 self.0.step_count()
1559 }
1560
1561 pub fn usage(&self) -> Usage {
1563 self.0.usage
1564 }
1565
1566 pub fn last_turn(&self) -> Option<&TurnSummary> {
1568 self.0.last_turn.as_ref()
1569 }
1570
1571 pub fn to_json(&self) -> String {
1573 serde_json::to_string(&self.0).expect("a conversation always serializes")
1574 }
1575
1576 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1579 serde_json::from_str(json).map(Self)
1580 }
1581}
1582
1583type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1587
1588pub struct FnTool {
1591 name: String,
1592 description: String,
1593 parameters: Value,
1594 side_effecting: bool,
1595 run: Box<ToolFn>,
1596}
1597
1598impl FnTool {
1599 pub fn new(
1602 name: impl Into<String>,
1603 description: impl Into<String>,
1604 parameters: Value,
1605 run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
1606 + Send
1607 + Sync
1608 + 'static,
1609 ) -> Self {
1610 Self {
1611 name: name.into(),
1612 description: description.into(),
1613 parameters,
1614 side_effecting: false,
1615 run: Box::new(run),
1616 }
1617 }
1618
1619 pub fn side_effecting(mut self) -> Self {
1622 self.side_effecting = true;
1623 self
1624 }
1625}
1626
1627impl Tool for FnTool {
1628 fn name(&self) -> &str {
1629 &self.name
1630 }
1631
1632 fn description(&self) -> &str {
1633 &self.description
1634 }
1635
1636 fn side_effecting(&self) -> bool {
1637 self.side_effecting
1638 }
1639
1640 fn parameters(&self) -> Value {
1641 self.parameters.clone()
1642 }
1643
1644 fn execute(
1645 &self,
1646 args: &Map<String, Value>,
1647 ctx: &ToolContext,
1648 ) -> Result<ToolResult, ToolError> {
1649 match (self.run)(args, ctx) {
1650 Ok(content) => Ok(ToolResult {
1651 call_id: String::new(),
1652 name: self.name.clone(),
1653 ok: true,
1654 content,
1655 error: None,
1656 metadata: Map::new(),
1657 }),
1658 Err(message) => Err(ToolError::Raised {
1659 exception: "ToolError".to_owned(),
1660 message,
1661 }),
1662 }
1663 }
1664}
1665
1666pub mod providers {
1671 pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
1672 pub use crate::provider::google::{GoogleConfig, GoogleProvider};
1673 pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
1674 pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
1675 pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
1676 pub use crate::types::{
1677 Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
1678 };
1679}