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;
103pub use crate::verify::{Verification, VerifyStatus};
104#[cfg(feature = "agent86ui")]
107pub use agent86_ui;
108#[cfg(feature = "agent86ui")]
109pub use agent86_ui::{Action, AgentMessage, AgentMessageKind, Catalog};
110pub use providers::Provider;
111
112#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
115pub enum Builtins {
116 #[default]
118 None,
119 ReadOnly,
121 Files,
123 All,
126}
127
128fn default_system(runs_commands: bool) -> String {
130 let identity = crate::prompt::BASE_IDENTITY.trim();
131 if runs_commands {
132 format!(
133 "{identity}\n\nEnvironment: {}",
134 crate::prompt::platform_note(crate::config::SandboxMode::Subprocess)
135 )
136 } else {
137 identity.to_owned()
138 }
139}
140
141#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
146#[non_exhaustive]
147pub enum BuildError {
148 #[error("no provider was given; call AgentBuilder::provider")]
149 MissingProvider,
150 #[error("no workspace was given; call AgentBuilder::workspace")]
151 MissingWorkspace,
152 #[error("could not open the workspace {path}: {detail}")]
153 Workspace { path: String, detail: String },
154 #[error("could not register a tool: {0}")]
155 Tool(String),
156 #[error("could not open the trace directory: {0}")]
157 Trace(String),
158 #[error("MCP server '{name}' failed to start: {reason}")]
159 Mcp { name: String, reason: String },
160 #[error("a session to resume needs memory; call AgentBuilder::memory")]
161 SessionWithoutMemory,
162 #[error("no session '{0}' in memory")]
163 SessionNotFound(String),
164 #[error("memory could not be read: {0}")]
165 Memory(String),
166 #[error("no model named '{0}'; add it with AgentBuilder::model")]
167 UnknownModel(String),
168 #[error("the secret {name} was refused: {reason}")]
171 Secret { name: String, reason: String },
172 #[cfg(feature = "agent86ui")]
174 #[error("agent86UI could not be set up: {0}")]
175 Ui(String),
176}
177
178#[derive(Debug, Clone, PartialEq, thiserror::Error)]
183#[non_exhaustive]
184pub enum RunError {
185 #[error(transparent)]
187 Harness(#[from] HarnessError),
188 #[error("no skill named '{0}'")]
190 UnknownSkill(String),
191 #[error("no specialist named '{0}'")]
194 UnknownSpecialist(String),
195 #[cfg(feature = "agent86ui")]
199 #[error("the UI action was refused: {0}")]
200 UiAction(String),
201}
202
203type Approver = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
206
207type SecretAsker = Box<dyn Fn(&SecretRequest) -> Option<String> + Send + Sync>;
209
210pub struct AgentBuilder {
212 provider: Option<Arc<dyn Provider>>,
213 workspace: Option<PathBuf>,
214 system: Option<String>,
215 builtins: Builtins,
216 tools: Vec<Box<dyn Tool>>,
217 approval: ApprovalMode,
218 approver: Option<Approver>,
219 limits: LimitsConfig,
220 guardrails: GuardrailsConfig,
221 context_window: u64,
222 max_output_tokens: u32,
223 trace_dir: Option<PathBuf>,
224 tool_timeout: Duration,
225 mcp_servers: Vec<(String, McpServer)>,
226 memory: Option<Memory>,
227 session: Option<String>,
228 skill_dirs: Vec<PathBuf>,
229 subagents: Option<SubAgents>,
230 verify: Option<(String, u32)>,
231 models: IndexMap<String, Model>,
232 triage: Option<(String, String)>,
233 otel: Option<Otel>,
234 on_limit: Option<crate::limits::LimitPrompt>,
235 on_secret: Option<SecretAsker>,
236 #[cfg(feature = "agent86ui")]
237 ui: Option<Ui>,
238 secrets: Vec<(String, String)>,
240}
241
242impl Default for AgentBuilder {
243 fn default() -> Self {
244 let config = builtin_config();
245 Self {
246 provider: None,
247 workspace: None,
248 system: None,
249 builtins: Builtins::None,
250 tools: Vec::new(),
251 approval: ApprovalMode::Ask,
252 approver: None,
253 max_output_tokens: config.limits.max_output_tokens,
254 tool_timeout: Duration::from_secs(config.limits.tool_timeout_s),
255 limits: config.limits,
256 guardrails: config.guardrails,
257 context_window: DEFAULT_CONTEXT_WINDOW,
258 trace_dir: None,
259 mcp_servers: Vec::new(),
260 memory: None,
261 session: None,
262 skill_dirs: Vec::new(),
263 subagents: None,
264 verify: None,
265 models: IndexMap::new(),
266 triage: None,
267 otel: None,
268 on_limit: None,
269 on_secret: None,
270 #[cfg(feature = "agent86ui")]
271 ui: None,
272 secrets: Vec::new(),
273 }
274 }
275}
276
277pub const DEFAULT_CONTEXT_WINDOW: u64 = 128_000;
280
281impl AgentBuilder {
282 pub fn provider(mut self, provider: Arc<dyn Provider>) -> Self {
285 self.provider = Some(provider);
286 self
287 }
288
289 pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
292 self.workspace = Some(path.into());
293 self
294 }
295
296 pub fn system_prompt(mut self, text: impl Into<String>) -> Self {
302 self.system = Some(text.into());
303 self
304 }
305
306 pub fn builtins(mut self, builtins: Builtins) -> Self {
308 self.builtins = builtins;
309 self
310 }
311
312 pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
314 self.tools.push(Box::new(tool));
315 self
316 }
317
318 pub fn approval(mut self, mode: ApprovalMode) -> Self {
322 self.approval = mode;
323 self
324 }
325
326 pub fn approver(
330 mut self,
331 approver: impl Fn(&str, &ApprovalPreview) -> bool + Send + Sync + 'static,
332 ) -> Self {
333 self.approver = Some(Box::new(approver));
334 self
335 }
336
337 pub fn max_steps(mut self, steps: u32) -> Self {
339 self.limits.max_steps = steps;
340 self
341 }
342
343 pub fn max_cost_usd(mut self, usd: f64) -> Self {
346 self.limits.max_cost_usd = usd;
347 self
348 }
349
350 pub fn max_wall_clock_s(mut self, seconds: u64) -> Self {
352 self.limits.max_wall_clock_s = seconds;
353 self
354 }
355
356 pub fn tool_timeout(mut self, timeout: Duration) -> Self {
358 self.tool_timeout = timeout;
359 self
360 }
361
362 pub fn context_window(mut self, tokens: u64) -> Self {
364 self.context_window = tokens;
365 self
366 }
367
368 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
370 self.max_output_tokens = tokens;
371 self
372 }
373
374 pub fn guardrails(mut self, guardrails: GuardrailsConfig) -> Self {
377 self.guardrails = guardrails;
378 self
379 }
380
381 pub fn trace_dir(mut self, dir: impl Into<PathBuf>) -> Self {
384 self.trace_dir = Some(dir.into());
385 self
386 }
387
388 pub fn mcp_server(mut self, name: impl Into<String>, server: McpServer) -> Self {
393 self.mcp_servers.push((name.into(), server));
394 self
395 }
396
397 pub fn memory(mut self, memory: Memory) -> Self {
402 self.memory = Some(memory);
403 self
404 }
405
406 pub fn session(mut self, id: impl Into<String>) -> Self {
409 self.session = Some(id.into());
410 self
411 }
412
413 pub fn skills_dir(mut self, dir: impl Into<PathBuf>) -> Self {
420 self.skill_dirs.push(dir.into());
421 self
422 }
423
424 pub fn verify(mut self, command: impl Into<String>, max_attempts: u32) -> Self {
430 self.verify = Some((command.into(), max_attempts));
431 self
432 }
433
434 pub fn subagents(mut self, subagents: SubAgents) -> Self {
436 self.subagents = Some(subagents);
437 self
438 }
439
440 pub fn model(mut self, name: impl Into<String>, model: Model) -> Self {
444 self.models.insert(name.into(), model);
445 self
446 }
447
448 pub fn triage(mut self, cheap: impl Into<String>, frontier: impl Into<String>) -> Self {
454 self.triage = Some((cheap.into(), frontier.into()));
455 self
456 }
457
458 pub fn otel(mut self, otel: Otel) -> Self {
464 self.otel = Some(otel);
465 self
466 }
467
468 pub fn on_limit(
475 mut self,
476 decide: impl Fn(&LimitHit) -> Option<u32> + Send + Sync + 'static,
477 ) -> Self {
478 self.on_limit = Some(Box::new(decide));
479 self
480 }
481
482 pub fn on_secret_request(
490 mut self,
491 answer: impl Fn(&SecretRequest) -> Option<String> + Send + Sync + 'static,
492 ) -> Self {
493 self.on_secret = Some(Box::new(answer));
494 self
495 }
496
497 #[cfg(feature = "agent86ui")]
505 pub fn ui(mut self, ui: Ui) -> Self {
506 self.ui = Some(ui);
507 self
508 }
509
510 pub fn secret(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
517 self.secrets.push((name.into(), value.into()));
518 self
519 }
520
521 pub fn build(self) -> Result<Agent, BuildError> {
525 let router = self.router()?;
526 let provider = self.provider.ok_or(BuildError::MissingProvider)?;
527 let workspace = self.workspace.ok_or(BuildError::MissingWorkspace)?;
528 let mut context = ToolContext::new(&workspace).map_err(|error| BuildError::Workspace {
529 path: workspace.display().to_string(),
530 detail: error.to_string(),
531 })?;
532 context.policy.timeout = self.tool_timeout;
533 context.executor = Executor::Subprocess;
534 for (name, value) in &self.secrets {
535 let refused = |reason: &str| BuildError::Secret {
536 name: name.clone(),
537 reason: reason.to_owned(),
538 };
539 if !crate::vault::valid_name(name) {
540 return Err(refused("not a valid environment variable name"));
541 }
542 let answer = crate::vault::SecretAnswer {
543 value: value.clone(),
544 remember: false,
545 };
546 context.secrets.accept(name, answer).map_err(|_| {
547 refused(&format!(
548 "shorter than {} characters",
549 crate::vault::MIN_SECRET_CHARS
550 ))
551 })?;
552 }
553
554 let registry = registry_for(self.builtins);
555 let runs_commands = ["run_command", "python_exec"]
557 .iter()
558 .any(|name| registry.get(name).is_some());
559 for tool in self.tools {
560 registry.register(tool).map_err(BuildError::Tool)?;
561 }
562
563 let store = self.memory.as_ref().map(|memory| memory.store.clone());
564 let state = match (&self.session, &store) {
565 (None, _) => AgentState::new(),
566 (Some(_), None) => return Err(BuildError::SessionWithoutMemory),
567 (Some(id), Some(store)) => store
568 .load(id)
569 .map_err(|error| BuildError::Memory(error.0))?
570 .ok_or_else(|| BuildError::SessionNotFound(id.clone()))?,
571 };
572 if let Some(memory) = &self.memory {
573 let (episodes, sessions, days) = memory.retention;
574 store
575 .as_ref()
576 .expect("memory gives a store")
577 .enforce_retention(episodes, sessions, days)
578 .map_err(|error| BuildError::Memory(error.0))?;
579 for tool in [
580 Box::new(crate::tools::memory::RememberTool) as Box<dyn Tool>,
581 Box::new(crate::tools::memory::RecallTool),
582 ] {
583 registry.register(tool).map_err(BuildError::Tool)?;
584 }
585 }
586 context.memory = store.clone();
587
588 let skills = Arc::new(crate::skills::discover_in(&self.skill_dirs));
591 if !skills.is_empty() {
592 context.policy.allow(
593 self.skill_dirs
594 .iter()
595 .filter(|dir| dir.is_dir())
596 .filter_map(|dir| std::fs::canonicalize(dir).ok())
597 .collect::<Vec<_>>(),
598 );
599 registry
600 .register(Box::new(crate::tools::skills::UseSkillTool))
601 .map_err(BuildError::Tool)?;
602 }
603 context.skills = Arc::clone(&skills);
604
605 let config = builtin_config();
607 let mut agents = crate::config::AgentsConfig {
608 enabled: false,
609 ..config.agents.clone()
610 };
611 let mut notices = Vec::new();
612 if let Some(subagents) = &self.subagents {
613 agents = crate::config::AgentsConfig {
614 enabled: true,
615 max_depth: subagents.max_depth,
616 max_steps: subagents.max_steps.min(self.limits.max_steps.max(1)),
617 max_parallel: subagents
618 .max_parallel
619 .clamp(1, crate::config::MAX_PARALLEL_CEILING),
620 };
621 let mut specialties = if subagents.built_ins {
622 Specialties::built_in()
623 } else {
624 Specialties::default()
625 };
626 for dir in &subagents.dirs {
627 specialties.add_user_dir(dir);
628 }
629 notices.extend(specialties.notices.iter().cloned());
630 context.specialties = Arc::new(specialties);
631 registry
632 .register(Box::new(crate::tools::delegate::DelegateTool))
633 .map_err(BuildError::Tool)?;
634 }
635
636 let tracer = self
637 .otel
638 .as_ref()
639 .map(|otel| crate::otel::Tracer::to(otel.destination.clone()))
640 .unwrap_or_default();
641
642 if let Some(answer) = self.on_secret {
643 context
644 .secrets
645 .set_prompt(Some(Box::new(move |request: &SecretRequest| {
646 answer(request).map(|value| crate::vault::SecretAnswer {
647 value,
648 remember: false,
649 })
650 })));
651 registry
652 .register(Box::new(crate::tools::secret::RequestSecretTool))
653 .map_err(BuildError::Tool)?;
654 }
655 #[cfg(feature = "agent86ui")]
656 let mut ui_session = None;
657 #[cfg(feature = "agent86ui")]
658 if let Some(ui) = self.ui {
659 if ui.catalogs.is_empty() {
660 return Err(BuildError::Ui(
661 "a renderer needs at least one catalog".into(),
662 ));
663 }
664 ui_session = Some(
665 crate::agent86ui::UiSession::new(ui.catalogs)
666 .map_err(|error| BuildError::Ui(error.to_string()))?
667 .with_egress(self.guardrails.egress)
668 .with_remote_media(ui.remote_media)
669 .with_waiter(ui.on_wait),
670 );
671 }
672 let mut session_limits = crate::limits::SessionLimits::default();
673 session_limits.prompt = self.on_limit;
674
675 let mcp = start_mcp(&self.mcp_servers, ®istry)?;
676
677 let recorder = match &self.trace_dir {
678 None => Recorder::disabled(),
679 Some(dir) => {
680 std::fs::create_dir_all(dir)
681 .map_err(|error| BuildError::Trace(error.to_string()))?;
682 let defaults = builtin_config().observability;
683 Recorder::from_config(&ObservabilityConfig {
684 trace: true,
685 path: dir.display().to_string(),
686 otel: false,
687 ..defaults
688 })
689 }
690 }
691 .with_secrets(context.secrets.clone());
692
693 let mut limits = self.limits;
694 limits.max_output_tokens = self.max_output_tokens;
695 let mut system = self.system.unwrap_or_else(|| default_system(runs_commands));
696 system.push_str(&crate::prompt::skills_section(
697 skills.values().map(AsRef::as_ref),
698 ));
699 let mut harness = Harness {
700 provider,
701 router,
702 tracer,
703 registry,
704 context,
705 limits,
706 agents,
707 system: Message {
708 role: Role::System,
709 content: system,
710 tool_calls: Vec::new(),
711 tool_call_id: None,
712 name: None,
713 },
714 max_tokens: self.max_output_tokens,
715 session_limits,
716 context_window: self.context_window,
717 gate: ApprovalGate::new(self.approval, self.approver),
718 guardrails: Guardrails::new(&self.guardrails),
719 recorder,
720 mcp,
721 memory: store,
722 cancel: Default::default(),
723 subagents: Default::default(),
724 calibration: Default::default(),
725 verify: match &self.verify {
726 Some((command, attempts)) => crate::verify::Verify::new(Some(command), *attempts),
727 None => Default::default(),
728 },
729 };
730 #[cfg(feature = "agent86ui")]
731 if let Some(session) = ui_session {
732 harness.attach_ui(session).map_err(BuildError::Tool)?;
733 harness
735 .offer_questions_as_forms()
736 .map_err(BuildError::Tool)?;
737 }
738 harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
739 harness.gate.queue.watch(harness.cancel.clone());
740 harness
741 .context
742 .secrets
743 .set_queue(harness.gate.queue.clone());
744 let agent = Agent {
745 harness,
746 conversation: Conversation(state),
747 notices,
748 };
749 #[cfg(feature = "agent86ui")]
751 agent.replay_surfaces();
752 Ok(agent)
753 }
754
755 fn router(&self) -> Result<Router, BuildError> {
758 if self.models.is_empty() {
759 return match &self.triage {
760 Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
761 None => Ok(Router::default()),
762 };
763 }
764 let (triage, cheap, frontier) = match &self.triage {
765 Some((cheap, frontier)) => {
766 for name in [cheap, frontier] {
767 if !self.models.contains_key(name) {
768 return Err(BuildError::UnknownModel(name.clone()));
769 }
770 }
771 (true, cheap.as_str(), frontier.as_str())
772 }
773 None => (false, "", ""),
774 };
775 let window = self.context_window;
776 let output = self.max_output_tokens;
777 let models: HashMap<String, RoutedModel> = self
778 .models
779 .iter()
780 .map(|(name, model)| {
781 (
782 name.clone(),
783 RoutedModel {
784 reference: name.clone(),
785 provider: Arc::clone(&model.provider),
786 max_tokens: model.max_output_tokens.unwrap_or(output),
787 context_window: model.context_window.unwrap_or(window),
788 output_setting: "max_output_tokens".to_owned(),
789 },
790 )
791 })
792 .collect();
793 Ok(Router::new(
794 triage,
795 cheap,
796 frontier,
797 Box::new(move |name| {
798 models
799 .get(name)
800 .cloned()
801 .ok_or_else(|| format!("no model named '{name}'"))
802 }),
803 ))
804 }
805}
806
807#[derive(Debug, Clone)]
817pub struct SubAgents {
818 max_depth: u32,
819 max_steps: u32,
820 max_parallel: u32,
821 built_ins: bool,
822 dirs: Vec<PathBuf>,
823}
824
825impl Default for SubAgents {
826 fn default() -> Self {
827 let agents = builtin_config().agents;
828 Self {
829 max_depth: agents.max_depth,
830 max_steps: agents.max_steps,
831 max_parallel: agents.max_parallel,
832 built_ins: true,
833 dirs: Vec::new(),
834 }
835 }
836}
837
838impl SubAgents {
839 pub fn new() -> Self {
842 Self::default()
843 }
844
845 pub fn max_depth(mut self, depth: u32) -> Self {
847 self.max_depth = depth;
848 self
849 }
850
851 pub fn max_steps(mut self, steps: u32) -> Self {
853 self.max_steps = steps;
854 self
855 }
856
857 pub fn max_parallel(mut self, parallel: u32) -> Self {
859 self.max_parallel = parallel;
860 self
861 }
862
863 pub fn without_built_ins(mut self) -> Self {
865 self.built_ins = false;
866 self
867 }
868
869 pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
875 self.dirs.push(dir.into());
876 self
877 }
878}
879
880#[derive(Clone)]
882pub struct Model {
883 provider: Arc<dyn Provider>,
884 context_window: Option<u64>,
885 max_output_tokens: Option<u32>,
886}
887
888impl std::fmt::Debug for Model {
889 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
890 f.debug_struct("Model")
891 .field("provider", &self.provider.name())
892 .field("model", &self.provider.model())
893 .field("context_window", &self.context_window)
894 .field("max_output_tokens", &self.max_output_tokens)
895 .finish()
896 }
897}
898
899impl Model {
900 pub fn new(provider: Arc<dyn Provider>) -> Self {
902 Self {
903 provider,
904 context_window: None,
905 max_output_tokens: None,
906 }
907 }
908
909 pub fn context_window(mut self, tokens: u64) -> Self {
911 self.context_window = Some(tokens);
912 self
913 }
914
915 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
917 self.max_output_tokens = Some(tokens);
918 self
919 }
920}
921
922#[cfg(feature = "agent86ui")]
925#[derive(Clone)]
926pub struct Ui {
927 catalogs: Vec<Catalog>,
928 remote_media: bool,
929 on_wait: Option<crate::agent86ui::UiWaiter>,
930}
931
932#[cfg(feature = "agent86ui")]
933impl std::fmt::Debug for Ui {
934 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
935 f.debug_struct("Ui")
936 .field(
937 "catalogs",
938 &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
939 )
940 .field("remote_media", &self.remote_media)
941 .field("on_wait", &self.on_wait.is_some())
942 .finish()
943 }
944}
945
946#[cfg(feature = "agent86ui")]
947impl Ui {
948 pub fn basic() -> Self {
951 Self::new([Catalog::basic().clone()])
952 }
953
954 pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
957 Self {
958 catalogs: catalogs.into_iter().collect(),
959 remote_media: false,
960 on_wait: None,
961 }
962 }
963
964 pub fn on_wait(
973 mut self,
974 answer: impl Fn(&UiWait) -> Option<Action> + Send + Sync + 'static,
975 ) -> Self {
976 self.on_wait = Some(std::sync::Arc::new(answer));
977 self
978 }
979
980 pub fn allow_remote_media(mut self) -> Self {
985 self.remote_media = true;
986 self
987 }
988
989 pub fn catalogs(&self) -> &[Catalog] {
991 &self.catalogs
992 }
993}
994
995#[derive(Debug, Clone)]
997pub struct Otel {
998 destination: crate::otel::Destination,
999}
1000
1001impl Otel {
1002 pub fn otlp(traces_url: impl Into<String>) -> Self {
1005 Self {
1006 destination: crate::otel::Destination::Otlp {
1007 url: traces_url.into(),
1008 headers: Vec::new(),
1009 timeout: Duration::from_secs(10),
1010 },
1011 }
1012 }
1013
1014 pub fn console() -> Self {
1016 Self {
1017 destination: crate::otel::Destination::Console,
1018 }
1019 }
1020
1021 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1023 if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
1024 headers.push((name.into(), value.into()));
1025 }
1026 self
1027 }
1028
1029 pub fn timeout(mut self, timeout: Duration) -> Self {
1031 if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
1032 *limit = timeout;
1033 }
1034 self
1035 }
1036}
1037
1038fn start_mcp(
1041 servers: &[(String, McpServer)],
1042 registry: &ToolRegistry,
1043) -> Result<Option<Arc<McpManager>>, BuildError> {
1044 if servers.is_empty() {
1045 return Ok(None);
1046 }
1047 let manager = Arc::new(McpManager::empty(&builtin_config()));
1048 manager.attach(registry);
1049 let mut seen: Vec<&str> = Vec::new();
1050 for (name, server) in servers {
1051 let failed = |reason: String| BuildError::Mcp {
1052 name: name.clone(),
1053 reason,
1054 };
1055 if seen.contains(&name.as_str()) {
1056 return Err(failed("another server was given the same name".to_owned()));
1057 }
1058 seen.push(name);
1059 let mut config = server.config.clone();
1060 config.resolve_transport().map_err(failed)?;
1061 manager
1062 .start_server(
1063 name,
1064 &config,
1065 &server.literal_refs(),
1066 &NoSecretStore,
1067 config.connect_timeout_s,
1068 )
1069 .map_err(failed)?;
1070 let (_, collisions) = manager.mount(name);
1071 if !collisions.is_empty() {
1072 return Err(BuildError::Tool(format!(
1073 "MCP server '{name}' offers tools already taken: {}",
1074 collisions.join(", ")
1075 )));
1076 }
1077 }
1078 Ok(Some(manager))
1079}
1080
1081#[derive(Debug, Clone)]
1086pub struct McpServer {
1087 config: McpServerConfig,
1088}
1089
1090impl McpServer {
1091 fn from(value: Value) -> Self {
1092 Self {
1093 config: serde_json::from_value(value).expect("a server config always deserializes"),
1094 }
1095 }
1096
1097 pub fn stdio<S: Into<String>>(
1101 command: impl Into<String>,
1102 args: impl IntoIterator<Item = S>,
1103 ) -> Self {
1104 let args: Vec<String> = args.into_iter().map(Into::into).collect();
1105 Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
1106 }
1107
1108 pub fn http(url: impl Into<String>) -> Self {
1110 Self::from(json!({"url": url.into(), "transport": "http"}))
1111 }
1112
1113 pub fn sse(url: impl Into<String>) -> Self {
1115 Self::from(json!({"url": url.into(), "transport": "sse"}))
1116 }
1117
1118 pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1120 self.config.env.insert(name.into(), value.into());
1121 self
1122 }
1123
1124 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1126 self.config.headers.insert(name.into(), value.into());
1127 self
1128 }
1129
1130 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
1132 self.config.connect_timeout_s = timeout.as_secs_f64();
1133 self
1134 }
1135
1136 pub fn call_timeout(mut self, timeout: Duration) -> Self {
1138 self.config.call_timeout_s = timeout.as_secs_f64();
1139 self
1140 }
1141
1142 pub fn max_result_chars(mut self, chars: usize) -> Self {
1144 self.config.max_result_chars = chars;
1145 self
1146 }
1147
1148 fn literal_refs(&self) -> HashMap<String, String> {
1151 let config = &self.config;
1152 config
1153 .args
1154 .iter()
1155 .chain(config.env.values())
1156 .chain(config.url.iter())
1157 .chain(config.headers.values())
1158 .flat_map(|text| var_ref_names(text))
1159 .map(|name| (name.clone(), format!("${{{name}}}")))
1160 .collect()
1161 }
1162}
1163
1164#[derive(Clone)]
1168pub struct Memory {
1169 store: SessionStore,
1170 retention: (i64, i64, f64),
1171}
1172
1173impl std::fmt::Debug for Memory {
1174 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1175 f.debug_struct("Memory")
1176 .field("retention", &self.retention)
1177 .finish_non_exhaustive()
1178 }
1179}
1180
1181impl Memory {
1182 pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1185 Self::wrap(SessionStore::open(path.as_ref()))
1186 }
1187
1188 pub fn open_with(
1192 path: impl AsRef<Path>,
1193 embedder: Arc<dyn Embedder>,
1194 ) -> Result<Self, BuildError> {
1195 Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
1196 }
1197
1198 pub fn in_memory() -> Result<Self, BuildError> {
1200 Self::open(":memory:")
1201 }
1202
1203 fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
1204 let memory = builtin_config().memory;
1205 Ok(Self {
1206 store: store.map_err(|error| BuildError::Memory(error.0))?,
1207 retention: (
1208 memory.retention_max_episodes,
1209 memory.retention_max_sessions,
1210 memory.retention_max_age_days,
1211 ),
1212 })
1213 }
1214
1215 pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
1219 self.retention = (episodes, sessions, max_age_days);
1220 self
1221 }
1222
1223 pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
1225 Ok(self
1226 .store
1227 .recent_sessions(limit)
1228 .map_err(|error| BuildError::Memory(error.0))?
1229 .into_iter()
1230 .map(|session| (session.session_id, session.title))
1231 .collect())
1232 }
1233
1234 pub fn store(&self) -> &SessionStore {
1237 &self.store
1238 }
1239}
1240
1241fn registry_for(builtins: Builtins) -> ToolRegistry {
1242 let registry = ToolRegistry::new();
1243 let mut tools: Vec<Box<dyn Tool>> = Vec::new();
1244 if builtins != Builtins::None {
1245 tools.push(Box::new(files::ReadFileTool));
1246 tools.push(Box::new(files::ListDirTool));
1247 tools.push(Box::new(search::SearchFilesTool));
1248 tools.push(Box::new(search::FindFilesTool));
1249 }
1250 if matches!(builtins, Builtins::Files | Builtins::All) {
1251 tools.push(Box::new(files::WriteFileTool));
1252 tools.push(Box::new(files::EditFileTool));
1253 }
1254 if builtins == Builtins::All {
1255 tools.push(Box::new(exec::RunCommandTool));
1256 tools.push(Box::new(exec::PythonExecTool));
1257 tools.push(Box::new(web::WebFetchTool));
1258 }
1259 for tool in tools {
1260 registry
1261 .register(tool)
1262 .expect("built-in tool names are unique");
1263 }
1264 registry
1265}
1266
1267#[derive(Debug, Clone, PartialEq)]
1273#[non_exhaustive]
1274pub struct RunResult {
1275 pub answer: String,
1278 pub output: String,
1281 pub turn: Option<TurnSummary>,
1283 pub usage: Usage,
1285 pub verification: Option<Verification>,
1288}
1289
1290#[derive(Debug, Clone, PartialEq, Eq)]
1293pub enum Turn {
1294 Goal(String),
1296 Skill { name: String, task: String },
1299 Specialist {
1303 name: String,
1304 task: String,
1305 with_context: bool,
1306 },
1307}
1308
1309impl Turn {
1310 pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
1311 Self::Skill {
1312 name: name.into(),
1313 task: task.into(),
1314 }
1315 }
1316
1317 pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
1318 Self::Specialist {
1319 name: name.into(),
1320 task: task.into(),
1321 with_context: false,
1322 }
1323 }
1324
1325 pub fn with_context(mut self) -> Self {
1327 if let Self::Specialist { with_context, .. } = &mut self {
1328 *with_context = true;
1329 }
1330 self
1331 }
1332}
1333
1334impl From<&str> for Turn {
1335 fn from(goal: &str) -> Self {
1336 Self::Goal(goal.to_owned())
1337 }
1338}
1339
1340impl From<String> for Turn {
1341 fn from(goal: String) -> Self {
1342 Self::Goal(goal)
1343 }
1344}
1345
1346impl From<&String> for Turn {
1347 fn from(goal: &String) -> Self {
1348 Self::Goal(goal.clone())
1349 }
1350}
1351
1352pub struct Agent {
1355 harness: Harness,
1356 conversation: Conversation,
1357 notices: Vec<String>,
1359}
1360
1361impl Agent {
1362 pub fn builder() -> AgentBuilder {
1363 AgentBuilder::default()
1364 }
1365
1366 pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1368 self.run_with_events(turn, |_| {}).await
1369 }
1370
1371 pub async fn run_with_events(
1374 &mut self,
1375 turn: impl Into<Turn>,
1376 mut on_event: impl FnMut(TurnEvent<'_>),
1377 ) -> Result<RunResult, RunError> {
1378 let (kind, prompt, display) = match turn.into() {
1379 Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
1380 Turn::Skill { name, task } => {
1381 let skill = self
1382 .harness
1383 .context
1384 .skills
1385 .get(&name)
1386 .cloned()
1387 .ok_or(RunError::UnknownSkill(name.clone()))?;
1388 let display = format!("/{name} {task}").trim_end().to_owned();
1389 (TurnKind::Skill(skill), task, display)
1390 }
1391 Turn::Specialist {
1392 name,
1393 task,
1394 with_context,
1395 } => {
1396 if !self.harness.agents.enabled
1397 || self.harness.context.specialties.get(&name).is_none()
1398 {
1399 return Err(RunError::UnknownSpecialist(name));
1400 }
1401 let display = format!("/agent {name} {task}");
1402 (TurnKind::Agent { name, with_context }, task, display)
1403 }
1404 };
1405 let output = self
1406 .harness
1407 .run_kind(
1408 &mut self.conversation.0,
1409 &kind,
1410 &prompt,
1411 &display,
1412 &mut on_event,
1413 )
1414 .await;
1415 if let Some(store) = &self.harness.memory {
1418 let _ = store.persist(&self.conversation.0);
1419 }
1420 let output = output?;
1421 Ok(RunResult {
1422 answer: final_answer(&self.conversation.0.messages).to_owned(),
1423 output,
1424 turn: self.conversation.0.last_turn.clone(),
1425 usage: self.conversation.0.usage,
1426 verification: self.harness.verify.last(),
1427 })
1428 }
1429
1430 #[cfg(feature = "agent86ui")]
1439 pub async fn ui_action(&mut self, action: Action) -> Result<RunResult, RunError> {
1440 self.ui_action_with_events(action, |_| {}).await
1441 }
1442
1443 #[cfg(feature = "agent86ui")]
1445 pub async fn ui_action_with_events(
1446 &mut self,
1447 action: Action,
1448 on_event: impl FnMut(TurnEvent<'_>),
1449 ) -> Result<RunResult, RunError> {
1450 let text = self
1451 .harness
1452 .accept_ui_action(&self.conversation.0.session_id, &action)
1453 .map_err(RunError::UiAction)?;
1454 self.run_with_events(Turn::Goal(text), on_event).await
1455 }
1456
1457 pub fn cancel_handle(&self) -> CancelToken {
1460 self.harness.cancel.clone()
1461 }
1462
1463 pub fn conversation(&self) -> &Conversation {
1465 &self.conversation
1466 }
1467
1468 pub fn with_conversation(mut self, conversation: Conversation) -> Self {
1472 self.conversation = conversation;
1473 #[cfg(feature = "agent86ui")]
1474 self.replay_surfaces();
1475 self
1476 }
1477
1478 #[cfg(feature = "agent86ui")]
1480 fn replay_surfaces(&self) {
1481 if let Some(ui) = &self.harness.context.ui {
1482 ui.replay(&self.conversation.0, &self.harness.context);
1483 }
1484 }
1485
1486 #[cfg(feature = "agent86ui")]
1494 pub fn surfaces(&self) -> Vec<AgentMessage> {
1495 self.harness
1496 .context
1497 .ui
1498 .as_ref()
1499 .map(|ui| ui.snapshot())
1500 .unwrap_or_default()
1501 }
1502
1503 pub fn session_id(&self) -> &str {
1505 self.conversation.id()
1506 }
1507
1508 pub fn secret_names(&self) -> Vec<String> {
1510 self.harness.context.secrets.names()
1511 }
1512
1513 pub fn notes(&self) -> Vec<String> {
1517 let mut notes = self.notices.clone();
1518 if let Some(mcp) = &self.harness.mcp {
1519 notes.extend(mcp.notes());
1520 }
1521 notes.extend(self.harness.tracer.note());
1522 notes
1523 }
1524
1525 pub fn skills(&self) -> Vec<String> {
1527 self.harness.context.skills.keys().cloned().collect()
1528 }
1529
1530 pub fn specialists(&self) -> Vec<String> {
1532 if !self.harness.agents.enabled {
1533 return Vec::new();
1534 }
1535 self.harness
1536 .context
1537 .specialties
1538 .names()
1539 .into_iter()
1540 .map(str::to_owned)
1541 .collect()
1542 }
1543
1544 pub fn tool_names(&self) -> Vec<String> {
1546 self.harness.registry.names()
1547 }
1548
1549 pub fn harness(&self) -> &Harness {
1552 &self.harness
1553 }
1554}
1555
1556#[derive(Debug, Clone, Default, PartialEq)]
1561pub struct Conversation(AgentState);
1562
1563#[derive(Debug, Clone, PartialEq)]
1565pub struct ConversationMessage {
1566 pub role: Role,
1567 pub text: String,
1569 pub tool_calls: Vec<ToolCall>,
1571 pub answers: Option<String>,
1573}
1574
1575impl Conversation {
1576 pub fn new() -> Self {
1578 Self::default()
1579 }
1580
1581 pub fn id(&self) -> &str {
1583 &self.0.session_id
1584 }
1585
1586 pub fn messages(&self) -> Vec<ConversationMessage> {
1588 self.0
1589 .messages
1590 .iter()
1591 .map(|message| ConversationMessage {
1592 role: message.role,
1593 text: message.content.clone(),
1594 tool_calls: message.tool_calls.clone(),
1595 answers: message.tool_call_id.clone(),
1596 })
1597 .collect()
1598 }
1599
1600 pub fn steps(&self) -> usize {
1602 self.0.step_count()
1603 }
1604
1605 pub fn usage(&self) -> Usage {
1607 self.0.usage
1608 }
1609
1610 pub fn last_turn(&self) -> Option<&TurnSummary> {
1612 self.0.last_turn.as_ref()
1613 }
1614
1615 pub fn to_json(&self) -> String {
1617 serde_json::to_string(&self.0).expect("a conversation always serializes")
1618 }
1619
1620 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1623 serde_json::from_str(json).map(Self)
1624 }
1625}
1626
1627type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1631
1632pub struct FnTool {
1635 name: String,
1636 description: String,
1637 parameters: Value,
1638 side_effecting: bool,
1639 run: Box<ToolFn>,
1640}
1641
1642impl FnTool {
1643 pub fn new(
1646 name: impl Into<String>,
1647 description: impl Into<String>,
1648 parameters: Value,
1649 run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
1650 + Send
1651 + Sync
1652 + 'static,
1653 ) -> Self {
1654 Self {
1655 name: name.into(),
1656 description: description.into(),
1657 parameters,
1658 side_effecting: false,
1659 run: Box::new(run),
1660 }
1661 }
1662
1663 pub fn side_effecting(mut self) -> Self {
1666 self.side_effecting = true;
1667 self
1668 }
1669}
1670
1671impl Tool for FnTool {
1672 fn name(&self) -> &str {
1673 &self.name
1674 }
1675
1676 fn description(&self) -> &str {
1677 &self.description
1678 }
1679
1680 fn side_effecting(&self) -> bool {
1681 self.side_effecting
1682 }
1683
1684 fn parameters(&self) -> Value {
1685 self.parameters.clone()
1686 }
1687
1688 fn execute(
1689 &self,
1690 args: &Map<String, Value>,
1691 ctx: &ToolContext,
1692 ) -> Result<ToolResult, ToolError> {
1693 match (self.run)(args, ctx) {
1694 Ok(content) => Ok(ToolResult {
1695 call_id: String::new(),
1696 name: self.name.clone(),
1697 ok: true,
1698 content,
1699 error: None,
1700 metadata: Map::new(),
1701 }),
1702 Err(message) => Err(ToolError::Raised {
1703 exception: "ToolError".to_owned(),
1704 message,
1705 }),
1706 }
1707 }
1708}
1709
1710pub mod providers {
1715 pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
1716 pub use crate::provider::google::{GoogleConfig, GoogleProvider};
1717 pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
1718 pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
1719 pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
1720 pub use crate::types::{
1721 Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
1722 };
1723}