use crate::agent::Harness;
use crate::agents_def::Specialties;
use crate::approval::ApprovalGate;
use crate::config::{builtin_config, LimitsConfig, McpServerConfig, ObservabilityConfig};
use crate::guardrails::Guardrails;
use crate::mcp::{var_ref_names, McpManager};
use crate::observability::Recorder;
use crate::router::{RoutedModel, Router};
use crate::secrets::NoSecretStore;
use crate::session::{AgentState, SessionStore};
use crate::specialty_turn::TurnKind;
use crate::tools::sandbox::Executor;
use crate::tools::{exec, files, search, web, ToolRegistry};
use crate::turn::final_answer;
use crate::types::Message;
use indexmap::IndexMap;
use serde_json::{json, Map, Value};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
pub use crate::agent::{CancelToken, HarnessError, TurnEvent};
#[cfg(feature = "agent86ui")]
pub use crate::agent86ui::UiWait;
pub use crate::approval::ApprovalPreview;
pub use crate::config::{EgressMode, GuardrailsConfig, IngressMode};
pub use crate::limits::{LimitHit, LimitKind};
pub use crate::memory::embeddings::Embedder;
pub use crate::tools::{Tool, ToolContext, ToolError};
pub use crate::turn::TurnSummary;
pub use crate::types::{ApprovalMode, Role, ToolCall, ToolResult, ToolSpec, Usage};
pub use crate::vault::SecretRequest;
#[cfg(feature = "agent86ui")]
pub use agent86_ui;
#[cfg(feature = "agent86ui")]
pub use agent86_ui::{Action, AgentMessage, AgentMessageKind, Catalog};
pub use providers::Provider;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Builtins {
#[default]
None,
ReadOnly,
Files,
All,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum BuildError {
#[error("no provider was given; call AgentBuilder::provider")]
MissingProvider,
#[error("no workspace was given; call AgentBuilder::workspace")]
MissingWorkspace,
#[error("could not open the workspace {path}: {detail}")]
Workspace { path: String, detail: String },
#[error("could not register a tool: {0}")]
Tool(String),
#[error("could not open the trace directory: {0}")]
Trace(String),
#[error("MCP server '{name}' failed to start: {reason}")]
Mcp { name: String, reason: String },
#[error("a session to resume needs memory; call AgentBuilder::memory")]
SessionWithoutMemory,
#[error("no session '{0}' in memory")]
SessionNotFound(String),
#[error("memory could not be read: {0}")]
Memory(String),
#[error("no model named '{0}'; add it with AgentBuilder::model")]
UnknownModel(String),
#[error("the secret {name} was refused: {reason}")]
Secret { name: String, reason: String },
#[cfg(feature = "agent86ui")]
#[error("agent86UI could not be set up: {0}")]
Ui(String),
}
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum RunError {
#[error(transparent)]
Harness(#[from] HarnessError),
#[error("no skill named '{0}'")]
UnknownSkill(String),
#[error("no specialist named '{0}'")]
UnknownSpecialist(String),
#[cfg(feature = "agent86ui")]
#[error("the UI action was refused: {0}")]
UiAction(String),
}
type Approver = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
type SecretAsker = Box<dyn Fn(&SecretRequest) -> Option<String> + Send + Sync>;
pub struct AgentBuilder {
provider: Option<Arc<dyn Provider>>,
workspace: Option<PathBuf>,
system: Option<String>,
builtins: Builtins,
tools: Vec<Box<dyn Tool>>,
approval: ApprovalMode,
approver: Option<Approver>,
limits: LimitsConfig,
guardrails: GuardrailsConfig,
context_window: u64,
max_output_tokens: u32,
trace_dir: Option<PathBuf>,
tool_timeout: Duration,
mcp_servers: Vec<(String, McpServer)>,
memory: Option<Memory>,
session: Option<String>,
skill_dirs: Vec<PathBuf>,
subagents: Option<SubAgents>,
models: IndexMap<String, Model>,
triage: Option<(String, String)>,
otel: Option<Otel>,
on_limit: Option<crate::limits::LimitPrompt>,
on_secret: Option<SecretAsker>,
#[cfg(feature = "agent86ui")]
ui: Option<Ui>,
secrets: Vec<(String, String)>,
}
impl Default for AgentBuilder {
fn default() -> Self {
let config = builtin_config();
Self {
provider: None,
workspace: None,
system: None,
builtins: Builtins::None,
tools: Vec::new(),
approval: ApprovalMode::Ask,
approver: None,
max_output_tokens: config.limits.max_output_tokens,
tool_timeout: Duration::from_secs(config.limits.tool_timeout_s),
limits: config.limits,
guardrails: config.guardrails,
context_window: DEFAULT_CONTEXT_WINDOW,
trace_dir: None,
mcp_servers: Vec::new(),
memory: None,
session: None,
skill_dirs: Vec::new(),
subagents: None,
models: IndexMap::new(),
triage: None,
otel: None,
on_limit: None,
on_secret: None,
#[cfg(feature = "agent86ui")]
ui: None,
secrets: Vec::new(),
}
}
}
pub const DEFAULT_CONTEXT_WINDOW: u64 = 128_000;
impl AgentBuilder {
pub fn provider(mut self, provider: Arc<dyn Provider>) -> Self {
self.provider = Some(provider);
self
}
pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
self.workspace = Some(path.into());
self
}
pub fn system_prompt(mut self, text: impl Into<String>) -> Self {
self.system = Some(text.into());
self
}
pub fn builtins(mut self, builtins: Builtins) -> Self {
self.builtins = builtins;
self
}
pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
self.tools.push(Box::new(tool));
self
}
pub fn approval(mut self, mode: ApprovalMode) -> Self {
self.approval = mode;
self
}
pub fn approver(
mut self,
approver: impl Fn(&str, &ApprovalPreview) -> bool + Send + Sync + 'static,
) -> Self {
self.approver = Some(Box::new(approver));
self
}
pub fn max_steps(mut self, steps: u32) -> Self {
self.limits.max_steps = steps;
self
}
pub fn max_cost_usd(mut self, usd: f64) -> Self {
self.limits.max_cost_usd = usd;
self
}
pub fn max_wall_clock_s(mut self, seconds: u64) -> Self {
self.limits.max_wall_clock_s = seconds;
self
}
pub fn tool_timeout(mut self, timeout: Duration) -> Self {
self.tool_timeout = timeout;
self
}
pub fn context_window(mut self, tokens: u64) -> Self {
self.context_window = tokens;
self
}
pub fn max_output_tokens(mut self, tokens: u32) -> Self {
self.max_output_tokens = tokens;
self
}
pub fn guardrails(mut self, guardrails: GuardrailsConfig) -> Self {
self.guardrails = guardrails;
self
}
pub fn trace_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.trace_dir = Some(dir.into());
self
}
pub fn mcp_server(mut self, name: impl Into<String>, server: McpServer) -> Self {
self.mcp_servers.push((name.into(), server));
self
}
pub fn memory(mut self, memory: Memory) -> Self {
self.memory = Some(memory);
self
}
pub fn session(mut self, id: impl Into<String>) -> Self {
self.session = Some(id.into());
self
}
pub fn skills_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.skill_dirs.push(dir.into());
self
}
pub fn subagents(mut self, subagents: SubAgents) -> Self {
self.subagents = Some(subagents);
self
}
pub fn model(mut self, name: impl Into<String>, model: Model) -> Self {
self.models.insert(name.into(), model);
self
}
pub fn triage(mut self, cheap: impl Into<String>, frontier: impl Into<String>) -> Self {
self.triage = Some((cheap.into(), frontier.into()));
self
}
pub fn otel(mut self, otel: Otel) -> Self {
self.otel = Some(otel);
self
}
pub fn on_limit(
mut self,
decide: impl Fn(&LimitHit) -> Option<u32> + Send + Sync + 'static,
) -> Self {
self.on_limit = Some(Box::new(decide));
self
}
pub fn on_secret_request(
mut self,
answer: impl Fn(&SecretRequest) -> Option<String> + Send + Sync + 'static,
) -> Self {
self.on_secret = Some(Box::new(answer));
self
}
#[cfg(feature = "agent86ui")]
pub fn ui(mut self, ui: Ui) -> Self {
self.ui = Some(ui);
self
}
pub fn secret(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.secrets.push((name.into(), value.into()));
self
}
pub fn build(self) -> Result<Agent, BuildError> {
let router = self.router()?;
let provider = self.provider.ok_or(BuildError::MissingProvider)?;
let workspace = self.workspace.ok_or(BuildError::MissingWorkspace)?;
let mut context = ToolContext::new(&workspace).map_err(|error| BuildError::Workspace {
path: workspace.display().to_string(),
detail: error.to_string(),
})?;
context.policy.timeout = self.tool_timeout;
context.executor = Executor::Subprocess;
for (name, value) in &self.secrets {
let refused = |reason: &str| BuildError::Secret {
name: name.clone(),
reason: reason.to_owned(),
};
if !crate::vault::valid_name(name) {
return Err(refused("not a valid environment variable name"));
}
let answer = crate::vault::SecretAnswer {
value: value.clone(),
remember: false,
};
context.secrets.accept(name, answer).map_err(|_| {
refused(&format!(
"shorter than {} characters",
crate::vault::MIN_SECRET_CHARS
))
})?;
}
let registry = registry_for(self.builtins);
for tool in self.tools {
registry.register(tool).map_err(BuildError::Tool)?;
}
let store = self.memory.as_ref().map(|memory| memory.store.clone());
let state = match (&self.session, &store) {
(None, _) => AgentState::new(),
(Some(_), None) => return Err(BuildError::SessionWithoutMemory),
(Some(id), Some(store)) => store
.load(id)
.map_err(|error| BuildError::Memory(error.0))?
.ok_or_else(|| BuildError::SessionNotFound(id.clone()))?,
};
if let Some(memory) = &self.memory {
let (episodes, sessions, days) = memory.retention;
store
.as_ref()
.expect("memory gives a store")
.enforce_retention(episodes, sessions, days)
.map_err(|error| BuildError::Memory(error.0))?;
for tool in [
Box::new(crate::tools::memory::RememberTool) as Box<dyn Tool>,
Box::new(crate::tools::memory::RecallTool),
] {
registry.register(tool).map_err(BuildError::Tool)?;
}
}
context.memory = store.clone();
let skills = Arc::new(crate::skills::discover_in(&self.skill_dirs));
if !skills.is_empty() {
context.policy.allow(
self.skill_dirs
.iter()
.filter(|dir| dir.is_dir())
.filter_map(|dir| std::fs::canonicalize(dir).ok())
.collect::<Vec<_>>(),
);
registry
.register(Box::new(crate::tools::skills::UseSkillTool))
.map_err(BuildError::Tool)?;
}
context.skills = Arc::clone(&skills);
let config = builtin_config();
let mut agents = crate::config::AgentsConfig {
enabled: false,
..config.agents.clone()
};
let mut notices = Vec::new();
if let Some(subagents) = &self.subagents {
agents = crate::config::AgentsConfig {
enabled: true,
max_depth: subagents.max_depth,
max_steps: subagents.max_steps.min(self.limits.max_steps.max(1)),
max_parallel: subagents
.max_parallel
.clamp(1, crate::config::MAX_PARALLEL_CEILING),
};
let mut specialties = if subagents.built_ins {
Specialties::built_in()
} else {
Specialties::default()
};
for dir in &subagents.dirs {
specialties.add_user_dir(dir);
}
notices.extend(specialties.notices.iter().cloned());
context.specialties = Arc::new(specialties);
registry
.register(Box::new(crate::tools::delegate::DelegateTool))
.map_err(BuildError::Tool)?;
}
let tracer = self
.otel
.as_ref()
.map(|otel| crate::otel::Tracer::to(otel.destination.clone()))
.unwrap_or_default();
if let Some(answer) = self.on_secret {
context
.secrets
.set_prompt(Some(Box::new(move |request: &SecretRequest| {
answer(request).map(|value| crate::vault::SecretAnswer {
value,
remember: false,
})
})));
registry
.register(Box::new(crate::tools::secret::RequestSecretTool))
.map_err(BuildError::Tool)?;
}
#[cfg(feature = "agent86ui")]
let mut ui_session = None;
#[cfg(feature = "agent86ui")]
if let Some(ui) = self.ui {
if ui.catalogs.is_empty() {
return Err(BuildError::Ui(
"a renderer needs at least one catalog".into(),
));
}
ui_session = Some(
crate::agent86ui::UiSession::new(ui.catalogs)
.map_err(|error| BuildError::Ui(error.to_string()))?
.with_egress(self.guardrails.egress)
.with_remote_media(ui.remote_media)
.with_waiter(ui.on_wait),
);
}
let mut session_limits = crate::limits::SessionLimits::default();
session_limits.prompt = self.on_limit;
let mcp = start_mcp(&self.mcp_servers, ®istry)?;
let recorder = match &self.trace_dir {
None => Recorder::disabled(),
Some(dir) => {
std::fs::create_dir_all(dir)
.map_err(|error| BuildError::Trace(error.to_string()))?;
let defaults = builtin_config().observability;
Recorder::from_config(&ObservabilityConfig {
trace: true,
path: dir.display().to_string(),
otel: false,
..defaults
})
}
}
.with_secrets(context.secrets.clone());
let mut limits = self.limits;
limits.max_output_tokens = self.max_output_tokens;
let mut system = self
.system
.unwrap_or_else(|| crate::prompt::BASE_IDENTITY.trim().to_owned());
system.push_str(&crate::prompt::skills_section(
skills.values().map(AsRef::as_ref),
));
let mut harness = Harness {
provider,
router,
tracer,
registry,
context,
limits,
agents,
system: Message {
role: Role::System,
content: system,
tool_calls: Vec::new(),
tool_call_id: None,
name: None,
},
max_tokens: self.max_output_tokens,
session_limits,
context_window: self.context_window,
gate: ApprovalGate::new(self.approval, self.approver),
guardrails: Guardrails::new(&self.guardrails),
recorder,
mcp,
memory: store,
cancel: Default::default(),
subagents: Default::default(),
};
#[cfg(feature = "agent86ui")]
if let Some(session) = ui_session {
harness.attach_ui(session).map_err(BuildError::Tool)?;
harness
.offer_questions_as_forms()
.map_err(BuildError::Tool)?;
}
harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
harness.gate.queue.watch(harness.cancel.clone());
harness
.context
.secrets
.set_queue(harness.gate.queue.clone());
let agent = Agent {
harness,
conversation: Conversation(state),
notices,
};
#[cfg(feature = "agent86ui")]
agent.replay_surfaces();
Ok(agent)
}
fn router(&self) -> Result<Router, BuildError> {
if self.models.is_empty() {
return match &self.triage {
Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
None => Ok(Router::default()),
};
}
let (triage, cheap, frontier) = match &self.triage {
Some((cheap, frontier)) => {
for name in [cheap, frontier] {
if !self.models.contains_key(name) {
return Err(BuildError::UnknownModel(name.clone()));
}
}
(true, cheap.as_str(), frontier.as_str())
}
None => (false, "", ""),
};
let window = self.context_window;
let output = self.max_output_tokens;
let models: HashMap<String, RoutedModel> = self
.models
.iter()
.map(|(name, model)| {
(
name.clone(),
RoutedModel {
reference: name.clone(),
provider: Arc::clone(&model.provider),
max_tokens: model.max_output_tokens.unwrap_or(output),
context_window: model.context_window.unwrap_or(window),
output_setting: "max_output_tokens".to_owned(),
},
)
})
.collect();
Ok(Router::new(
triage,
cheap,
frontier,
Box::new(move |name| {
models
.get(name)
.cloned()
.ok_or_else(|| format!("no model named '{name}'"))
}),
))
}
}
#[derive(Debug, Clone)]
pub struct SubAgents {
max_depth: u32,
max_steps: u32,
max_parallel: u32,
built_ins: bool,
dirs: Vec<PathBuf>,
}
impl Default for SubAgents {
fn default() -> Self {
let agents = builtin_config().agents;
Self {
max_depth: agents.max_depth,
max_steps: agents.max_steps,
max_parallel: agents.max_parallel,
built_ins: true,
dirs: Vec::new(),
}
}
}
impl SubAgents {
pub fn new() -> Self {
Self::default()
}
pub fn max_depth(mut self, depth: u32) -> Self {
self.max_depth = depth;
self
}
pub fn max_steps(mut self, steps: u32) -> Self {
self.max_steps = steps;
self
}
pub fn max_parallel(mut self, parallel: u32) -> Self {
self.max_parallel = parallel;
self
}
pub fn without_built_ins(mut self) -> Self {
self.built_ins = false;
self
}
pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.dirs.push(dir.into());
self
}
}
#[derive(Clone)]
pub struct Model {
provider: Arc<dyn Provider>,
context_window: Option<u64>,
max_output_tokens: Option<u32>,
}
impl std::fmt::Debug for Model {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Model")
.field("provider", &self.provider.name())
.field("model", &self.provider.model())
.field("context_window", &self.context_window)
.field("max_output_tokens", &self.max_output_tokens)
.finish()
}
}
impl Model {
pub fn new(provider: Arc<dyn Provider>) -> Self {
Self {
provider,
context_window: None,
max_output_tokens: None,
}
}
pub fn context_window(mut self, tokens: u64) -> Self {
self.context_window = Some(tokens);
self
}
pub fn max_output_tokens(mut self, tokens: u32) -> Self {
self.max_output_tokens = Some(tokens);
self
}
}
#[cfg(feature = "agent86ui")]
#[derive(Clone)]
pub struct Ui {
catalogs: Vec<Catalog>,
remote_media: bool,
on_wait: Option<crate::agent86ui::UiWaiter>,
}
#[cfg(feature = "agent86ui")]
impl std::fmt::Debug for Ui {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Ui")
.field(
"catalogs",
&self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
)
.field("remote_media", &self.remote_media)
.field("on_wait", &self.on_wait.is_some())
.finish()
}
}
#[cfg(feature = "agent86ui")]
impl Ui {
pub fn basic() -> Self {
Self::new([Catalog::basic().clone()])
}
pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
Self {
catalogs: catalogs.into_iter().collect(),
remote_media: false,
on_wait: None,
}
}
pub fn on_wait(
mut self,
answer: impl Fn(&UiWait) -> Option<Action> + Send + Sync + 'static,
) -> Self {
self.on_wait = Some(std::sync::Arc::new(answer));
self
}
pub fn allow_remote_media(mut self) -> Self {
self.remote_media = true;
self
}
pub fn catalogs(&self) -> &[Catalog] {
&self.catalogs
}
}
#[derive(Debug, Clone)]
pub struct Otel {
destination: crate::otel::Destination,
}
impl Otel {
pub fn otlp(traces_url: impl Into<String>) -> Self {
Self {
destination: crate::otel::Destination::Otlp {
url: traces_url.into(),
headers: Vec::new(),
timeout: Duration::from_secs(10),
},
}
}
pub fn console() -> Self {
Self {
destination: crate::otel::Destination::Console,
}
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
headers.push((name.into(), value.into()));
}
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
*limit = timeout;
}
self
}
}
fn start_mcp(
servers: &[(String, McpServer)],
registry: &ToolRegistry,
) -> Result<Option<Arc<McpManager>>, BuildError> {
if servers.is_empty() {
return Ok(None);
}
let manager = Arc::new(McpManager::empty(&builtin_config()));
manager.attach(registry);
let mut seen: Vec<&str> = Vec::new();
for (name, server) in servers {
let failed = |reason: String| BuildError::Mcp {
name: name.clone(),
reason,
};
if seen.contains(&name.as_str()) {
return Err(failed("another server was given the same name".to_owned()));
}
seen.push(name);
let mut config = server.config.clone();
config.resolve_transport().map_err(failed)?;
manager
.start_server(
name,
&config,
&server.literal_refs(),
&NoSecretStore,
config.connect_timeout_s,
)
.map_err(failed)?;
let (_, collisions) = manager.mount(name);
if !collisions.is_empty() {
return Err(BuildError::Tool(format!(
"MCP server '{name}' offers tools already taken: {}",
collisions.join(", ")
)));
}
}
Ok(Some(manager))
}
#[derive(Debug, Clone)]
pub struct McpServer {
config: McpServerConfig,
}
impl McpServer {
fn from(value: Value) -> Self {
Self {
config: serde_json::from_value(value).expect("a server config always deserializes"),
}
}
pub fn stdio<S: Into<String>>(
command: impl Into<String>,
args: impl IntoIterator<Item = S>,
) -> Self {
let args: Vec<String> = args.into_iter().map(Into::into).collect();
Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
}
pub fn http(url: impl Into<String>) -> Self {
Self::from(json!({"url": url.into(), "transport": "http"}))
}
pub fn sse(url: impl Into<String>) -> Self {
Self::from(json!({"url": url.into(), "transport": "sse"}))
}
pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.config.env.insert(name.into(), value.into());
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.config.headers.insert(name.into(), value.into());
self
}
pub fn connect_timeout(mut self, timeout: Duration) -> Self {
self.config.connect_timeout_s = timeout.as_secs_f64();
self
}
pub fn call_timeout(mut self, timeout: Duration) -> Self {
self.config.call_timeout_s = timeout.as_secs_f64();
self
}
pub fn max_result_chars(mut self, chars: usize) -> Self {
self.config.max_result_chars = chars;
self
}
fn literal_refs(&self) -> HashMap<String, String> {
let config = &self.config;
config
.args
.iter()
.chain(config.env.values())
.chain(config.url.iter())
.chain(config.headers.values())
.flat_map(|text| var_ref_names(text))
.map(|name| (name.clone(), format!("${{{name}}}")))
.collect()
}
}
#[derive(Clone)]
pub struct Memory {
store: SessionStore,
retention: (i64, i64, f64),
}
impl std::fmt::Debug for Memory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Memory")
.field("retention", &self.retention)
.finish_non_exhaustive()
}
}
impl Memory {
pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
Self::wrap(SessionStore::open(path.as_ref()))
}
pub fn open_with(
path: impl AsRef<Path>,
embedder: Arc<dyn Embedder>,
) -> Result<Self, BuildError> {
Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
}
pub fn in_memory() -> Result<Self, BuildError> {
Self::open(":memory:")
}
fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
let memory = builtin_config().memory;
Ok(Self {
store: store.map_err(|error| BuildError::Memory(error.0))?,
retention: (
memory.retention_max_episodes,
memory.retention_max_sessions,
memory.retention_max_age_days,
),
})
}
pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
self.retention = (episodes, sessions, max_age_days);
self
}
pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
Ok(self
.store
.recent_sessions(limit)
.map_err(|error| BuildError::Memory(error.0))?
.into_iter()
.map(|session| (session.session_id, session.title))
.collect())
}
pub fn store(&self) -> &SessionStore {
&self.store
}
}
fn registry_for(builtins: Builtins) -> ToolRegistry {
let registry = ToolRegistry::new();
let mut tools: Vec<Box<dyn Tool>> = Vec::new();
if builtins != Builtins::None {
tools.push(Box::new(files::ReadFileTool));
tools.push(Box::new(files::ListDirTool));
tools.push(Box::new(search::SearchFilesTool));
tools.push(Box::new(search::FindFilesTool));
}
if matches!(builtins, Builtins::Files | Builtins::All) {
tools.push(Box::new(files::WriteFileTool));
tools.push(Box::new(files::EditFileTool));
}
if builtins == Builtins::All {
tools.push(Box::new(exec::RunCommandTool));
tools.push(Box::new(exec::PythonExecTool));
tools.push(Box::new(web::WebFetchTool));
}
for tool in tools {
registry
.register(tool)
.expect("built-in tool names are unique");
}
registry
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RunResult {
pub answer: String,
pub output: String,
pub turn: Option<TurnSummary>,
pub usage: Usage,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Turn {
Goal(String),
Skill { name: String, task: String },
Specialist {
name: String,
task: String,
with_context: bool,
},
}
impl Turn {
pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
Self::Skill {
name: name.into(),
task: task.into(),
}
}
pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
Self::Specialist {
name: name.into(),
task: task.into(),
with_context: false,
}
}
pub fn with_context(mut self) -> Self {
if let Self::Specialist { with_context, .. } = &mut self {
*with_context = true;
}
self
}
}
impl From<&str> for Turn {
fn from(goal: &str) -> Self {
Self::Goal(goal.to_owned())
}
}
impl From<String> for Turn {
fn from(goal: String) -> Self {
Self::Goal(goal)
}
}
impl From<&String> for Turn {
fn from(goal: &String) -> Self {
Self::Goal(goal.clone())
}
}
pub struct Agent {
harness: Harness,
conversation: Conversation,
notices: Vec<String>,
}
impl Agent {
pub fn builder() -> AgentBuilder {
AgentBuilder::default()
}
pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
self.run_with_events(turn, |_| {}).await
}
pub async fn run_with_events(
&mut self,
turn: impl Into<Turn>,
mut on_event: impl FnMut(TurnEvent<'_>),
) -> Result<RunResult, RunError> {
let (kind, prompt, display) = match turn.into() {
Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
Turn::Skill { name, task } => {
let skill = self
.harness
.context
.skills
.get(&name)
.cloned()
.ok_or(RunError::UnknownSkill(name.clone()))?;
let display = format!("/{name} {task}").trim_end().to_owned();
(TurnKind::Skill(skill), task, display)
}
Turn::Specialist {
name,
task,
with_context,
} => {
if !self.harness.agents.enabled
|| self.harness.context.specialties.get(&name).is_none()
{
return Err(RunError::UnknownSpecialist(name));
}
let display = format!("/agent {name} {task}");
(TurnKind::Agent { name, with_context }, task, display)
}
};
let output = self
.harness
.run_kind(
&mut self.conversation.0,
&kind,
&prompt,
&display,
&mut on_event,
)
.await;
if let Some(store) = &self.harness.memory {
let _ = store.persist(&self.conversation.0);
}
let output = output?;
Ok(RunResult {
answer: final_answer(&self.conversation.0.messages).to_owned(),
output,
turn: self.conversation.0.last_turn.clone(),
usage: self.conversation.0.usage,
})
}
#[cfg(feature = "agent86ui")]
pub async fn ui_action(&mut self, action: Action) -> Result<RunResult, RunError> {
self.ui_action_with_events(action, |_| {}).await
}
#[cfg(feature = "agent86ui")]
pub async fn ui_action_with_events(
&mut self,
action: Action,
on_event: impl FnMut(TurnEvent<'_>),
) -> Result<RunResult, RunError> {
let text = self
.harness
.accept_ui_action(&self.conversation.0.session_id, &action)
.map_err(RunError::UiAction)?;
self.run_with_events(Turn::Goal(text), on_event).await
}
pub fn cancel_handle(&self) -> CancelToken {
self.harness.cancel.clone()
}
pub fn conversation(&self) -> &Conversation {
&self.conversation
}
pub fn with_conversation(mut self, conversation: Conversation) -> Self {
self.conversation = conversation;
#[cfg(feature = "agent86ui")]
self.replay_surfaces();
self
}
#[cfg(feature = "agent86ui")]
fn replay_surfaces(&self) {
if let Some(ui) = &self.harness.context.ui {
ui.replay(&self.conversation.0, &self.harness.context);
}
}
#[cfg(feature = "agent86ui")]
pub fn surfaces(&self) -> Vec<AgentMessage> {
self.harness
.context
.ui
.as_ref()
.map(|ui| ui.snapshot())
.unwrap_or_default()
}
pub fn session_id(&self) -> &str {
self.conversation.id()
}
pub fn secret_names(&self) -> Vec<String> {
self.harness.context.secrets.names()
}
pub fn notes(&self) -> Vec<String> {
let mut notes = self.notices.clone();
if let Some(mcp) = &self.harness.mcp {
notes.extend(mcp.notes());
}
notes.extend(self.harness.tracer.note());
notes
}
pub fn skills(&self) -> Vec<String> {
self.harness.context.skills.keys().cloned().collect()
}
pub fn specialists(&self) -> Vec<String> {
if !self.harness.agents.enabled {
return Vec::new();
}
self.harness
.context
.specialties
.names()
.into_iter()
.map(str::to_owned)
.collect()
}
pub fn tool_names(&self) -> Vec<String> {
self.harness.registry.names()
}
pub fn harness(&self) -> &Harness {
&self.harness
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Conversation(AgentState);
#[derive(Debug, Clone, PartialEq)]
pub struct ConversationMessage {
pub role: Role,
pub text: String,
pub tool_calls: Vec<ToolCall>,
pub answers: Option<String>,
}
impl Conversation {
pub fn new() -> Self {
Self::default()
}
pub fn id(&self) -> &str {
&self.0.session_id
}
pub fn messages(&self) -> Vec<ConversationMessage> {
self.0
.messages
.iter()
.map(|message| ConversationMessage {
role: message.role,
text: message.content.clone(),
tool_calls: message.tool_calls.clone(),
answers: message.tool_call_id.clone(),
})
.collect()
}
pub fn steps(&self) -> usize {
self.0.step_count()
}
pub fn usage(&self) -> Usage {
self.0.usage
}
pub fn last_turn(&self) -> Option<&TurnSummary> {
self.0.last_turn.as_ref()
}
pub fn to_json(&self) -> String {
serde_json::to_string(&self.0).expect("a conversation always serializes")
}
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json).map(Self)
}
}
type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
pub struct FnTool {
name: String,
description: String,
parameters: Value,
side_effecting: bool,
run: Box<ToolFn>,
}
impl FnTool {
pub fn new(
name: impl Into<String>,
description: impl Into<String>,
parameters: Value,
run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
+ Send
+ Sync
+ 'static,
) -> Self {
Self {
name: name.into(),
description: description.into(),
parameters,
side_effecting: false,
run: Box::new(run),
}
}
pub fn side_effecting(mut self) -> Self {
self.side_effecting = true;
self
}
}
impl Tool for FnTool {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
&self.description
}
fn side_effecting(&self) -> bool {
self.side_effecting
}
fn parameters(&self) -> Value {
self.parameters.clone()
}
fn execute(
&self,
args: &Map<String, Value>,
ctx: &ToolContext,
) -> Result<ToolResult, ToolError> {
match (self.run)(args, ctx) {
Ok(content) => Ok(ToolResult {
call_id: String::new(),
name: self.name.clone(),
ok: true,
content,
error: None,
metadata: Map::new(),
}),
Err(message) => Err(ToolError::Raised {
exception: "ToolError".to_owned(),
message,
}),
}
}
}
pub mod providers {
pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
pub use crate::provider::google::{GoogleConfig, GoogleProvider};
pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
pub use crate::types::{
Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
};
}