Skip to main content

agent86_core/
sdk.rs

1//! Embedding agent86 in another program (beyond Python; see
2//! `docs/adr/0003-embeddable-agent-api.md`).
3//!
4//! [`Agent::builder`] assembles the same [`Harness`] the CLI, the interface, and
5//! the ACP server run, from parts the caller hands it, with no config file,
6//! environment variable, home directory, keyring, or terminal involved:
7//!
8//! ```no_run
9//! use agent86_core::sdk::{Agent, ApprovalMode, Builtins, FnTool};
10//! use serde_json::json;
11//! # fn provider() -> std::sync::Arc<dyn agent86_core::sdk::Provider> { unimplemented!() }
12//!
13//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
14//! let weather = FnTool::new(
15//!     "get_weather",
16//!     "The current weather in a city.",
17//!     json!({"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}),
18//!     |args, _ctx| Ok(format!("Sunny in {}", args["city"].as_str().unwrap_or("?"))),
19//! );
20//! let mut agent = Agent::builder()
21//!     .provider(provider())
22//!     .workspace("./project")
23//!     .builtins(Builtins::ReadOnly)
24//!     .tool(weather)
25//!     .approval(ApprovalMode::Ask)
26//!     .approver(|tool, _preview| tool != "write_file")
27//!     .build()?;
28//! let reply = agent.run("What's the weather in Oslo?").await?;
29//! println!("{}", reply.answer);
30//! # Ok(()) }
31//! ```
32//!
33//! What it keeps from the harness, unchanged: the ReAct loop and its circuit
34//! breaker, the workspace jail, the approval gate (side-effecting calls with
35//! nobody to ask are declined), the guardrails, the secret vault's redaction,
36//! parallel read-only tool calls, context fitting and compaction, and the
37//! [`TurnEvent`] stream. On request it adds:
38//!
39//! - MCP servers ([`McpServer`]), values taken literally, never expanded from the
40//!   environment or the keyring;
41//! - long-term memory ([`Memory`]): sessions saved after every step, past turns
42//!   recalled into similar later ones, `remember` and `recall`;
43//! - skills from the directories named ([`AgentBuilder::skills_dir`]), offered to
44//!   the model through `use_skill` and run directly with [`Turn::skill`];
45//! - sub-agents ([`SubAgents`]): `delegate`, agent86's built-in specialists and
46//!   the caller's own, in parallel and in git worktrees, each narrowing its
47//!   caller's authority, and run directly with [`Turn::specialist`];
48//! - named models ([`Model`], [`AgentBuilder::model`]) for specialists' `model:`
49//!   lines and for triage routing ([`AgentBuilder::triage`]);
50//! - OpenTelemetry spans ([`Otel`]), with agent86's span and attribute names;
51//! - questions a turn asks mid-way: whether to raise a limit it reached
52//!   ([`AgentBuilder::on_limit`]) and a secret the model needs
53//!   ([`AgentBuilder::on_secret_request`]), plus secrets the program already holds
54//!   ([`AgentBuilder::secret`]), which tools get as environment variables and the
55//!   model only ever sees as `${secret:NAME}`.
56//!
57//! A conversation is a [`Conversation`], which saves to and loads from the JSON
58//! the session database keeps.
59//!
60//! Nothing is discovered: no `.agent86/` or `~/.agent86/` directory is read, and
61//! no `OTEL_*` variable either. Each part is what the caller passes in.
62//!
63//! This module is the crate's public surface, the one semantic versioning
64//! covers; the rest of the crate is public for the `agent86` binary and makes no
65//! stability promise.
66
67use 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
89// Every type this module's signatures use, re-exported here so a user names no
90// other module of the crate: those are public for the `agent86` binary only, are
91// hidden from the docs, and carry no stability promise.
92pub 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/// agent86UI's protocol layer (ADR 0005): A2UI 1.0 messages, catalogs, the
105/// validator, and the headless surface runtime a renderer can build on.
106#[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/// Which of agent86's own tools an [`Agent`] offers, each set including the one
113/// before it. Every one of them is jailed to the workspace.
114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
115pub enum Builtins {
116    /// None: only the tools given with [`AgentBuilder::tool`].
117    #[default]
118    None,
119    /// `read_file`, `list_dir`, `search_files`, and `find_files`.
120    ReadOnly,
121    /// Also `write_file` and `edit_file`, which go through the approval gate.
122    Files,
123    /// Also `run_command` and `python_exec` (under the sandbox executor) and
124    /// `web_fetch` (guarded against SSRF), all through the approval gate.
125    All,
126}
127
128/// The system prompt when none is given (see [`AgentBuilder::system_prompt`]).
129fn 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/// Why [`AgentBuilder::build`] failed.
142///
143/// `#[non_exhaustive]` (since 1.2.0): later releases may add reasons, so a
144/// `match` outside this crate needs a `_` arm; the `Display` text describes any.
145#[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    /// A secret given to [`AgentBuilder::secret`] was refused. The message names
169    /// the secret and why, never its value.
170    #[error("the secret {name} was refused: {reason}")]
171    Secret { name: String, reason: String },
172    /// [`AgentBuilder::ui`] was given no catalogs, or one that does not compile.
173    #[cfg(feature = "agent86ui")]
174    #[error("agent86UI could not be set up: {0}")]
175    Ui(String),
176}
177
178/// Why [`Agent::run`] failed.
179///
180/// `#[non_exhaustive]` (since 1.2.0): later releases may add reasons, so a
181/// `match` outside this crate needs a `_` arm; the `Display` text describes any.
182#[derive(Debug, Clone, PartialEq, thiserror::Error)]
183#[non_exhaustive]
184pub enum RunError {
185    /// The turn failed: the model could not be reached, or a limit tripped.
186    #[error(transparent)]
187    Harness(#[from] HarnessError),
188    /// [`Turn::skill`] named a skill the agent does not have.
189    #[error("no skill named '{0}'")]
190    UnknownSkill(String),
191    /// [`Turn::specialist`] named a specialist the agent does not have, or the
192    /// agent has no [`SubAgents`].
193    #[error("no specialist named '{0}'")]
194    UnknownSpecialist(String),
195    /// [`Agent::ui_action`] was given an action no surface up could have sent
196    /// (no renderer, no such surface or component, or no name). The message
197    /// says which, never the action's values.
198    #[cfg(feature = "agent86ui")]
199    #[error("the UI action was refused: {0}")]
200    UiAction(String),
201}
202
203/// Decides a side-effecting call: given the tool's name and what the call would
204/// do, `true` lets it run.
205type Approver = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
206
207/// Answers [`AgentBuilder::on_secret_request`]: the value, or `None` to decline.
208type SecretAsker = Box<dyn Fn(&SecretRequest) -> Option<String> + Send + Sync>;
209
210/// Builds an [`Agent`]; start from [`Agent::builder`].
211pub 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    /// Never printed: the builder has no `Debug`, and errors name only the secret.
239    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
277/// The window assumed when the caller names none: small enough that a turn is
278/// compacted before most models would refuse it.
279pub const DEFAULT_CONTEXT_WINDOW: u64 = 128_000;
280
281impl AgentBuilder {
282    /// The model. Build one with [`crate::provider`]'s adapters or implement
283    /// [`Provider`] yourself (only `stream` is required).
284    pub fn provider(mut self, provider: Arc<dyn Provider>) -> Self {
285        self.provider = Some(provider);
286        self
287    }
288
289    /// The directory the tools are jailed to. Required, so an embedded agent
290    /// never silently works on the process's current directory.
291    pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
292        self.workspace = Some(path.into());
293        self
294    }
295
296    /// The system prompt; when not set, agent86's own identity
297    /// ([`crate::prompt::BASE_IDENTITY`]), followed, when `run_command` or
298    /// `python_exec` is offered, by a line naming the platform, the shell
299    /// commands run with, and the Python command
300    /// ([`crate::prompt::platform_note`]), since a model otherwise assumes Linux.
301    pub fn system_prompt(mut self, text: impl Into<String>) -> Self {
302        self.system = Some(text.into());
303        self
304    }
305
306    /// Which of agent86's tools to offer ([`Builtins::None`] when not set).
307    pub fn builtins(mut self, builtins: Builtins) -> Self {
308        self.builtins = builtins;
309        self
310    }
311
312    /// Offer `tool` too. A name already taken fails [`AgentBuilder::build`].
313    pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
314        self.tools.push(Box::new(tool));
315        self
316    }
317
318    /// The approval mode for side-effecting calls: `auto` runs them, `deny`
319    /// refuses them, and `ask` (the default) asks the [`AgentBuilder::approver`],
320    /// declining every one when there is none.
321    pub fn approval(mut self, mode: ApprovalMode) -> Self {
322        self.approval = mode;
323        self
324    }
325
326    /// Who is asked in `ask` mode: given the tool's name and what the call would do
327    /// (its arguments, and a diff for a file write), `true` lets it run. Called on
328    /// the turn's thread, one question at a time.
329    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    /// Model calls one turn may make before it stops (40 by default).
338    pub fn max_steps(mut self, steps: u32) -> Self {
339        self.limits.max_steps = steps;
340        self
341    }
342
343    /// The spend, in US dollars, at which a turn stops; `0` for no cap (5 by
344    /// default). Only priced models count toward it.
345    pub fn max_cost_usd(mut self, usd: f64) -> Self {
346        self.limits.max_cost_usd = usd;
347        self
348    }
349
350    /// Seconds one turn may run; `0` for no limit (900 by default).
351    pub fn max_wall_clock_s(mut self, seconds: u64) -> Self {
352        self.limits.max_wall_clock_s = seconds;
353        self
354    }
355
356    /// Seconds a command or fetch may run (60 by default).
357    pub fn tool_timeout(mut self, timeout: Duration) -> Self {
358        self.tool_timeout = timeout;
359        self
360    }
361
362    /// The tokens of context the model holds, which history is fitted to.
363    pub fn context_window(mut self, tokens: u64) -> Self {
364        self.context_window = tokens;
365        self
366    }
367
368    /// The most tokens one model call may write (8192 by default).
369    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
370        self.max_output_tokens = tokens;
371        self
372    }
373
374    /// Ingress, egress, and observation scanning (agent86's defaults when not set:
375    /// warn, warn, on). Its `approval` is ignored; use [`AgentBuilder::approval`].
376    pub fn guardrails(mut self, guardrails: GuardrailsConfig) -> Self {
377        self.guardrails = guardrails;
378        self
379    }
380
381    /// Write the flight recorder's `trace.jsonl` in `dir`, redacted as the CLI's
382    /// is. Off when not set.
383    pub fn trace_dir(mut self, dir: impl Into<PathBuf>) -> Self {
384        self.trace_dir = Some(dir.into());
385        self
386    }
387
388    /// Start the MCP server `server` with the agent and offer its tools, named
389    /// `mcp__<name>__<tool>` and asked about unless the server marks them
390    /// read-only. A server that fails to start fails [`AgentBuilder::build`]; the
391    /// servers stop when the agent is dropped.
392    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    /// Give the agent long-term memory: the session is saved after every step and
398    /// at the end of each turn, finished turns are recalled into similar later
399    /// ones, and the model gets `remember` and `recall`. One [`Memory`] can be
400    /// shared by several agents.
401    pub fn memory(mut self, memory: Memory) -> Self {
402        self.memory = Some(memory);
403        self
404    }
405
406    /// Continue the session `id` from [`AgentBuilder::memory`] (any session saved
407    /// there, by this API, `agent86`, or Python's agent86).
408    pub fn session(mut self, id: impl Into<String>) -> Self {
409        self.session = Some(id.into());
410        self
411    }
412
413    /// Offer the skills in `dir`, a directory of `<name>/SKILL.md` folders, in
414    /// agent86's (and Claude Code's) skill format. The model sees their names and
415    /// descriptions and loads one with `use_skill`, whose `allowed-tools` then
416    /// limit it; [`Turn::skill`] runs one directly. The folders join the jail for
417    /// reading, since skills bundle files. Called again, an earlier directory wins a
418    /// name both hold.
419    pub fn skills_dir(mut self, dir: impl Into<PathBuf>) -> Self {
420        self.skill_dirs.push(dir.into());
421        self
422    }
423
424    /// A verification gate: when a turn that changed the workspace gives its final
425    /// answer, run `command` as a `run_command` call (under the approval mode, as
426    /// the model's own calls are) and send a failure back to the model, up to
427    /// `max_attempts` times, before the answer stands. [`RunResult::verification`]
428    /// says what it did.
429    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    /// Let the model delegate to sub-agents (see [`SubAgents`]).
435    pub fn subagents(mut self, subagents: SubAgents) -> Self {
436        self.subagents = Some(subagents);
437        self
438    }
439
440    /// Name a model, for a specialist whose definition says `model: <name>` and for
441    /// [`AgentBuilder::triage`]. A specialist naming a model that is not here runs
442    /// on the turn's model, with a notice.
443    pub fn model(mut self, name: impl Into<String>, model: Model) -> Self {
444        self.models.insert(name.into(), model);
445        self
446    }
447
448    /// Route each turn by its task, as agent86's `[model] router = "triage"` does:
449    /// a short, plain ask goes to the model named `cheap`, anything else to
450    /// `frontier` (both named with [`AgentBuilder::model`]); compaction summaries
451    /// use `cheap`. The [`AgentBuilder::provider`] is still required, and serves
452    /// nothing while routing is on.
453    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    /// Export OpenTelemetry spans: a `turn` span per turn, parent of a
459    /// `model_call` per model call and a `tool_call` per tool call, with the GenAI
460    /// attribute names agent86 uses. Exported on a worker thread, flushed at the end
461    /// of each turn and when the agent is dropped; a collector that cannot be
462    /// reached becomes a note ([`Agent::notes`]), never an error.
463    pub fn otel(mut self, otel: Otel) -> Self {
464        self.otel = Some(otel);
465        self
466    }
467
468    /// Asked when a turn reaches a limit (its step budget, a sub-agent's, or the
469    /// output cap before any text): given what was reached and the values offered,
470    /// return the new limit to go on with, or `None` to stop there as without this
471    /// callback. A raise lasts for the agent's life, or for one specialist's run
472    /// when [`LimitHit::run_only`] says so. Called on the turn's thread, one
473    /// question at a time with approvals.
474    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    /// Offer the model `request_secret`, and ask `answer` when it is called: given
483    /// the variable's name and the model's reason, return the value (held for the
484    /// agent's life, at least 6 characters) or `None` to decline. Tools that run
485    /// commands get it as that environment variable, and every path back to the
486    /// model, the conversation, and the trace shows only `${secret:NAME}`. Names
487    /// that would change how programs run (`PATH`, `LD_PRELOAD`, ...) are refused
488    /// before `answer` is asked. Nothing is kept in a keyring.
489    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    /// Declare a renderer (ADR 0005): offer the model `render_ui`, through which
498    /// it draws interactive UI as A2UI 1.0 messages in the renderer's catalogs.
499    /// Each validated message reaches [`Agent::run`]'s callback as
500    /// [`TurnEvent::Ui`], for the program to draw with its own widgets (Google's
501    /// React and Lit renderers take them as they are). The system prompt gains a
502    /// section with the catalogs' instructions and components on every request;
503    /// sub-agents never draw.
504    #[cfg(feature = "agent86ui")]
505    pub fn ui(mut self, ui: Ui) -> Self {
506        self.ui = Some(ui);
507        self
508    }
509
510    /// Hold a secret the program already has (an API token for a command the
511    /// agent will run), with the same rules as [`AgentBuilder::on_secret_request`]:
512    /// tools get it as the environment variable `name`, the model sees only
513    /// `${secret:NAME}`, and `write_file` and `edit_file` may put it in a file the
514    /// approver sees. `name` must be a valid variable name and the value at least 6
515    /// characters, or [`AgentBuilder::build`] fails.
516    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    /// Assemble the agent. Reads nothing but the workspace path, the memory
522    /// database, skill and specialist directories when given, and starts the MCP
523    /// servers given.
524    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        // Beyond Python: the default prompt says where commands run, when they can.
556        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        // Skills: only the directories named, highest precedence first, their
589        // folders readable through the jail.
590        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        // Sub-agents: `delegate`, and the specialists.
606        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, &registry)?;
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            // A renderer that answers waits answers `ask_user` too (ADR 0006).
734            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        // A resumed session's surfaces come back from its history.
750        #[cfg(feature = "agent86ui")]
751        agent.replay_surfaces();
752        Ok(agent)
753    }
754
755    /// The router for the named models: it builds nothing, it looks names up, so a
756    /// specialist's `model:` resolves with or without triage.
757    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/// Sub-agents for [`AgentBuilder::subagents`]: the model gets `delegate`, which
808/// runs a sub-agent on a task with its own step budget and a fork of the caller's
809/// tools, approvals, and jail. A *specialist* is a named sub-agent with its own
810/// instructions, tool allowlist, approval mode, model, and skills, defined in a
811/// Markdown file with frontmatter (agent86's `.agent86/agents/<name>.md` format;
812/// see `docs/subagents.md`). A specialist's authority only narrows its caller's.
813/// Adjacent specialist delegations run in parallel, each on its own thread, so a
814/// custom [`Provider`] must implement `fresh`; one with `isolation: worktree` runs
815/// in a git worktree and hands back its diff.
816#[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    /// Delegation two levels deep, 8 steps per sub-agent, 3 in parallel, with
840    /// agent86's built-in specialists (`researcher`, `reviewer`, `planner`).
841    pub fn new() -> Self {
842        Self::default()
843    }
844
845    /// How deep delegation may nest; the main agent is depth 0.
846    pub fn max_depth(mut self, depth: u32) -> Self {
847        self.max_depth = depth;
848        self
849    }
850
851    /// Each sub-agent's step budget, kept at or below the turn's.
852    pub fn max_steps(mut self, steps: u32) -> Self {
853        self.max_steps = steps;
854        self
855    }
856
857    /// How many adjacent specialist delegations run at once (1 to 8).
858    pub fn max_parallel(mut self, parallel: u32) -> Self {
859        self.max_parallel = parallel;
860        self
861    }
862
863    /// Leave out agent86's built-in specialists.
864    pub fn without_built_ins(mut self) -> Self {
865        self.built_ins = false;
866        self
867    }
868
869    /// Add the specialists defined in `dir` (`<name>.md` files), replacing a
870    /// built-in or an earlier directory's of the same name. They are trusted as
871    /// the caller's own, so never pass a directory from a repository the user did
872    /// not write: its files become prompt text and tool scopes. A file that does
873    /// not parse is skipped, and said so in [`Agent::notes`].
874    pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
875        self.dirs.push(dir.into());
876        self
877    }
878}
879
880/// A model for [`AgentBuilder::model`].
881#[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    /// `provider`, with the agent's context window and output cap unless set.
901    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    /// The tokens of context this model holds.
910    pub fn context_window(mut self, tokens: u64) -> Self {
911        self.context_window = Some(tokens);
912        self
913    }
914
915    /// The most tokens one call to this model may write.
916    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
917        self.max_output_tokens = Some(tokens);
918        self
919    }
920}
921
922/// A renderer for agent86UI ([`AgentBuilder::ui`]): the A2UI catalogs it
923/// draws, in order of preference.
924#[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    /// A renderer for the specification's basic catalog, which Google's
949    /// renderers implement.
950    pub fn basic() -> Self {
951        Self::new([Catalog::basic().clone()])
952    }
953
954    /// A renderer for `catalogs` (load one with [`Catalog::from_value`]), in
955    /// order of preference.
956    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    /// Let the model wait for the user's answer (`render_ui` with `wait`), for
965    /// a form in the middle of a task: once the call's [`TurnEvent::Ui`]
966    /// messages are out, `answer` is asked for the first [`Action`] the user
967    /// takes on one of [`UiWait::surface_ids`], or `None` when they dismiss it.
968    /// Called on the turn's thread, one question at a time with approvals, and
969    /// never once the turn is cancelled. The action's context becomes the call's
970    /// result, through the vault and the ingress guardrail as typed input does.
971    /// Without it, a waiting call is refused and the model asks without waiting.
972    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    /// Let `Image`, `Video`, and `AudioPlayer` load `https` URLs. Off by
981    /// default: a surface's media is then a `data:` URL or a file in the
982    /// workspace (a path relative to it, which the program serves), since a
983    /// fetch can track the user or carry data out in its URL.
984    pub fn allow_remote_media(mut self) -> Self {
985        self.remote_media = true;
986        self
987    }
988
989    /// The catalogs, in order of preference.
990    pub fn catalogs(&self) -> &[Catalog] {
991        &self.catalogs
992    }
993}
994
995/// Where [`AgentBuilder::otel`] sends spans. OTLP is HTTP with JSON bodies.
996#[derive(Debug, Clone)]
997pub struct Otel {
998    destination: crate::otel::Destination,
999}
1000
1001impl Otel {
1002    /// An OTLP/HTTP collector's traces endpoint, such as
1003    /// `http://localhost:4318/v1/traces`, with a 10-second timeout.
1004    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    /// Each span as one line of JSON on stderr.
1015    pub fn console() -> Self {
1016        Self {
1017            destination: crate::otel::Destination::Console,
1018        }
1019    }
1020
1021    /// Send `name: value` with every export (an API key, for a hosted collector).
1022    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    /// How long one export may take.
1030    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
1038/// Start `servers` on a manager attached to `registry`, failing on the first that
1039/// does not start or whose tools collide; dropping the manager stops the rest.
1040fn 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/// An MCP server for [`AgentBuilder::mcp_server`]. Every value (arguments,
1082/// environment, URL, headers) is used exactly as given: a `${VAR}` in one is
1083/// never expanded from the process's environment or the keyring, as it would be
1084/// in a config file, so pass resolved values.
1085#[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    /// A server agent86 starts as `command` with `args`, speaking MCP on its
1098    /// standard streams. It gets agent86's scrubbed environment plus
1099    /// [`McpServer::env`], never the whole of this process's.
1100    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    /// A server at `url` over streamable HTTP.
1109    pub fn http(url: impl Into<String>) -> Self {
1110        Self::from(json!({"url": url.into(), "transport": "http"}))
1111    }
1112
1113    /// A server at `url` over the older SSE transport.
1114    pub fn sse(url: impl Into<String>) -> Self {
1115        Self::from(json!({"url": url.into(), "transport": "sse"}))
1116    }
1117
1118    /// Set an environment variable for a stdio server.
1119    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    /// Send a header with every request to a remote server.
1125    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    /// How long the server has to start and list its tools (30 seconds by default).
1131    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
1132        self.config.connect_timeout_s = timeout.as_secs_f64();
1133        self
1134    }
1135
1136    /// How long one tool call may take (120 seconds by default).
1137    pub fn call_timeout(mut self, timeout: Duration) -> Self {
1138        self.config.call_timeout_s = timeout.as_secs_f64();
1139        self
1140    }
1141
1142    /// The most characters of a result the model is shown (8000 by default).
1143    pub fn max_result_chars(mut self, chars: usize) -> Self {
1144        self.config.max_result_chars = chars;
1145        self
1146    }
1147
1148    /// Every `${VAR}` in the values mapped to itself, so the manager's expansion
1149    /// leaves it as written (overrides win over the environment and the keyring).
1150    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/// Long-term memory for [`AgentBuilder::memory`]: agent86's SQLite memory
1165/// database (the same file and schema the CLI uses, so its sessions and facts are
1166/// shared), opened once and cheap to clone.
1167#[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    /// Open (creating if needed) the database at `path`, embedding with the
1183    /// offline hashing embedder (`hash:256`), which needs no model download.
1184    pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1185        Self::wrap(SessionStore::open(path.as_ref()))
1186    }
1187
1188    /// [`Memory::open`] with another embedder, such as the sentence-transformers
1189    /// model `crate::memory::embeddings::build_embedder` loads. Episodes and facts
1190    /// written with one embedder are only found again with the same one.
1191    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    /// A database that lives only as long as this value and its clones.
1199    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    /// Keep at most `episodes` episodes and `sessions` sessions, and none older
1216    /// than `max_age_days` (`0` for no age limit), pruned when an agent is built
1217    /// (1000, 500, and no age limit by default). Pinned entries are kept.
1218    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    /// The sessions saved here, newest first: (id, title).
1224    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    /// The store underneath, for what this type does not cover yet (facts,
1235    /// episodes, pins). Its API makes no stability promise.
1236    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/// What one [`Agent::run`] produced.
1268///
1269/// `#[non_exhaustive]` (since 1.2.0): later releases may add fields, so code
1270/// outside this crate reads the fields it needs and cannot build one or
1271/// destructure it without `..`.
1272#[derive(Debug, Clone, PartialEq)]
1273#[non_exhaustive]
1274pub struct RunResult {
1275    /// The turn's answer: the model's last message when it made no tool call,
1276    /// otherwise empty (a turn stopped by a limit or a cancel).
1277    pub answer: String,
1278    /// Everything the turn streamed, notices and `[tool] ...` lines included, as
1279    /// `agent86 run --output full` prints it.
1280    pub output: String,
1281    /// The turn's tokens, cost, steps, and tool calls.
1282    pub turn: Option<TurnSummary>,
1283    /// The conversation's usage so far.
1284    pub usage: Usage,
1285    /// What the verification gate did this turn, when one is set
1286    /// ([`AgentBuilder::verify`]).
1287    pub verification: Option<Verification>,
1288}
1289
1290/// One turn for [`Agent::run`]: a goal (a `&str` or `String` converts to one),
1291/// a skill run directly, or a specialist run directly.
1292#[derive(Debug, Clone, PartialEq, Eq)]
1293pub enum Turn {
1294    /// The model works toward the goal with every tool it is offered.
1295    Goal(String),
1296    /// The skill's instructions lead the user's message and the skill is active
1297    /// from the first step, so its `allowed-tools` apply at once.
1298    Skill { name: String, task: String },
1299    /// The specialist runs the task as a sub-agent at depth 1, and the exchange is
1300    /// kept as an ordinary user and assistant message. With `with_context`, the
1301    /// conversation so far is summarized and handed over.
1302    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    /// For a [`Turn::Specialist`], hand over a summary of the conversation so far.
1326    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
1352/// An agent: a harness and its conversation. Each [`Agent::run`] is one turn
1353/// that continues the conversation.
1354pub struct Agent {
1355    harness: Harness,
1356    conversation: Conversation,
1357    /// What building found worth saying (a specialist file skipped).
1358    notices: Vec<String>,
1359}
1360
1361impl Agent {
1362    pub fn builder() -> AgentBuilder {
1363        AgentBuilder::default()
1364    }
1365
1366    /// Run one turn: a goal, or a [`Turn`].
1367    pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1368        self.run_with_events(turn, |_| {}).await
1369    }
1370
1371    /// [`Agent::run`], reporting each [`TurnEvent`] (text, reasoning, tool calls
1372    /// and their results, usage) as it happens.
1373    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        // Saved after a failed turn too, as the CLI does; a failed write loses this
1416        // save, never the turn (the harness saved after every step already).
1417        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    /// Hand the model what the user did on a surface (a button pressed), when no
1431    /// `render_ui` call was waiting for it: it becomes the next user message,
1432    /// `[ui action] <name> on <surfaceId>: <context as JSON>` (plus the event's
1433    /// `userMessage` on its own line), and runs a turn as [`Agent::run`] does,
1434    /// through the vault and the ingress guardrail like typed input. Recorded as
1435    /// `ui_action`, without its values. Call it after the turn that drew the
1436    /// surface has ended; actions taken during a turn wait for it, as typed
1437    /// input does.
1438    #[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    /// [`Agent::ui_action`], reporting each [`TurnEvent`] as it happens.
1444    #[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    /// A handle that stops the running turn at its next safe point (before a model
1458    /// call, while streaming, or between tool calls), from any thread.
1459    pub fn cancel_handle(&self) -> CancelToken {
1460        self.harness.cancel.clone()
1461    }
1462
1463    /// The conversation so far, to read or to save with [`Conversation::to_json`].
1464    pub fn conversation(&self) -> &Conversation {
1465        &self.conversation
1466    }
1467
1468    /// Continue an earlier conversation instead of starting a new one.
1469    /// With agent86UI, the surfaces are rebuilt from its `render_ui` calls, as
1470    /// on resuming a session; [`Agent::surfaces`] gives them to draw.
1471    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    /// Rebuild the renderer's surfaces from the conversation's history.
1479    #[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    /// Every surface up now, each as the one `createSurface` message that draws
1487    /// it as it is (its components and data model), in surface id order. After
1488    /// resuming a session ([`AgentBuilder::session`] or
1489    /// [`Agent::with_conversation`]) the surfaces are rebuilt from the
1490    /// history's `render_ui` calls, so a program that reopens draws these to
1491    /// show the user where they were. What the user typed but never submitted is
1492    /// the renderer's alone, so it is not here. Empty without a renderer.
1493    #[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    /// The session's id, under which [`AgentBuilder::memory`] saves it.
1504    pub fn session_id(&self) -> &str {
1505        self.conversation.id()
1506    }
1507
1508    /// The names of the secrets held, never their values.
1509    pub fn secret_names(&self) -> Vec<String> {
1510        self.harness.context.secrets.names()
1511    }
1512
1513    /// What is worth telling the user, oldest first: specialist files that were
1514    /// skipped, what the MCP servers reported (a server that dropped, reconnected,
1515    /// or changed its tools), and why spans could not be exported.
1516    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    /// The skills [`Turn::skill`] can run, in precedence order.
1526    pub fn skills(&self) -> Vec<String> {
1527        self.harness.context.skills.keys().cloned().collect()
1528    }
1529
1530    /// The specialists [`Turn::specialist`] and `delegate` can run.
1531    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    /// The names of the tools the model is offered.
1545    pub fn tool_names(&self) -> Vec<String> {
1546        self.harness.registry.names()
1547    }
1548
1549    /// The harness underneath, for what this module does not cover yet. Its API
1550    /// makes no stability promise.
1551    pub fn harness(&self) -> &Harness {
1552        &self.harness
1553    }
1554}
1555
1556/// A conversation: its messages, steps, and usage. It is saved as the JSON the
1557/// session database keeps (`state_json`, the format agent86 and Python's agent86
1558/// share), so a saved conversation opens in either.
1559/// [`Conversation::default`] is a new conversation with a fresh id.
1560#[derive(Debug, Clone, Default, PartialEq)]
1561pub struct Conversation(AgentState);
1562
1563/// One message of a [`Conversation`].
1564#[derive(Debug, Clone, PartialEq)]
1565pub struct ConversationMessage {
1566    pub role: Role,
1567    /// The text: the user's words, the model's reply, or a tool's result.
1568    pub text: String,
1569    /// The tools an assistant message called.
1570    pub tool_calls: Vec<ToolCall>,
1571    /// For a tool's result, the id of the call it answers.
1572    pub answers: Option<String>,
1573}
1574
1575impl Conversation {
1576    /// A new, empty conversation with a fresh id.
1577    pub fn new() -> Self {
1578        Self::default()
1579    }
1580
1581    /// Its id, which the session database files it under.
1582    pub fn id(&self) -> &str {
1583        &self.0.session_id
1584    }
1585
1586    /// Its messages, oldest first (the system prompt is not one of them).
1587    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    /// The model calls made so far.
1601    pub fn steps(&self) -> usize {
1602        self.0.step_count()
1603    }
1604
1605    /// The tokens and cost so far.
1606    pub fn usage(&self) -> Usage {
1607        self.0.usage
1608    }
1609
1610    /// The last turn's summary, or `None` before the first.
1611    pub fn last_turn(&self) -> Option<&TurnSummary> {
1612        self.0.last_turn.as_ref()
1613    }
1614
1615    /// The conversation as the session database's JSON.
1616    pub fn to_json(&self) -> String {
1617        serde_json::to_string(&self.0).expect("a conversation always serializes")
1618    }
1619
1620    /// A conversation from [`Conversation::to_json`]'s JSON, or a session
1621    /// database's `state_json`.
1622    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1623        serde_json::from_str(json).map(Self)
1624    }
1625}
1626
1627/// The function behind an [`FnTool`]: given the validated-as-JSON arguments and
1628/// the tool context (its workspace jail, `ctx.policy.resolve_within`), the text
1629/// the model sees, or an error message.
1630type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1631
1632/// A tool from a closure, for the common case where implementing [`Tool`] is more
1633/// than needed. Read-only unless [`FnTool::side_effecting`] says otherwise.
1634pub struct FnTool {
1635    name: String,
1636    description: String,
1637    parameters: Value,
1638    side_effecting: bool,
1639    run: Box<ToolFn>,
1640}
1641
1642impl FnTool {
1643    /// A tool named `name` (letters, digits, `_`, `-`), described to the model by
1644    /// `description`, taking arguments matching the JSON Schema `parameters`.
1645    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    /// Mark the tool as having effects outside the conversation, so every call goes
1664    /// through the approval gate.
1665    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
1710/// The model layer: the [`Provider`] trait, which only needs `stream`, the types
1711/// a provider speaks, and agent86's own adapters, which run any OpenAI-compatible
1712/// endpoint (OpenAI, OpenRouter, Groq, vLLM, LM Studio, llama.cpp), Anthropic,
1713/// Ollama, and Google Gemini, with agent86's retries, redaction, and pricing.
1714pub 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}