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 #[error("{0}")]
205 NotContinuable(String),
206}
207
208type Approver = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
211
212type SecretAsker = Box<dyn Fn(&SecretRequest) -> Option<String> + Send + Sync>;
214
215pub struct AgentBuilder {
217 provider: Option<Arc<dyn Provider>>,
218 workspace: Option<PathBuf>,
219 system: Option<String>,
220 builtins: Builtins,
221 tools: Vec<Box<dyn Tool>>,
222 approval: ApprovalMode,
223 approver: Option<Approver>,
224 limits: LimitsConfig,
225 guardrails: GuardrailsConfig,
226 context_window: u64,
227 max_output_tokens: u32,
228 trace_dir: Option<PathBuf>,
229 tool_timeout: Duration,
230 mcp_servers: Vec<(String, McpServer)>,
231 memory: Option<Memory>,
232 session: Option<String>,
233 skill_dirs: Vec<PathBuf>,
234 subagents: Option<SubAgents>,
235 verify: Option<(String, u32)>,
236 models: IndexMap<String, Model>,
237 triage: Option<(String, String)>,
238 otel: Option<Otel>,
239 on_limit: Option<crate::limits::LimitPrompt>,
240 on_secret: Option<SecretAsker>,
241 #[cfg(feature = "agent86ui")]
242 ui: Option<Ui>,
243 secrets: Vec<(String, String)>,
245}
246
247impl Default for AgentBuilder {
248 fn default() -> Self {
249 let config = builtin_config();
250 Self {
251 provider: None,
252 workspace: None,
253 system: None,
254 builtins: Builtins::None,
255 tools: Vec::new(),
256 approval: ApprovalMode::Ask,
257 approver: None,
258 max_output_tokens: config.limits.max_output_tokens,
259 tool_timeout: Duration::from_secs(config.limits.tool_timeout_s),
260 limits: config.limits,
261 guardrails: config.guardrails,
262 context_window: DEFAULT_CONTEXT_WINDOW,
263 trace_dir: None,
264 mcp_servers: Vec::new(),
265 memory: None,
266 session: None,
267 skill_dirs: Vec::new(),
268 subagents: None,
269 verify: None,
270 models: IndexMap::new(),
271 triage: None,
272 otel: None,
273 on_limit: None,
274 on_secret: None,
275 #[cfg(feature = "agent86ui")]
276 ui: None,
277 secrets: Vec::new(),
278 }
279 }
280}
281
282pub const DEFAULT_CONTEXT_WINDOW: u64 = 128_000;
285
286impl AgentBuilder {
287 pub fn provider(mut self, provider: Arc<dyn Provider>) -> Self {
290 self.provider = Some(provider);
291 self
292 }
293
294 pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
297 self.workspace = Some(path.into());
298 self
299 }
300
301 pub fn system_prompt(mut self, text: impl Into<String>) -> Self {
307 self.system = Some(text.into());
308 self
309 }
310
311 pub fn builtins(mut self, builtins: Builtins) -> Self {
313 self.builtins = builtins;
314 self
315 }
316
317 pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
319 self.tools.push(Box::new(tool));
320 self
321 }
322
323 pub fn approval(mut self, mode: ApprovalMode) -> Self {
327 self.approval = mode;
328 self
329 }
330
331 pub fn approver(
335 mut self,
336 approver: impl Fn(&str, &ApprovalPreview) -> bool + Send + Sync + 'static,
337 ) -> Self {
338 self.approver = Some(Box::new(approver));
339 self
340 }
341
342 pub fn max_steps(mut self, steps: u32) -> Self {
344 self.limits.max_steps = steps;
345 self
346 }
347
348 pub fn max_cost_usd(mut self, usd: f64) -> Self {
351 self.limits.max_cost_usd = usd;
352 self
353 }
354
355 pub fn max_wall_clock_s(mut self, seconds: u64) -> Self {
357 self.limits.max_wall_clock_s = seconds;
358 self
359 }
360
361 pub fn tool_timeout(mut self, timeout: Duration) -> Self {
363 self.tool_timeout = timeout;
364 self
365 }
366
367 pub fn context_window(mut self, tokens: u64) -> Self {
369 self.context_window = tokens;
370 self
371 }
372
373 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
375 self.max_output_tokens = tokens;
376 self
377 }
378
379 pub fn guardrails(mut self, guardrails: GuardrailsConfig) -> Self {
382 self.guardrails = guardrails;
383 self
384 }
385
386 pub fn trace_dir(mut self, dir: impl Into<PathBuf>) -> Self {
389 self.trace_dir = Some(dir.into());
390 self
391 }
392
393 pub fn mcp_server(mut self, name: impl Into<String>, server: McpServer) -> Self {
398 self.mcp_servers.push((name.into(), server));
399 self
400 }
401
402 pub fn memory(mut self, memory: Memory) -> Self {
407 self.memory = Some(memory);
408 self
409 }
410
411 pub fn session(mut self, id: impl Into<String>) -> Self {
414 self.session = Some(id.into());
415 self
416 }
417
418 pub fn skills_dir(mut self, dir: impl Into<PathBuf>) -> Self {
425 self.skill_dirs.push(dir.into());
426 self
427 }
428
429 pub fn verify(mut self, command: impl Into<String>, max_attempts: u32) -> Self {
435 self.verify = Some((command.into(), max_attempts));
436 self
437 }
438
439 pub fn subagents(mut self, subagents: SubAgents) -> Self {
441 self.subagents = Some(subagents);
442 self
443 }
444
445 pub fn model(mut self, name: impl Into<String>, model: Model) -> Self {
449 self.models.insert(name.into(), model);
450 self
451 }
452
453 pub fn triage(mut self, cheap: impl Into<String>, frontier: impl Into<String>) -> Self {
459 self.triage = Some((cheap.into(), frontier.into()));
460 self
461 }
462
463 pub fn otel(mut self, otel: Otel) -> Self {
469 self.otel = Some(otel);
470 self
471 }
472
473 pub fn on_limit(
480 mut self,
481 decide: impl Fn(&LimitHit) -> Option<u32> + Send + Sync + 'static,
482 ) -> Self {
483 self.on_limit = Some(Box::new(decide));
484 self
485 }
486
487 pub fn on_secret_request(
495 mut self,
496 answer: impl Fn(&SecretRequest) -> Option<String> + Send + Sync + 'static,
497 ) -> Self {
498 self.on_secret = Some(Box::new(answer));
499 self
500 }
501
502 #[cfg(feature = "agent86ui")]
510 pub fn ui(mut self, ui: Ui) -> Self {
511 self.ui = Some(ui);
512 self
513 }
514
515 pub fn secret(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
522 self.secrets.push((name.into(), value.into()));
523 self
524 }
525
526 pub fn build(self) -> Result<Agent, BuildError> {
530 let router = self.router()?;
531 let provider = self.provider.ok_or(BuildError::MissingProvider)?;
532 let workspace = self.workspace.ok_or(BuildError::MissingWorkspace)?;
533 let mut context = ToolContext::new(&workspace).map_err(|error| BuildError::Workspace {
534 path: workspace.display().to_string(),
535 detail: error.to_string(),
536 })?;
537 context.policy.timeout = self.tool_timeout;
538 context.executor = Executor::Subprocess;
539 for (name, value) in &self.secrets {
540 let refused = |reason: &str| BuildError::Secret {
541 name: name.clone(),
542 reason: reason.to_owned(),
543 };
544 if !crate::vault::valid_name(name) {
545 return Err(refused("not a valid environment variable name"));
546 }
547 let answer = crate::vault::SecretAnswer {
548 value: value.clone(),
549 remember: false,
550 };
551 context.secrets.accept(name, answer).map_err(|_| {
552 refused(&format!(
553 "shorter than {} characters",
554 crate::vault::MIN_SECRET_CHARS
555 ))
556 })?;
557 }
558
559 let registry = registry_for(self.builtins);
560 let runs_commands = ["run_command", "python_exec"]
562 .iter()
563 .any(|name| registry.get(name).is_some());
564 for tool in self.tools {
565 registry.register(tool).map_err(BuildError::Tool)?;
566 }
567
568 let store = self.memory.as_ref().map(|memory| memory.store.clone());
569 let state = match (&self.session, &store) {
570 (None, _) => AgentState::new(),
571 (Some(_), None) => return Err(BuildError::SessionWithoutMemory),
572 (Some(id), Some(store)) => store
573 .load(id)
574 .map_err(|error| BuildError::Memory(error.0))?
575 .ok_or_else(|| BuildError::SessionNotFound(id.clone()))?,
576 };
577 if let Some(memory) = &self.memory {
578 let (episodes, sessions, days) = memory.retention;
579 store
580 .as_ref()
581 .expect("memory gives a store")
582 .enforce_retention(episodes, sessions, days)
583 .map_err(|error| BuildError::Memory(error.0))?;
584 for tool in [
585 Box::new(crate::tools::memory::RememberTool) as Box<dyn Tool>,
586 Box::new(crate::tools::memory::RecallTool),
587 ] {
588 registry.register(tool).map_err(BuildError::Tool)?;
589 }
590 }
591 context.memory = store.clone();
592
593 let skills = Arc::new(crate::skills::discover_in(&self.skill_dirs));
596 if !skills.is_empty() {
597 context.policy.allow(
598 self.skill_dirs
599 .iter()
600 .filter(|dir| dir.is_dir())
601 .filter_map(|dir| std::fs::canonicalize(dir).ok())
602 .collect::<Vec<_>>(),
603 );
604 registry
605 .register(Box::new(crate::tools::skills::UseSkillTool))
606 .map_err(BuildError::Tool)?;
607 }
608 context.skills = Arc::clone(&skills);
609
610 let config = builtin_config();
612 let mut agents = crate::config::AgentsConfig {
613 enabled: false,
614 ..config.agents.clone()
615 };
616 let mut notices = Vec::new();
617 if let Some(subagents) = &self.subagents {
618 agents = crate::config::AgentsConfig {
619 enabled: true,
620 max_depth: subagents.max_depth,
621 max_steps: subagents.max_steps.min(self.limits.max_steps.max(1)),
622 max_parallel: subagents
623 .max_parallel
624 .clamp(1, crate::config::MAX_PARALLEL_CEILING),
625 };
626 let mut specialties = if subagents.built_ins {
627 Specialties::built_in()
628 } else {
629 Specialties::default()
630 };
631 for dir in &subagents.dirs {
632 specialties.add_user_dir(dir);
633 }
634 notices.extend(specialties.notices.iter().cloned());
635 context.specialties = Arc::new(specialties);
636 registry
637 .register(Box::new(crate::tools::delegate::DelegateTool))
638 .map_err(BuildError::Tool)?;
639 }
640
641 let tracer = self
642 .otel
643 .as_ref()
644 .map(|otel| crate::otel::Tracer::to(otel.destination.clone()))
645 .unwrap_or_default();
646
647 if let Some(answer) = self.on_secret {
648 context
649 .secrets
650 .set_prompt(Some(Box::new(move |request: &SecretRequest| {
651 answer(request).map(|value| crate::vault::SecretAnswer {
652 value,
653 remember: false,
654 })
655 })));
656 registry
657 .register(Box::new(crate::tools::secret::RequestSecretTool))
658 .map_err(BuildError::Tool)?;
659 }
660 #[cfg(feature = "agent86ui")]
661 let mut ui_session = None;
662 #[cfg(feature = "agent86ui")]
663 if let Some(ui) = self.ui {
664 if ui.catalogs.is_empty() {
665 return Err(BuildError::Ui(
666 "a renderer needs at least one catalog".into(),
667 ));
668 }
669 ui_session = Some(
670 crate::agent86ui::UiSession::new(ui.catalogs)
671 .map_err(|error| BuildError::Ui(error.to_string()))?
672 .with_egress(self.guardrails.egress)
673 .with_remote_media(ui.remote_media)
674 .with_waiter(ui.on_wait),
675 );
676 }
677 let mut session_limits = crate::limits::SessionLimits::default();
678 session_limits.prompt = self.on_limit;
679
680 let mcp = start_mcp(&self.mcp_servers, ®istry)?;
681
682 let recorder = match &self.trace_dir {
683 None => Recorder::disabled(),
684 Some(dir) => {
685 std::fs::create_dir_all(dir)
686 .map_err(|error| BuildError::Trace(error.to_string()))?;
687 let defaults = builtin_config().observability;
688 Recorder::from_config(&ObservabilityConfig {
689 trace: true,
690 path: dir.display().to_string(),
691 otel: false,
692 ..defaults
693 })
694 }
695 }
696 .with_secrets(context.secrets.clone());
697
698 let mut limits = self.limits;
699 limits.max_output_tokens = self.max_output_tokens;
700 let mut system = self.system.unwrap_or_else(|| default_system(runs_commands));
701 system.push_str(&crate::prompt::skills_section(
702 skills.values().map(AsRef::as_ref),
703 ));
704 let mut harness = Harness {
705 provider,
706 router,
707 tracer,
708 registry,
709 context,
710 limits,
711 agents,
712 system: Message {
713 role: Role::System,
714 content: system,
715 tool_calls: Vec::new(),
716 tool_call_id: None,
717 name: None,
718 },
719 max_tokens: self.max_output_tokens,
720 session_limits,
721 context_window: self.context_window,
722 gate: ApprovalGate::new(self.approval, self.approver),
723 guardrails: Guardrails::new(&self.guardrails),
724 recorder,
725 mcp,
726 memory: store,
727 cancel: Default::default(),
728 subagents: Default::default(),
729 calibration: Default::default(),
730 verify: match &self.verify {
731 Some((command, attempts)) => crate::verify::Verify::new(Some(command), *attempts),
732 None => Default::default(),
733 },
734 };
735 #[cfg(feature = "agent86ui")]
736 if let Some(session) = ui_session {
737 harness.attach_ui(session).map_err(BuildError::Tool)?;
738 harness
740 .offer_questions_as_forms()
741 .map_err(BuildError::Tool)?;
742 }
743 harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
744 harness.gate.queue.watch(harness.cancel.clone());
745 harness
746 .context
747 .secrets
748 .set_queue(harness.gate.queue.clone());
749 let agent = Agent {
750 harness,
751 conversation: Conversation(state),
752 notices,
753 };
754 #[cfg(feature = "agent86ui")]
756 agent.replay_surfaces();
757 Ok(agent)
758 }
759
760 fn router(&self) -> Result<Router, BuildError> {
763 if self.models.is_empty() {
764 return match &self.triage {
765 Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
766 None => Ok(Router::default()),
767 };
768 }
769 let (triage, cheap, frontier) = match &self.triage {
770 Some((cheap, frontier)) => {
771 for name in [cheap, frontier] {
772 if !self.models.contains_key(name) {
773 return Err(BuildError::UnknownModel(name.clone()));
774 }
775 }
776 (true, cheap.as_str(), frontier.as_str())
777 }
778 None => (false, "", ""),
779 };
780 let window = self.context_window;
781 let output = self.max_output_tokens;
782 let models: HashMap<String, RoutedModel> = self
783 .models
784 .iter()
785 .map(|(name, model)| {
786 (
787 name.clone(),
788 RoutedModel {
789 reference: name.clone(),
790 provider: Arc::clone(&model.provider),
791 max_tokens: model.max_output_tokens.unwrap_or(output),
792 context_window: model.context_window.unwrap_or(window),
793 output_setting: "max_output_tokens".to_owned(),
794 },
795 )
796 })
797 .collect();
798 Ok(Router::new(
799 triage,
800 cheap,
801 frontier,
802 Box::new(move |name| {
803 models
804 .get(name)
805 .cloned()
806 .ok_or_else(|| format!("no model named '{name}'"))
807 }),
808 ))
809 }
810}
811
812#[derive(Debug, Clone)]
822pub struct SubAgents {
823 max_depth: u32,
824 max_steps: u32,
825 max_parallel: u32,
826 built_ins: bool,
827 dirs: Vec<PathBuf>,
828}
829
830impl Default for SubAgents {
831 fn default() -> Self {
832 let agents = builtin_config().agents;
833 Self {
834 max_depth: agents.max_depth,
835 max_steps: agents.max_steps,
836 max_parallel: agents.max_parallel,
837 built_ins: true,
838 dirs: Vec::new(),
839 }
840 }
841}
842
843impl SubAgents {
844 pub fn new() -> Self {
847 Self::default()
848 }
849
850 pub fn max_depth(mut self, depth: u32) -> Self {
852 self.max_depth = depth;
853 self
854 }
855
856 pub fn max_steps(mut self, steps: u32) -> Self {
858 self.max_steps = steps;
859 self
860 }
861
862 pub fn max_parallel(mut self, parallel: u32) -> Self {
864 self.max_parallel = parallel;
865 self
866 }
867
868 pub fn without_built_ins(mut self) -> Self {
870 self.built_ins = false;
871 self
872 }
873
874 pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
880 self.dirs.push(dir.into());
881 self
882 }
883}
884
885#[derive(Clone)]
887pub struct Model {
888 provider: Arc<dyn Provider>,
889 context_window: Option<u64>,
890 max_output_tokens: Option<u32>,
891}
892
893impl std::fmt::Debug for Model {
894 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
895 f.debug_struct("Model")
896 .field("provider", &self.provider.name())
897 .field("model", &self.provider.model())
898 .field("context_window", &self.context_window)
899 .field("max_output_tokens", &self.max_output_tokens)
900 .finish()
901 }
902}
903
904impl Model {
905 pub fn new(provider: Arc<dyn Provider>) -> Self {
907 Self {
908 provider,
909 context_window: None,
910 max_output_tokens: None,
911 }
912 }
913
914 pub fn context_window(mut self, tokens: u64) -> Self {
916 self.context_window = Some(tokens);
917 self
918 }
919
920 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
922 self.max_output_tokens = Some(tokens);
923 self
924 }
925}
926
927#[cfg(feature = "agent86ui")]
930#[derive(Clone)]
931pub struct Ui {
932 catalogs: Vec<Catalog>,
933 remote_media: bool,
934 on_wait: Option<crate::agent86ui::UiWaiter>,
935}
936
937#[cfg(feature = "agent86ui")]
938impl std::fmt::Debug for Ui {
939 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
940 f.debug_struct("Ui")
941 .field(
942 "catalogs",
943 &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
944 )
945 .field("remote_media", &self.remote_media)
946 .field("on_wait", &self.on_wait.is_some())
947 .finish()
948 }
949}
950
951#[cfg(feature = "agent86ui")]
952impl Ui {
953 pub fn basic() -> Self {
956 Self::new([Catalog::basic().clone()])
957 }
958
959 pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
962 Self {
963 catalogs: catalogs.into_iter().collect(),
964 remote_media: false,
965 on_wait: None,
966 }
967 }
968
969 pub fn on_wait(
978 mut self,
979 answer: impl Fn(&UiWait) -> Option<Action> + Send + Sync + 'static,
980 ) -> Self {
981 self.on_wait = Some(std::sync::Arc::new(answer));
982 self
983 }
984
985 pub fn allow_remote_media(mut self) -> Self {
990 self.remote_media = true;
991 self
992 }
993
994 pub fn catalogs(&self) -> &[Catalog] {
996 &self.catalogs
997 }
998}
999
1000#[derive(Debug, Clone)]
1002pub struct Otel {
1003 destination: crate::otel::Destination,
1004}
1005
1006impl Otel {
1007 pub fn otlp(traces_url: impl Into<String>) -> Self {
1010 Self {
1011 destination: crate::otel::Destination::Otlp {
1012 url: traces_url.into(),
1013 headers: Vec::new(),
1014 timeout: Duration::from_secs(10),
1015 },
1016 }
1017 }
1018
1019 pub fn console() -> Self {
1021 Self {
1022 destination: crate::otel::Destination::Console,
1023 }
1024 }
1025
1026 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1028 if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
1029 headers.push((name.into(), value.into()));
1030 }
1031 self
1032 }
1033
1034 pub fn timeout(mut self, timeout: Duration) -> Self {
1036 if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
1037 *limit = timeout;
1038 }
1039 self
1040 }
1041}
1042
1043fn start_mcp(
1046 servers: &[(String, McpServer)],
1047 registry: &ToolRegistry,
1048) -> Result<Option<Arc<McpManager>>, BuildError> {
1049 if servers.is_empty() {
1050 return Ok(None);
1051 }
1052 let manager = Arc::new(McpManager::empty(&builtin_config()));
1053 manager.attach(registry);
1054 let mut seen: Vec<&str> = Vec::new();
1055 for (name, server) in servers {
1056 let failed = |reason: String| BuildError::Mcp {
1057 name: name.clone(),
1058 reason,
1059 };
1060 if seen.contains(&name.as_str()) {
1061 return Err(failed("another server was given the same name".to_owned()));
1062 }
1063 seen.push(name);
1064 let mut config = server.config.clone();
1065 config.resolve_transport().map_err(failed)?;
1066 manager
1067 .start_server(
1068 name,
1069 &config,
1070 &server.literal_refs(),
1071 &NoSecretStore,
1072 config.connect_timeout_s,
1073 )
1074 .map_err(failed)?;
1075 let (_, collisions) = manager.mount(name);
1076 if !collisions.is_empty() {
1077 return Err(BuildError::Tool(format!(
1078 "MCP server '{name}' offers tools already taken: {}",
1079 collisions.join(", ")
1080 )));
1081 }
1082 }
1083 Ok(Some(manager))
1084}
1085
1086#[derive(Debug, Clone)]
1091pub struct McpServer {
1092 config: McpServerConfig,
1093}
1094
1095impl McpServer {
1096 fn from(value: Value) -> Self {
1097 Self {
1098 config: serde_json::from_value(value).expect("a server config always deserializes"),
1099 }
1100 }
1101
1102 pub fn stdio<S: Into<String>>(
1106 command: impl Into<String>,
1107 args: impl IntoIterator<Item = S>,
1108 ) -> Self {
1109 let args: Vec<String> = args.into_iter().map(Into::into).collect();
1110 Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
1111 }
1112
1113 pub fn http(url: impl Into<String>) -> Self {
1115 Self::from(json!({"url": url.into(), "transport": "http"}))
1116 }
1117
1118 pub fn sse(url: impl Into<String>) -> Self {
1120 Self::from(json!({"url": url.into(), "transport": "sse"}))
1121 }
1122
1123 pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1125 self.config.env.insert(name.into(), value.into());
1126 self
1127 }
1128
1129 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1131 self.config.headers.insert(name.into(), value.into());
1132 self
1133 }
1134
1135 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
1137 self.config.connect_timeout_s = timeout.as_secs_f64();
1138 self
1139 }
1140
1141 pub fn call_timeout(mut self, timeout: Duration) -> Self {
1143 self.config.call_timeout_s = timeout.as_secs_f64();
1144 self
1145 }
1146
1147 pub fn max_result_chars(mut self, chars: usize) -> Self {
1149 self.config.max_result_chars = chars;
1150 self
1151 }
1152
1153 fn literal_refs(&self) -> HashMap<String, String> {
1156 let config = &self.config;
1157 config
1158 .args
1159 .iter()
1160 .chain(config.env.values())
1161 .chain(config.url.iter())
1162 .chain(config.headers.values())
1163 .flat_map(|text| var_ref_names(text))
1164 .map(|name| (name.clone(), format!("${{{name}}}")))
1165 .collect()
1166 }
1167}
1168
1169#[derive(Clone)]
1173pub struct Memory {
1174 store: SessionStore,
1175 retention: (i64, i64, f64),
1176}
1177
1178impl std::fmt::Debug for Memory {
1179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1180 f.debug_struct("Memory")
1181 .field("retention", &self.retention)
1182 .finish_non_exhaustive()
1183 }
1184}
1185
1186impl Memory {
1187 pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1190 Self::wrap(SessionStore::open(path.as_ref()))
1191 }
1192
1193 pub fn open_with(
1197 path: impl AsRef<Path>,
1198 embedder: Arc<dyn Embedder>,
1199 ) -> Result<Self, BuildError> {
1200 Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
1201 }
1202
1203 pub fn in_memory() -> Result<Self, BuildError> {
1205 Self::open(":memory:")
1206 }
1207
1208 fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
1209 let memory = builtin_config().memory;
1210 Ok(Self {
1211 store: store.map_err(|error| BuildError::Memory(error.0))?,
1212 retention: (
1213 memory.retention_max_episodes,
1214 memory.retention_max_sessions,
1215 memory.retention_max_age_days,
1216 ),
1217 })
1218 }
1219
1220 pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
1224 self.retention = (episodes, sessions, max_age_days);
1225 self
1226 }
1227
1228 pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
1230 Ok(self
1231 .store
1232 .recent_sessions(limit)
1233 .map_err(|error| BuildError::Memory(error.0))?
1234 .into_iter()
1235 .map(|session| (session.session_id, session.title))
1236 .collect())
1237 }
1238
1239 pub fn store(&self) -> &SessionStore {
1242 &self.store
1243 }
1244}
1245
1246fn registry_for(builtins: Builtins) -> ToolRegistry {
1247 let registry = ToolRegistry::new();
1248 let mut tools: Vec<Box<dyn Tool>> = Vec::new();
1249 if builtins != Builtins::None {
1250 tools.push(Box::new(files::ReadFileTool));
1251 tools.push(Box::new(files::ListDirTool));
1252 tools.push(Box::new(search::SearchFilesTool));
1253 tools.push(Box::new(search::FindFilesTool));
1254 }
1255 if matches!(builtins, Builtins::Files | Builtins::All) {
1256 tools.push(Box::new(files::WriteFileTool));
1257 tools.push(Box::new(files::EditFileTool));
1258 }
1259 if builtins == Builtins::All {
1260 tools.push(Box::new(exec::RunCommandTool));
1261 tools.push(Box::new(exec::PythonExecTool));
1262 tools.push(Box::new(web::WebFetchTool));
1263 }
1264 for tool in tools {
1265 registry
1266 .register(tool)
1267 .expect("built-in tool names are unique");
1268 }
1269 registry
1270}
1271
1272#[derive(Debug, Clone, PartialEq)]
1278#[non_exhaustive]
1279pub struct RunResult {
1280 pub answer: String,
1283 pub output: String,
1286 pub turn: Option<TurnSummary>,
1288 pub usage: Usage,
1290 pub verification: Option<Verification>,
1293}
1294
1295#[derive(Debug, Clone, PartialEq, Eq)]
1298pub enum Turn {
1299 Goal(String),
1301 Skill { name: String, task: String },
1304 Specialist {
1308 name: String,
1309 task: String,
1310 with_context: bool,
1311 },
1312}
1313
1314impl Turn {
1315 pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
1316 Self::Skill {
1317 name: name.into(),
1318 task: task.into(),
1319 }
1320 }
1321
1322 pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
1323 Self::Specialist {
1324 name: name.into(),
1325 task: task.into(),
1326 with_context: false,
1327 }
1328 }
1329
1330 pub fn with_context(mut self) -> Self {
1332 if let Self::Specialist { with_context, .. } = &mut self {
1333 *with_context = true;
1334 }
1335 self
1336 }
1337}
1338
1339impl From<&str> for Turn {
1340 fn from(goal: &str) -> Self {
1341 Self::Goal(goal.to_owned())
1342 }
1343}
1344
1345impl From<String> for Turn {
1346 fn from(goal: String) -> Self {
1347 Self::Goal(goal)
1348 }
1349}
1350
1351impl From<&String> for Turn {
1352 fn from(goal: &String) -> Self {
1353 Self::Goal(goal.clone())
1354 }
1355}
1356
1357pub struct Agent {
1360 harness: Harness,
1361 conversation: Conversation,
1362 notices: Vec<String>,
1364}
1365
1366impl Agent {
1367 pub fn builder() -> AgentBuilder {
1368 AgentBuilder::default()
1369 }
1370
1371 pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1373 self.run_with_events(turn, |_| {}).await
1374 }
1375
1376 pub async fn run_with_events(
1379 &mut self,
1380 turn: impl Into<Turn>,
1381 on_event: impl FnMut(TurnEvent<'_>),
1382 ) -> Result<RunResult, RunError> {
1383 let (kind, prompt, display) = match turn.into() {
1384 Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
1385 Turn::Skill { name, task } => {
1386 let skill = self
1387 .harness
1388 .context
1389 .skills
1390 .get(&name)
1391 .cloned()
1392 .ok_or(RunError::UnknownSkill(name.clone()))?;
1393 let display = format!("/{name} {task}").trim_end().to_owned();
1394 (TurnKind::Skill(skill), task, display)
1395 }
1396 Turn::Specialist {
1397 name,
1398 task,
1399 with_context,
1400 } => {
1401 if !self.harness.agents.enabled
1402 || self.harness.context.specialties.get(&name).is_none()
1403 {
1404 return Err(RunError::UnknownSpecialist(name));
1405 }
1406 let display = format!("/agent {name} {task}");
1407 (TurnKind::Agent { name, with_context }, task, display)
1408 }
1409 };
1410 self.run_kind(kind, &prompt, &display, on_event).await
1411 }
1412
1413 pub fn can_continue(&self) -> bool {
1419 self.harness.continuable(&self.conversation.0).is_ok()
1420 }
1421
1422 pub async fn continue_turn(&mut self) -> Result<RunResult, RunError> {
1431 self.continue_turn_with_events(|_| {}).await
1432 }
1433
1434 pub async fn continue_turn_with_events(
1436 &mut self,
1437 on_event: impl FnMut(TurnEvent<'_>),
1438 ) -> Result<RunResult, RunError> {
1439 let continuation = self
1440 .harness
1441 .continuable(&self.conversation.0)
1442 .map_err(|refusal| RunError::NotContinuable(refusal.0))?;
1443 self.run_kind(TurnKind::Continue(Box::new(continuation)), "", "", on_event)
1444 .await
1445 }
1446
1447 async fn run_kind(
1449 &mut self,
1450 kind: TurnKind,
1451 prompt: &str,
1452 display: &str,
1453 mut on_event: impl FnMut(TurnEvent<'_>),
1454 ) -> Result<RunResult, RunError> {
1455 let output = self
1456 .harness
1457 .run_kind(
1458 &mut self.conversation.0,
1459 &kind,
1460 prompt,
1461 display,
1462 &mut on_event,
1463 )
1464 .await;
1465 if let Some(store) = &self.harness.memory {
1468 let _ = store.persist(&self.conversation.0);
1469 }
1470 let output = output?;
1471 Ok(RunResult {
1472 answer: final_answer(&self.conversation.0.messages).to_owned(),
1473 output,
1474 turn: self.conversation.0.last_turn.clone(),
1475 usage: self.conversation.0.usage,
1476 verification: self.harness.verify.last(),
1477 })
1478 }
1479
1480 #[cfg(feature = "agent86ui")]
1489 pub async fn ui_action(&mut self, action: Action) -> Result<RunResult, RunError> {
1490 self.ui_action_with_events(action, |_| {}).await
1491 }
1492
1493 #[cfg(feature = "agent86ui")]
1495 pub async fn ui_action_with_events(
1496 &mut self,
1497 action: Action,
1498 on_event: impl FnMut(TurnEvent<'_>),
1499 ) -> Result<RunResult, RunError> {
1500 let text = self
1501 .harness
1502 .accept_ui_action(&self.conversation.0.session_id, &action)
1503 .map_err(RunError::UiAction)?;
1504 self.run_with_events(Turn::Goal(text), on_event).await
1505 }
1506
1507 pub fn cancel_handle(&self) -> CancelToken {
1510 self.harness.cancel.clone()
1511 }
1512
1513 pub fn conversation(&self) -> &Conversation {
1515 &self.conversation
1516 }
1517
1518 pub fn with_conversation(mut self, conversation: Conversation) -> Self {
1522 self.conversation = conversation;
1523 #[cfg(feature = "agent86ui")]
1524 self.replay_surfaces();
1525 self
1526 }
1527
1528 #[cfg(feature = "agent86ui")]
1530 fn replay_surfaces(&self) {
1531 if let Some(ui) = &self.harness.context.ui {
1532 ui.replay(&self.conversation.0, &self.harness.context);
1533 }
1534 }
1535
1536 #[cfg(feature = "agent86ui")]
1544 pub fn surfaces(&self) -> Vec<AgentMessage> {
1545 self.harness
1546 .context
1547 .ui
1548 .as_ref()
1549 .map(|ui| ui.snapshot())
1550 .unwrap_or_default()
1551 }
1552
1553 pub fn session_id(&self) -> &str {
1555 self.conversation.id()
1556 }
1557
1558 pub fn secret_names(&self) -> Vec<String> {
1560 self.harness.context.secrets.names()
1561 }
1562
1563 pub fn notes(&self) -> Vec<String> {
1567 let mut notes = self.notices.clone();
1568 if let Some(mcp) = &self.harness.mcp {
1569 notes.extend(mcp.notes());
1570 }
1571 notes.extend(self.harness.tracer.note());
1572 notes
1573 }
1574
1575 pub fn skills(&self) -> Vec<String> {
1577 self.harness.context.skills.keys().cloned().collect()
1578 }
1579
1580 pub fn specialists(&self) -> Vec<String> {
1582 if !self.harness.agents.enabled {
1583 return Vec::new();
1584 }
1585 self.harness
1586 .context
1587 .specialties
1588 .names()
1589 .into_iter()
1590 .map(str::to_owned)
1591 .collect()
1592 }
1593
1594 pub fn tool_names(&self) -> Vec<String> {
1596 self.harness.registry.names()
1597 }
1598
1599 pub fn harness(&self) -> &Harness {
1602 &self.harness
1603 }
1604}
1605
1606#[derive(Debug, Clone, Default, PartialEq)]
1611pub struct Conversation(AgentState);
1612
1613#[derive(Debug, Clone, PartialEq)]
1615pub struct ConversationMessage {
1616 pub role: Role,
1617 pub text: String,
1619 pub tool_calls: Vec<ToolCall>,
1621 pub answers: Option<String>,
1623}
1624
1625impl Conversation {
1626 pub fn new() -> Self {
1628 Self::default()
1629 }
1630
1631 pub fn id(&self) -> &str {
1633 &self.0.session_id
1634 }
1635
1636 pub fn messages(&self) -> Vec<ConversationMessage> {
1640 self.0
1641 .messages
1642 .iter()
1643 .map(|message| ConversationMessage {
1644 role: message.role,
1645 text: match message.role {
1646 Role::User => crate::prompt::without_turn_note(&message.content).to_owned(),
1647 _ => message.content.clone(),
1648 },
1649 tool_calls: message.tool_calls.clone(),
1650 answers: message.tool_call_id.clone(),
1651 })
1652 .collect()
1653 }
1654
1655 pub fn steps(&self) -> usize {
1657 self.0.step_count()
1658 }
1659
1660 pub fn usage(&self) -> Usage {
1662 self.0.usage
1663 }
1664
1665 pub fn last_turn(&self) -> Option<&TurnSummary> {
1667 self.0.last_turn.as_ref()
1668 }
1669
1670 pub fn to_json(&self) -> String {
1672 serde_json::to_string(&self.0).expect("a conversation always serializes")
1673 }
1674
1675 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1678 serde_json::from_str(json).map(Self)
1679 }
1680}
1681
1682type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1686
1687pub struct FnTool {
1690 name: String,
1691 description: String,
1692 parameters: Value,
1693 side_effecting: bool,
1694 run: Box<ToolFn>,
1695}
1696
1697impl FnTool {
1698 pub fn new(
1701 name: impl Into<String>,
1702 description: impl Into<String>,
1703 parameters: Value,
1704 run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
1705 + Send
1706 + Sync
1707 + 'static,
1708 ) -> Self {
1709 Self {
1710 name: name.into(),
1711 description: description.into(),
1712 parameters,
1713 side_effecting: false,
1714 run: Box::new(run),
1715 }
1716 }
1717
1718 pub fn side_effecting(mut self) -> Self {
1721 self.side_effecting = true;
1722 self
1723 }
1724}
1725
1726impl Tool for FnTool {
1727 fn name(&self) -> &str {
1728 &self.name
1729 }
1730
1731 fn description(&self) -> &str {
1732 &self.description
1733 }
1734
1735 fn side_effecting(&self) -> bool {
1736 self.side_effecting
1737 }
1738
1739 fn parameters(&self) -> Value {
1740 self.parameters.clone()
1741 }
1742
1743 fn execute(
1744 &self,
1745 args: &Map<String, Value>,
1746 ctx: &ToolContext,
1747 ) -> Result<ToolResult, ToolError> {
1748 match (self.run)(args, ctx) {
1749 Ok(content) => Ok(ToolResult {
1750 call_id: String::new(),
1751 name: self.name.clone(),
1752 ok: true,
1753 content,
1754 error: None,
1755 metadata: Map::new(),
1756 }),
1757 Err(message) => Err(ToolError::Raised {
1758 exception: "ToolError".to_owned(),
1759 message,
1760 }),
1761 }
1762 }
1763}
1764
1765pub mod providers {
1770 pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
1771 pub use crate::provider::google::{GoogleConfig, GoogleProvider};
1772 pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
1773 pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
1774 pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
1775 pub use crate::types::{
1776 Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
1777 };
1778}