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 if let Some(ui) = self.ui {
624 if ui.catalogs.is_empty() {
625 return Err(BuildError::Ui(
626 "a renderer needs at least one catalog".into(),
627 ));
628 }
629 let session = crate::agent86ui::UiSession::new(ui.catalogs)
630 .map_err(|error| BuildError::Ui(error.to_string()))?
631 .with_egress(self.guardrails.egress)
632 .with_remote_media(ui.remote_media)
633 .with_waiter(ui.on_wait);
634 context.ui = Some(Arc::new(session));
635 registry
636 .register(Box::new(crate::tools::render_ui::RenderUiTool))
637 .map_err(BuildError::Tool)?;
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 harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
695 harness.gate.queue.watch(harness.cancel.clone());
696 harness
697 .context
698 .secrets
699 .set_queue(harness.gate.queue.clone());
700 let agent = Agent {
701 harness,
702 conversation: Conversation(state),
703 notices,
704 };
705 #[cfg(feature = "agent86ui")]
707 agent.replay_surfaces();
708 Ok(agent)
709 }
710
711 fn router(&self) -> Result<Router, BuildError> {
714 if self.models.is_empty() {
715 return match &self.triage {
716 Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
717 None => Ok(Router::default()),
718 };
719 }
720 let (triage, cheap, frontier) = match &self.triage {
721 Some((cheap, frontier)) => {
722 for name in [cheap, frontier] {
723 if !self.models.contains_key(name) {
724 return Err(BuildError::UnknownModel(name.clone()));
725 }
726 }
727 (true, cheap.as_str(), frontier.as_str())
728 }
729 None => (false, "", ""),
730 };
731 let window = self.context_window;
732 let output = self.max_output_tokens;
733 let models: HashMap<String, RoutedModel> = self
734 .models
735 .iter()
736 .map(|(name, model)| {
737 (
738 name.clone(),
739 RoutedModel {
740 reference: name.clone(),
741 provider: Arc::clone(&model.provider),
742 max_tokens: model.max_output_tokens.unwrap_or(output),
743 context_window: model.context_window.unwrap_or(window),
744 output_setting: "max_output_tokens".to_owned(),
745 },
746 )
747 })
748 .collect();
749 Ok(Router::new(
750 triage,
751 cheap,
752 frontier,
753 Box::new(move |name| {
754 models
755 .get(name)
756 .cloned()
757 .ok_or_else(|| format!("no model named '{name}'"))
758 }),
759 ))
760 }
761}
762
763#[derive(Debug, Clone)]
773pub struct SubAgents {
774 max_depth: u32,
775 max_steps: u32,
776 max_parallel: u32,
777 built_ins: bool,
778 dirs: Vec<PathBuf>,
779}
780
781impl Default for SubAgents {
782 fn default() -> Self {
783 let agents = builtin_config().agents;
784 Self {
785 max_depth: agents.max_depth,
786 max_steps: agents.max_steps,
787 max_parallel: agents.max_parallel,
788 built_ins: true,
789 dirs: Vec::new(),
790 }
791 }
792}
793
794impl SubAgents {
795 pub fn new() -> Self {
798 Self::default()
799 }
800
801 pub fn max_depth(mut self, depth: u32) -> Self {
803 self.max_depth = depth;
804 self
805 }
806
807 pub fn max_steps(mut self, steps: u32) -> Self {
809 self.max_steps = steps;
810 self
811 }
812
813 pub fn max_parallel(mut self, parallel: u32) -> Self {
815 self.max_parallel = parallel;
816 self
817 }
818
819 pub fn without_built_ins(mut self) -> Self {
821 self.built_ins = false;
822 self
823 }
824
825 pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
831 self.dirs.push(dir.into());
832 self
833 }
834}
835
836#[derive(Clone)]
838pub struct Model {
839 provider: Arc<dyn Provider>,
840 context_window: Option<u64>,
841 max_output_tokens: Option<u32>,
842}
843
844impl std::fmt::Debug for Model {
845 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
846 f.debug_struct("Model")
847 .field("provider", &self.provider.name())
848 .field("model", &self.provider.model())
849 .field("context_window", &self.context_window)
850 .field("max_output_tokens", &self.max_output_tokens)
851 .finish()
852 }
853}
854
855impl Model {
856 pub fn new(provider: Arc<dyn Provider>) -> Self {
858 Self {
859 provider,
860 context_window: None,
861 max_output_tokens: None,
862 }
863 }
864
865 pub fn context_window(mut self, tokens: u64) -> Self {
867 self.context_window = Some(tokens);
868 self
869 }
870
871 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
873 self.max_output_tokens = Some(tokens);
874 self
875 }
876}
877
878#[cfg(feature = "agent86ui")]
881#[derive(Clone)]
882pub struct Ui {
883 catalogs: Vec<Catalog>,
884 remote_media: bool,
885 on_wait: Option<crate::agent86ui::UiWaiter>,
886}
887
888#[cfg(feature = "agent86ui")]
889impl std::fmt::Debug for Ui {
890 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
891 f.debug_struct("Ui")
892 .field(
893 "catalogs",
894 &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
895 )
896 .field("remote_media", &self.remote_media)
897 .field("on_wait", &self.on_wait.is_some())
898 .finish()
899 }
900}
901
902#[cfg(feature = "agent86ui")]
903impl Ui {
904 pub fn basic() -> Self {
907 Self::new([Catalog::basic().clone()])
908 }
909
910 pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
913 Self {
914 catalogs: catalogs.into_iter().collect(),
915 remote_media: false,
916 on_wait: None,
917 }
918 }
919
920 pub fn on_wait(
929 mut self,
930 answer: impl Fn(&UiWait) -> Option<Action> + Send + Sync + 'static,
931 ) -> Self {
932 self.on_wait = Some(std::sync::Arc::new(answer));
933 self
934 }
935
936 pub fn allow_remote_media(mut self) -> Self {
941 self.remote_media = true;
942 self
943 }
944
945 pub fn catalogs(&self) -> &[Catalog] {
947 &self.catalogs
948 }
949}
950
951#[derive(Debug, Clone)]
953pub struct Otel {
954 destination: crate::otel::Destination,
955}
956
957impl Otel {
958 pub fn otlp(traces_url: impl Into<String>) -> Self {
961 Self {
962 destination: crate::otel::Destination::Otlp {
963 url: traces_url.into(),
964 headers: Vec::new(),
965 timeout: Duration::from_secs(10),
966 },
967 }
968 }
969
970 pub fn console() -> Self {
972 Self {
973 destination: crate::otel::Destination::Console,
974 }
975 }
976
977 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
979 if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
980 headers.push((name.into(), value.into()));
981 }
982 self
983 }
984
985 pub fn timeout(mut self, timeout: Duration) -> Self {
987 if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
988 *limit = timeout;
989 }
990 self
991 }
992}
993
994fn start_mcp(
997 servers: &[(String, McpServer)],
998 registry: &ToolRegistry,
999) -> Result<Option<Arc<McpManager>>, BuildError> {
1000 if servers.is_empty() {
1001 return Ok(None);
1002 }
1003 let manager = Arc::new(McpManager::empty(&builtin_config()));
1004 manager.attach(registry);
1005 let mut seen: Vec<&str> = Vec::new();
1006 for (name, server) in servers {
1007 let failed = |reason: String| BuildError::Mcp {
1008 name: name.clone(),
1009 reason,
1010 };
1011 if seen.contains(&name.as_str()) {
1012 return Err(failed("another server was given the same name".to_owned()));
1013 }
1014 seen.push(name);
1015 let mut config = server.config.clone();
1016 config.resolve_transport().map_err(failed)?;
1017 manager
1018 .start_server(
1019 name,
1020 &config,
1021 &server.literal_refs(),
1022 &NoSecretStore,
1023 config.connect_timeout_s,
1024 )
1025 .map_err(failed)?;
1026 let (_, collisions) = manager.mount(name);
1027 if !collisions.is_empty() {
1028 return Err(BuildError::Tool(format!(
1029 "MCP server '{name}' offers tools already taken: {}",
1030 collisions.join(", ")
1031 )));
1032 }
1033 }
1034 Ok(Some(manager))
1035}
1036
1037#[derive(Debug, Clone)]
1042pub struct McpServer {
1043 config: McpServerConfig,
1044}
1045
1046impl McpServer {
1047 fn from(value: Value) -> Self {
1048 Self {
1049 config: serde_json::from_value(value).expect("a server config always deserializes"),
1050 }
1051 }
1052
1053 pub fn stdio<S: Into<String>>(
1057 command: impl Into<String>,
1058 args: impl IntoIterator<Item = S>,
1059 ) -> Self {
1060 let args: Vec<String> = args.into_iter().map(Into::into).collect();
1061 Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
1062 }
1063
1064 pub fn http(url: impl Into<String>) -> Self {
1066 Self::from(json!({"url": url.into(), "transport": "http"}))
1067 }
1068
1069 pub fn sse(url: impl Into<String>) -> Self {
1071 Self::from(json!({"url": url.into(), "transport": "sse"}))
1072 }
1073
1074 pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1076 self.config.env.insert(name.into(), value.into());
1077 self
1078 }
1079
1080 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1082 self.config.headers.insert(name.into(), value.into());
1083 self
1084 }
1085
1086 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
1088 self.config.connect_timeout_s = timeout.as_secs_f64();
1089 self
1090 }
1091
1092 pub fn call_timeout(mut self, timeout: Duration) -> Self {
1094 self.config.call_timeout_s = timeout.as_secs_f64();
1095 self
1096 }
1097
1098 pub fn max_result_chars(mut self, chars: usize) -> Self {
1100 self.config.max_result_chars = chars;
1101 self
1102 }
1103
1104 fn literal_refs(&self) -> HashMap<String, String> {
1107 let config = &self.config;
1108 config
1109 .args
1110 .iter()
1111 .chain(config.env.values())
1112 .chain(config.url.iter())
1113 .chain(config.headers.values())
1114 .flat_map(|text| var_ref_names(text))
1115 .map(|name| (name.clone(), format!("${{{name}}}")))
1116 .collect()
1117 }
1118}
1119
1120#[derive(Clone)]
1124pub struct Memory {
1125 store: SessionStore,
1126 retention: (i64, i64, f64),
1127}
1128
1129impl std::fmt::Debug for Memory {
1130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1131 f.debug_struct("Memory")
1132 .field("retention", &self.retention)
1133 .finish_non_exhaustive()
1134 }
1135}
1136
1137impl Memory {
1138 pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1141 Self::wrap(SessionStore::open(path.as_ref()))
1142 }
1143
1144 pub fn open_with(
1148 path: impl AsRef<Path>,
1149 embedder: Arc<dyn Embedder>,
1150 ) -> Result<Self, BuildError> {
1151 Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
1152 }
1153
1154 pub fn in_memory() -> Result<Self, BuildError> {
1156 Self::open(":memory:")
1157 }
1158
1159 fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
1160 let memory = builtin_config().memory;
1161 Ok(Self {
1162 store: store.map_err(|error| BuildError::Memory(error.0))?,
1163 retention: (
1164 memory.retention_max_episodes,
1165 memory.retention_max_sessions,
1166 memory.retention_max_age_days,
1167 ),
1168 })
1169 }
1170
1171 pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
1175 self.retention = (episodes, sessions, max_age_days);
1176 self
1177 }
1178
1179 pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
1181 Ok(self
1182 .store
1183 .recent_sessions(limit)
1184 .map_err(|error| BuildError::Memory(error.0))?
1185 .into_iter()
1186 .map(|session| (session.session_id, session.title))
1187 .collect())
1188 }
1189
1190 pub fn store(&self) -> &SessionStore {
1193 &self.store
1194 }
1195}
1196
1197fn registry_for(builtins: Builtins) -> ToolRegistry {
1198 let registry = ToolRegistry::new();
1199 let mut tools: Vec<Box<dyn Tool>> = Vec::new();
1200 if builtins != Builtins::None {
1201 tools.push(Box::new(files::ReadFileTool));
1202 tools.push(Box::new(files::ListDirTool));
1203 tools.push(Box::new(search::SearchFilesTool));
1204 tools.push(Box::new(search::FindFilesTool));
1205 }
1206 if matches!(builtins, Builtins::Files | Builtins::All) {
1207 tools.push(Box::new(files::WriteFileTool));
1208 tools.push(Box::new(files::EditFileTool));
1209 }
1210 if builtins == Builtins::All {
1211 tools.push(Box::new(exec::RunCommandTool));
1212 tools.push(Box::new(exec::PythonExecTool));
1213 tools.push(Box::new(web::WebFetchTool));
1214 }
1215 for tool in tools {
1216 registry
1217 .register(tool)
1218 .expect("built-in tool names are unique");
1219 }
1220 registry
1221}
1222
1223#[derive(Debug, Clone, PartialEq)]
1229#[non_exhaustive]
1230pub struct RunResult {
1231 pub answer: String,
1234 pub output: String,
1237 pub turn: Option<TurnSummary>,
1239 pub usage: Usage,
1241}
1242
1243#[derive(Debug, Clone, PartialEq, Eq)]
1246pub enum Turn {
1247 Goal(String),
1249 Skill { name: String, task: String },
1252 Specialist {
1256 name: String,
1257 task: String,
1258 with_context: bool,
1259 },
1260}
1261
1262impl Turn {
1263 pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
1264 Self::Skill {
1265 name: name.into(),
1266 task: task.into(),
1267 }
1268 }
1269
1270 pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
1271 Self::Specialist {
1272 name: name.into(),
1273 task: task.into(),
1274 with_context: false,
1275 }
1276 }
1277
1278 pub fn with_context(mut self) -> Self {
1280 if let Self::Specialist { with_context, .. } = &mut self {
1281 *with_context = true;
1282 }
1283 self
1284 }
1285}
1286
1287impl From<&str> for Turn {
1288 fn from(goal: &str) -> Self {
1289 Self::Goal(goal.to_owned())
1290 }
1291}
1292
1293impl From<String> for Turn {
1294 fn from(goal: String) -> Self {
1295 Self::Goal(goal)
1296 }
1297}
1298
1299impl From<&String> for Turn {
1300 fn from(goal: &String) -> Self {
1301 Self::Goal(goal.clone())
1302 }
1303}
1304
1305pub struct Agent {
1308 harness: Harness,
1309 conversation: Conversation,
1310 notices: Vec<String>,
1312}
1313
1314impl Agent {
1315 pub fn builder() -> AgentBuilder {
1316 AgentBuilder::default()
1317 }
1318
1319 pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1321 self.run_with_events(turn, |_| {}).await
1322 }
1323
1324 pub async fn run_with_events(
1327 &mut self,
1328 turn: impl Into<Turn>,
1329 mut on_event: impl FnMut(TurnEvent<'_>),
1330 ) -> Result<RunResult, RunError> {
1331 let (kind, prompt, display) = match turn.into() {
1332 Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
1333 Turn::Skill { name, task } => {
1334 let skill = self
1335 .harness
1336 .context
1337 .skills
1338 .get(&name)
1339 .cloned()
1340 .ok_or(RunError::UnknownSkill(name.clone()))?;
1341 let display = format!("/{name} {task}").trim_end().to_owned();
1342 (TurnKind::Skill(skill), task, display)
1343 }
1344 Turn::Specialist {
1345 name,
1346 task,
1347 with_context,
1348 } => {
1349 if !self.harness.agents.enabled
1350 || self.harness.context.specialties.get(&name).is_none()
1351 {
1352 return Err(RunError::UnknownSpecialist(name));
1353 }
1354 let display = format!("/agent {name} {task}");
1355 (TurnKind::Agent { name, with_context }, task, display)
1356 }
1357 };
1358 let output = self
1359 .harness
1360 .run_kind(
1361 &mut self.conversation.0,
1362 &kind,
1363 &prompt,
1364 &display,
1365 &mut on_event,
1366 )
1367 .await;
1368 if let Some(store) = &self.harness.memory {
1371 let _ = store.persist(&self.conversation.0);
1372 }
1373 let output = output?;
1374 Ok(RunResult {
1375 answer: final_answer(&self.conversation.0.messages).to_owned(),
1376 output,
1377 turn: self.conversation.0.last_turn.clone(),
1378 usage: self.conversation.0.usage,
1379 })
1380 }
1381
1382 #[cfg(feature = "agent86ui")]
1391 pub async fn ui_action(&mut self, action: Action) -> Result<RunResult, RunError> {
1392 self.ui_action_with_events(action, |_| {}).await
1393 }
1394
1395 #[cfg(feature = "agent86ui")]
1397 pub async fn ui_action_with_events(
1398 &mut self,
1399 action: Action,
1400 on_event: impl FnMut(TurnEvent<'_>),
1401 ) -> Result<RunResult, RunError> {
1402 let ui = self
1403 .harness
1404 .context
1405 .ui
1406 .clone()
1407 .ok_or_else(|| RunError::UiAction("this agent has no renderer".into()))?;
1408 ui.check_action(&action, None).map_err(RunError::UiAction)?;
1409 self.harness.recorder.event(
1410 &self.conversation.0.session_id,
1411 "ui_action",
1412 vec![
1413 ("surface", json!(action.surface_id)),
1414 ("name", json!(action.name)),
1415 ("component", json!(action.source_component_id)),
1416 ("waited", json!(false)),
1417 ],
1418 );
1419 let text = crate::agent86ui::action_text(&action);
1420 self.run_with_events(Turn::Goal(text), on_event).await
1421 }
1422
1423 pub fn cancel_handle(&self) -> CancelToken {
1426 self.harness.cancel.clone()
1427 }
1428
1429 pub fn conversation(&self) -> &Conversation {
1431 &self.conversation
1432 }
1433
1434 pub fn with_conversation(mut self, conversation: Conversation) -> Self {
1438 self.conversation = conversation;
1439 #[cfg(feature = "agent86ui")]
1440 self.replay_surfaces();
1441 self
1442 }
1443
1444 #[cfg(feature = "agent86ui")]
1446 fn replay_surfaces(&self) {
1447 if let Some(ui) = &self.harness.context.ui {
1448 ui.replay(&self.conversation.0, &self.harness.context);
1449 }
1450 }
1451
1452 #[cfg(feature = "agent86ui")]
1460 pub fn surfaces(&self) -> Vec<AgentMessage> {
1461 self.harness
1462 .context
1463 .ui
1464 .as_ref()
1465 .map(|ui| ui.snapshot())
1466 .unwrap_or_default()
1467 }
1468
1469 pub fn session_id(&self) -> &str {
1471 self.conversation.id()
1472 }
1473
1474 pub fn secret_names(&self) -> Vec<String> {
1476 self.harness.context.secrets.names()
1477 }
1478
1479 pub fn notes(&self) -> Vec<String> {
1483 let mut notes = self.notices.clone();
1484 if let Some(mcp) = &self.harness.mcp {
1485 notes.extend(mcp.notes());
1486 }
1487 notes.extend(self.harness.tracer.note());
1488 notes
1489 }
1490
1491 pub fn skills(&self) -> Vec<String> {
1493 self.harness.context.skills.keys().cloned().collect()
1494 }
1495
1496 pub fn specialists(&self) -> Vec<String> {
1498 if !self.harness.agents.enabled {
1499 return Vec::new();
1500 }
1501 self.harness
1502 .context
1503 .specialties
1504 .names()
1505 .into_iter()
1506 .map(str::to_owned)
1507 .collect()
1508 }
1509
1510 pub fn tool_names(&self) -> Vec<String> {
1512 self.harness.registry.names()
1513 }
1514
1515 pub fn harness(&self) -> &Harness {
1518 &self.harness
1519 }
1520}
1521
1522#[derive(Debug, Clone, Default, PartialEq)]
1527pub struct Conversation(AgentState);
1528
1529#[derive(Debug, Clone, PartialEq)]
1531pub struct ConversationMessage {
1532 pub role: Role,
1533 pub text: String,
1535 pub tool_calls: Vec<ToolCall>,
1537 pub answers: Option<String>,
1539}
1540
1541impl Conversation {
1542 pub fn new() -> Self {
1544 Self::default()
1545 }
1546
1547 pub fn id(&self) -> &str {
1549 &self.0.session_id
1550 }
1551
1552 pub fn messages(&self) -> Vec<ConversationMessage> {
1554 self.0
1555 .messages
1556 .iter()
1557 .map(|message| ConversationMessage {
1558 role: message.role,
1559 text: message.content.clone(),
1560 tool_calls: message.tool_calls.clone(),
1561 answers: message.tool_call_id.clone(),
1562 })
1563 .collect()
1564 }
1565
1566 pub fn steps(&self) -> usize {
1568 self.0.step_count()
1569 }
1570
1571 pub fn usage(&self) -> Usage {
1573 self.0.usage
1574 }
1575
1576 pub fn last_turn(&self) -> Option<&TurnSummary> {
1578 self.0.last_turn.as_ref()
1579 }
1580
1581 pub fn to_json(&self) -> String {
1583 serde_json::to_string(&self.0).expect("a conversation always serializes")
1584 }
1585
1586 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1589 serde_json::from_str(json).map(Self)
1590 }
1591}
1592
1593type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1597
1598pub struct FnTool {
1601 name: String,
1602 description: String,
1603 parameters: Value,
1604 side_effecting: bool,
1605 run: Box<ToolFn>,
1606}
1607
1608impl FnTool {
1609 pub fn new(
1612 name: impl Into<String>,
1613 description: impl Into<String>,
1614 parameters: Value,
1615 run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
1616 + Send
1617 + Sync
1618 + 'static,
1619 ) -> Self {
1620 Self {
1621 name: name.into(),
1622 description: description.into(),
1623 parameters,
1624 side_effecting: false,
1625 run: Box::new(run),
1626 }
1627 }
1628
1629 pub fn side_effecting(mut self) -> Self {
1632 self.side_effecting = true;
1633 self
1634 }
1635}
1636
1637impl Tool for FnTool {
1638 fn name(&self) -> &str {
1639 &self.name
1640 }
1641
1642 fn description(&self) -> &str {
1643 &self.description
1644 }
1645
1646 fn side_effecting(&self) -> bool {
1647 self.side_effecting
1648 }
1649
1650 fn parameters(&self) -> Value {
1651 self.parameters.clone()
1652 }
1653
1654 fn execute(
1655 &self,
1656 args: &Map<String, Value>,
1657 ctx: &ToolContext,
1658 ) -> Result<ToolResult, ToolError> {
1659 match (self.run)(args, ctx) {
1660 Ok(content) => Ok(ToolResult {
1661 call_id: String::new(),
1662 name: self.name.clone(),
1663 ok: true,
1664 content,
1665 error: None,
1666 metadata: Map::new(),
1667 }),
1668 Err(message) => Err(ToolError::Raised {
1669 exception: "ToolError".to_owned(),
1670 message,
1671 }),
1672 }
1673 }
1674}
1675
1676pub mod providers {
1681 pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
1682 pub use crate::provider::google::{GoogleConfig, GoogleProvider};
1683 pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
1684 pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
1685 pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
1686 pub use crate::types::{
1687 Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
1688 };
1689}