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 harness
699 .offer_questions_as_forms()
700 .map_err(BuildError::Tool)?;
701 }
702 harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
703 harness.gate.queue.watch(harness.cancel.clone());
704 harness
705 .context
706 .secrets
707 .set_queue(harness.gate.queue.clone());
708 let agent = Agent {
709 harness,
710 conversation: Conversation(state),
711 notices,
712 };
713 #[cfg(feature = "agent86ui")]
715 agent.replay_surfaces();
716 Ok(agent)
717 }
718
719 fn router(&self) -> Result<Router, BuildError> {
722 if self.models.is_empty() {
723 return match &self.triage {
724 Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
725 None => Ok(Router::default()),
726 };
727 }
728 let (triage, cheap, frontier) = match &self.triage {
729 Some((cheap, frontier)) => {
730 for name in [cheap, frontier] {
731 if !self.models.contains_key(name) {
732 return Err(BuildError::UnknownModel(name.clone()));
733 }
734 }
735 (true, cheap.as_str(), frontier.as_str())
736 }
737 None => (false, "", ""),
738 };
739 let window = self.context_window;
740 let output = self.max_output_tokens;
741 let models: HashMap<String, RoutedModel> = self
742 .models
743 .iter()
744 .map(|(name, model)| {
745 (
746 name.clone(),
747 RoutedModel {
748 reference: name.clone(),
749 provider: Arc::clone(&model.provider),
750 max_tokens: model.max_output_tokens.unwrap_or(output),
751 context_window: model.context_window.unwrap_or(window),
752 output_setting: "max_output_tokens".to_owned(),
753 },
754 )
755 })
756 .collect();
757 Ok(Router::new(
758 triage,
759 cheap,
760 frontier,
761 Box::new(move |name| {
762 models
763 .get(name)
764 .cloned()
765 .ok_or_else(|| format!("no model named '{name}'"))
766 }),
767 ))
768 }
769}
770
771#[derive(Debug, Clone)]
781pub struct SubAgents {
782 max_depth: u32,
783 max_steps: u32,
784 max_parallel: u32,
785 built_ins: bool,
786 dirs: Vec<PathBuf>,
787}
788
789impl Default for SubAgents {
790 fn default() -> Self {
791 let agents = builtin_config().agents;
792 Self {
793 max_depth: agents.max_depth,
794 max_steps: agents.max_steps,
795 max_parallel: agents.max_parallel,
796 built_ins: true,
797 dirs: Vec::new(),
798 }
799 }
800}
801
802impl SubAgents {
803 pub fn new() -> Self {
806 Self::default()
807 }
808
809 pub fn max_depth(mut self, depth: u32) -> Self {
811 self.max_depth = depth;
812 self
813 }
814
815 pub fn max_steps(mut self, steps: u32) -> Self {
817 self.max_steps = steps;
818 self
819 }
820
821 pub fn max_parallel(mut self, parallel: u32) -> Self {
823 self.max_parallel = parallel;
824 self
825 }
826
827 pub fn without_built_ins(mut self) -> Self {
829 self.built_ins = false;
830 self
831 }
832
833 pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
839 self.dirs.push(dir.into());
840 self
841 }
842}
843
844#[derive(Clone)]
846pub struct Model {
847 provider: Arc<dyn Provider>,
848 context_window: Option<u64>,
849 max_output_tokens: Option<u32>,
850}
851
852impl std::fmt::Debug for Model {
853 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
854 f.debug_struct("Model")
855 .field("provider", &self.provider.name())
856 .field("model", &self.provider.model())
857 .field("context_window", &self.context_window)
858 .field("max_output_tokens", &self.max_output_tokens)
859 .finish()
860 }
861}
862
863impl Model {
864 pub fn new(provider: Arc<dyn Provider>) -> Self {
866 Self {
867 provider,
868 context_window: None,
869 max_output_tokens: None,
870 }
871 }
872
873 pub fn context_window(mut self, tokens: u64) -> Self {
875 self.context_window = Some(tokens);
876 self
877 }
878
879 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
881 self.max_output_tokens = Some(tokens);
882 self
883 }
884}
885
886#[cfg(feature = "agent86ui")]
889#[derive(Clone)]
890pub struct Ui {
891 catalogs: Vec<Catalog>,
892 remote_media: bool,
893 on_wait: Option<crate::agent86ui::UiWaiter>,
894}
895
896#[cfg(feature = "agent86ui")]
897impl std::fmt::Debug for Ui {
898 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
899 f.debug_struct("Ui")
900 .field(
901 "catalogs",
902 &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
903 )
904 .field("remote_media", &self.remote_media)
905 .field("on_wait", &self.on_wait.is_some())
906 .finish()
907 }
908}
909
910#[cfg(feature = "agent86ui")]
911impl Ui {
912 pub fn basic() -> Self {
915 Self::new([Catalog::basic().clone()])
916 }
917
918 pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
921 Self {
922 catalogs: catalogs.into_iter().collect(),
923 remote_media: false,
924 on_wait: None,
925 }
926 }
927
928 pub fn on_wait(
937 mut self,
938 answer: impl Fn(&UiWait) -> Option<Action> + Send + Sync + 'static,
939 ) -> Self {
940 self.on_wait = Some(std::sync::Arc::new(answer));
941 self
942 }
943
944 pub fn allow_remote_media(mut self) -> Self {
949 self.remote_media = true;
950 self
951 }
952
953 pub fn catalogs(&self) -> &[Catalog] {
955 &self.catalogs
956 }
957}
958
959#[derive(Debug, Clone)]
961pub struct Otel {
962 destination: crate::otel::Destination,
963}
964
965impl Otel {
966 pub fn otlp(traces_url: impl Into<String>) -> Self {
969 Self {
970 destination: crate::otel::Destination::Otlp {
971 url: traces_url.into(),
972 headers: Vec::new(),
973 timeout: Duration::from_secs(10),
974 },
975 }
976 }
977
978 pub fn console() -> Self {
980 Self {
981 destination: crate::otel::Destination::Console,
982 }
983 }
984
985 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
987 if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
988 headers.push((name.into(), value.into()));
989 }
990 self
991 }
992
993 pub fn timeout(mut self, timeout: Duration) -> Self {
995 if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
996 *limit = timeout;
997 }
998 self
999 }
1000}
1001
1002fn start_mcp(
1005 servers: &[(String, McpServer)],
1006 registry: &ToolRegistry,
1007) -> Result<Option<Arc<McpManager>>, BuildError> {
1008 if servers.is_empty() {
1009 return Ok(None);
1010 }
1011 let manager = Arc::new(McpManager::empty(&builtin_config()));
1012 manager.attach(registry);
1013 let mut seen: Vec<&str> = Vec::new();
1014 for (name, server) in servers {
1015 let failed = |reason: String| BuildError::Mcp {
1016 name: name.clone(),
1017 reason,
1018 };
1019 if seen.contains(&name.as_str()) {
1020 return Err(failed("another server was given the same name".to_owned()));
1021 }
1022 seen.push(name);
1023 let mut config = server.config.clone();
1024 config.resolve_transport().map_err(failed)?;
1025 manager
1026 .start_server(
1027 name,
1028 &config,
1029 &server.literal_refs(),
1030 &NoSecretStore,
1031 config.connect_timeout_s,
1032 )
1033 .map_err(failed)?;
1034 let (_, collisions) = manager.mount(name);
1035 if !collisions.is_empty() {
1036 return Err(BuildError::Tool(format!(
1037 "MCP server '{name}' offers tools already taken: {}",
1038 collisions.join(", ")
1039 )));
1040 }
1041 }
1042 Ok(Some(manager))
1043}
1044
1045#[derive(Debug, Clone)]
1050pub struct McpServer {
1051 config: McpServerConfig,
1052}
1053
1054impl McpServer {
1055 fn from(value: Value) -> Self {
1056 Self {
1057 config: serde_json::from_value(value).expect("a server config always deserializes"),
1058 }
1059 }
1060
1061 pub fn stdio<S: Into<String>>(
1065 command: impl Into<String>,
1066 args: impl IntoIterator<Item = S>,
1067 ) -> Self {
1068 let args: Vec<String> = args.into_iter().map(Into::into).collect();
1069 Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
1070 }
1071
1072 pub fn http(url: impl Into<String>) -> Self {
1074 Self::from(json!({"url": url.into(), "transport": "http"}))
1075 }
1076
1077 pub fn sse(url: impl Into<String>) -> Self {
1079 Self::from(json!({"url": url.into(), "transport": "sse"}))
1080 }
1081
1082 pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1084 self.config.env.insert(name.into(), value.into());
1085 self
1086 }
1087
1088 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1090 self.config.headers.insert(name.into(), value.into());
1091 self
1092 }
1093
1094 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
1096 self.config.connect_timeout_s = timeout.as_secs_f64();
1097 self
1098 }
1099
1100 pub fn call_timeout(mut self, timeout: Duration) -> Self {
1102 self.config.call_timeout_s = timeout.as_secs_f64();
1103 self
1104 }
1105
1106 pub fn max_result_chars(mut self, chars: usize) -> Self {
1108 self.config.max_result_chars = chars;
1109 self
1110 }
1111
1112 fn literal_refs(&self) -> HashMap<String, String> {
1115 let config = &self.config;
1116 config
1117 .args
1118 .iter()
1119 .chain(config.env.values())
1120 .chain(config.url.iter())
1121 .chain(config.headers.values())
1122 .flat_map(|text| var_ref_names(text))
1123 .map(|name| (name.clone(), format!("${{{name}}}")))
1124 .collect()
1125 }
1126}
1127
1128#[derive(Clone)]
1132pub struct Memory {
1133 store: SessionStore,
1134 retention: (i64, i64, f64),
1135}
1136
1137impl std::fmt::Debug for Memory {
1138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1139 f.debug_struct("Memory")
1140 .field("retention", &self.retention)
1141 .finish_non_exhaustive()
1142 }
1143}
1144
1145impl Memory {
1146 pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1149 Self::wrap(SessionStore::open(path.as_ref()))
1150 }
1151
1152 pub fn open_with(
1156 path: impl AsRef<Path>,
1157 embedder: Arc<dyn Embedder>,
1158 ) -> Result<Self, BuildError> {
1159 Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
1160 }
1161
1162 pub fn in_memory() -> Result<Self, BuildError> {
1164 Self::open(":memory:")
1165 }
1166
1167 fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
1168 let memory = builtin_config().memory;
1169 Ok(Self {
1170 store: store.map_err(|error| BuildError::Memory(error.0))?,
1171 retention: (
1172 memory.retention_max_episodes,
1173 memory.retention_max_sessions,
1174 memory.retention_max_age_days,
1175 ),
1176 })
1177 }
1178
1179 pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
1183 self.retention = (episodes, sessions, max_age_days);
1184 self
1185 }
1186
1187 pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
1189 Ok(self
1190 .store
1191 .recent_sessions(limit)
1192 .map_err(|error| BuildError::Memory(error.0))?
1193 .into_iter()
1194 .map(|session| (session.session_id, session.title))
1195 .collect())
1196 }
1197
1198 pub fn store(&self) -> &SessionStore {
1201 &self.store
1202 }
1203}
1204
1205fn registry_for(builtins: Builtins) -> ToolRegistry {
1206 let registry = ToolRegistry::new();
1207 let mut tools: Vec<Box<dyn Tool>> = Vec::new();
1208 if builtins != Builtins::None {
1209 tools.push(Box::new(files::ReadFileTool));
1210 tools.push(Box::new(files::ListDirTool));
1211 tools.push(Box::new(search::SearchFilesTool));
1212 tools.push(Box::new(search::FindFilesTool));
1213 }
1214 if matches!(builtins, Builtins::Files | Builtins::All) {
1215 tools.push(Box::new(files::WriteFileTool));
1216 tools.push(Box::new(files::EditFileTool));
1217 }
1218 if builtins == Builtins::All {
1219 tools.push(Box::new(exec::RunCommandTool));
1220 tools.push(Box::new(exec::PythonExecTool));
1221 tools.push(Box::new(web::WebFetchTool));
1222 }
1223 for tool in tools {
1224 registry
1225 .register(tool)
1226 .expect("built-in tool names are unique");
1227 }
1228 registry
1229}
1230
1231#[derive(Debug, Clone, PartialEq)]
1237#[non_exhaustive]
1238pub struct RunResult {
1239 pub answer: String,
1242 pub output: String,
1245 pub turn: Option<TurnSummary>,
1247 pub usage: Usage,
1249}
1250
1251#[derive(Debug, Clone, PartialEq, Eq)]
1254pub enum Turn {
1255 Goal(String),
1257 Skill { name: String, task: String },
1260 Specialist {
1264 name: String,
1265 task: String,
1266 with_context: bool,
1267 },
1268}
1269
1270impl Turn {
1271 pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
1272 Self::Skill {
1273 name: name.into(),
1274 task: task.into(),
1275 }
1276 }
1277
1278 pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
1279 Self::Specialist {
1280 name: name.into(),
1281 task: task.into(),
1282 with_context: false,
1283 }
1284 }
1285
1286 pub fn with_context(mut self) -> Self {
1288 if let Self::Specialist { with_context, .. } = &mut self {
1289 *with_context = true;
1290 }
1291 self
1292 }
1293}
1294
1295impl From<&str> for Turn {
1296 fn from(goal: &str) -> Self {
1297 Self::Goal(goal.to_owned())
1298 }
1299}
1300
1301impl From<String> for Turn {
1302 fn from(goal: String) -> Self {
1303 Self::Goal(goal)
1304 }
1305}
1306
1307impl From<&String> for Turn {
1308 fn from(goal: &String) -> Self {
1309 Self::Goal(goal.clone())
1310 }
1311}
1312
1313pub struct Agent {
1316 harness: Harness,
1317 conversation: Conversation,
1318 notices: Vec<String>,
1320}
1321
1322impl Agent {
1323 pub fn builder() -> AgentBuilder {
1324 AgentBuilder::default()
1325 }
1326
1327 pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1329 self.run_with_events(turn, |_| {}).await
1330 }
1331
1332 pub async fn run_with_events(
1335 &mut self,
1336 turn: impl Into<Turn>,
1337 mut on_event: impl FnMut(TurnEvent<'_>),
1338 ) -> Result<RunResult, RunError> {
1339 let (kind, prompt, display) = match turn.into() {
1340 Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
1341 Turn::Skill { name, task } => {
1342 let skill = self
1343 .harness
1344 .context
1345 .skills
1346 .get(&name)
1347 .cloned()
1348 .ok_or(RunError::UnknownSkill(name.clone()))?;
1349 let display = format!("/{name} {task}").trim_end().to_owned();
1350 (TurnKind::Skill(skill), task, display)
1351 }
1352 Turn::Specialist {
1353 name,
1354 task,
1355 with_context,
1356 } => {
1357 if !self.harness.agents.enabled
1358 || self.harness.context.specialties.get(&name).is_none()
1359 {
1360 return Err(RunError::UnknownSpecialist(name));
1361 }
1362 let display = format!("/agent {name} {task}");
1363 (TurnKind::Agent { name, with_context }, task, display)
1364 }
1365 };
1366 let output = self
1367 .harness
1368 .run_kind(
1369 &mut self.conversation.0,
1370 &kind,
1371 &prompt,
1372 &display,
1373 &mut on_event,
1374 )
1375 .await;
1376 if let Some(store) = &self.harness.memory {
1379 let _ = store.persist(&self.conversation.0);
1380 }
1381 let output = output?;
1382 Ok(RunResult {
1383 answer: final_answer(&self.conversation.0.messages).to_owned(),
1384 output,
1385 turn: self.conversation.0.last_turn.clone(),
1386 usage: self.conversation.0.usage,
1387 })
1388 }
1389
1390 #[cfg(feature = "agent86ui")]
1399 pub async fn ui_action(&mut self, action: Action) -> Result<RunResult, RunError> {
1400 self.ui_action_with_events(action, |_| {}).await
1401 }
1402
1403 #[cfg(feature = "agent86ui")]
1405 pub async fn ui_action_with_events(
1406 &mut self,
1407 action: Action,
1408 on_event: impl FnMut(TurnEvent<'_>),
1409 ) -> Result<RunResult, RunError> {
1410 let text = self
1411 .harness
1412 .accept_ui_action(&self.conversation.0.session_id, &action)
1413 .map_err(RunError::UiAction)?;
1414 self.run_with_events(Turn::Goal(text), on_event).await
1415 }
1416
1417 pub fn cancel_handle(&self) -> CancelToken {
1420 self.harness.cancel.clone()
1421 }
1422
1423 pub fn conversation(&self) -> &Conversation {
1425 &self.conversation
1426 }
1427
1428 pub fn with_conversation(mut self, conversation: Conversation) -> Self {
1432 self.conversation = conversation;
1433 #[cfg(feature = "agent86ui")]
1434 self.replay_surfaces();
1435 self
1436 }
1437
1438 #[cfg(feature = "agent86ui")]
1440 fn replay_surfaces(&self) {
1441 if let Some(ui) = &self.harness.context.ui {
1442 ui.replay(&self.conversation.0, &self.harness.context);
1443 }
1444 }
1445
1446 #[cfg(feature = "agent86ui")]
1454 pub fn surfaces(&self) -> Vec<AgentMessage> {
1455 self.harness
1456 .context
1457 .ui
1458 .as_ref()
1459 .map(|ui| ui.snapshot())
1460 .unwrap_or_default()
1461 }
1462
1463 pub fn session_id(&self) -> &str {
1465 self.conversation.id()
1466 }
1467
1468 pub fn secret_names(&self) -> Vec<String> {
1470 self.harness.context.secrets.names()
1471 }
1472
1473 pub fn notes(&self) -> Vec<String> {
1477 let mut notes = self.notices.clone();
1478 if let Some(mcp) = &self.harness.mcp {
1479 notes.extend(mcp.notes());
1480 }
1481 notes.extend(self.harness.tracer.note());
1482 notes
1483 }
1484
1485 pub fn skills(&self) -> Vec<String> {
1487 self.harness.context.skills.keys().cloned().collect()
1488 }
1489
1490 pub fn specialists(&self) -> Vec<String> {
1492 if !self.harness.agents.enabled {
1493 return Vec::new();
1494 }
1495 self.harness
1496 .context
1497 .specialties
1498 .names()
1499 .into_iter()
1500 .map(str::to_owned)
1501 .collect()
1502 }
1503
1504 pub fn tool_names(&self) -> Vec<String> {
1506 self.harness.registry.names()
1507 }
1508
1509 pub fn harness(&self) -> &Harness {
1512 &self.harness
1513 }
1514}
1515
1516#[derive(Debug, Clone, Default, PartialEq)]
1521pub struct Conversation(AgentState);
1522
1523#[derive(Debug, Clone, PartialEq)]
1525pub struct ConversationMessage {
1526 pub role: Role,
1527 pub text: String,
1529 pub tool_calls: Vec<ToolCall>,
1531 pub answers: Option<String>,
1533}
1534
1535impl Conversation {
1536 pub fn new() -> Self {
1538 Self::default()
1539 }
1540
1541 pub fn id(&self) -> &str {
1543 &self.0.session_id
1544 }
1545
1546 pub fn messages(&self) -> Vec<ConversationMessage> {
1548 self.0
1549 .messages
1550 .iter()
1551 .map(|message| ConversationMessage {
1552 role: message.role,
1553 text: message.content.clone(),
1554 tool_calls: message.tool_calls.clone(),
1555 answers: message.tool_call_id.clone(),
1556 })
1557 .collect()
1558 }
1559
1560 pub fn steps(&self) -> usize {
1562 self.0.step_count()
1563 }
1564
1565 pub fn usage(&self) -> Usage {
1567 self.0.usage
1568 }
1569
1570 pub fn last_turn(&self) -> Option<&TurnSummary> {
1572 self.0.last_turn.as_ref()
1573 }
1574
1575 pub fn to_json(&self) -> String {
1577 serde_json::to_string(&self.0).expect("a conversation always serializes")
1578 }
1579
1580 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1583 serde_json::from_str(json).map(Self)
1584 }
1585}
1586
1587type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1591
1592pub struct FnTool {
1595 name: String,
1596 description: String,
1597 parameters: Value,
1598 side_effecting: bool,
1599 run: Box<ToolFn>,
1600}
1601
1602impl FnTool {
1603 pub fn new(
1606 name: impl Into<String>,
1607 description: impl Into<String>,
1608 parameters: Value,
1609 run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
1610 + Send
1611 + Sync
1612 + 'static,
1613 ) -> Self {
1614 Self {
1615 name: name.into(),
1616 description: description.into(),
1617 parameters,
1618 side_effecting: false,
1619 run: Box::new(run),
1620 }
1621 }
1622
1623 pub fn side_effecting(mut self) -> Self {
1626 self.side_effecting = true;
1627 self
1628 }
1629}
1630
1631impl Tool for FnTool {
1632 fn name(&self) -> &str {
1633 &self.name
1634 }
1635
1636 fn description(&self) -> &str {
1637 &self.description
1638 }
1639
1640 fn side_effecting(&self) -> bool {
1641 self.side_effecting
1642 }
1643
1644 fn parameters(&self) -> Value {
1645 self.parameters.clone()
1646 }
1647
1648 fn execute(
1649 &self,
1650 args: &Map<String, Value>,
1651 ctx: &ToolContext,
1652 ) -> Result<ToolResult, ToolError> {
1653 match (self.run)(args, ctx) {
1654 Ok(content) => Ok(ToolResult {
1655 call_id: String::new(),
1656 name: self.name.clone(),
1657 ok: true,
1658 content,
1659 error: None,
1660 metadata: Map::new(),
1661 }),
1662 Err(message) => Err(ToolError::Raised {
1663 exception: "ToolError".to_owned(),
1664 message,
1665 }),
1666 }
1667 }
1668}
1669
1670pub mod providers {
1675 pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
1676 pub use crate::provider::google::{GoogleConfig, GoogleProvider};
1677 pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
1678 pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
1679 pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
1680 pub use crate::types::{
1681 Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
1682 };
1683}