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    /// [`Agent::continue_turn`] found nothing it may continue: the last turn
202    /// finished, the conversation changed since it stopped, or the skill it ran
203    /// under is gone. The message says which; nothing was sent to the model.
204    #[error("{0}")]
205    NotContinuable(String),
206}
207
208/// Decides a side-effecting call: given the tool's name and what the call would
209/// do, `true` lets it run.
210type Approver = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
211
212/// Answers [`AgentBuilder::on_secret_request`]: the value, or `None` to decline.
213type SecretAsker = Box<dyn Fn(&SecretRequest) -> Option<String> + Send + Sync>;
214
215/// Builds an [`Agent`]; start from [`Agent::builder`].
216pub struct AgentBuilder {
217    provider: Option<Arc<dyn Provider>>,
218    workspace: Option<PathBuf>,
219    system: Option<String>,
220    builtins: Builtins,
221    tools: Vec<Box<dyn Tool>>,
222    approval: ApprovalMode,
223    approver: Option<Approver>,
224    limits: LimitsConfig,
225    guardrails: GuardrailsConfig,
226    context_window: u64,
227    max_output_tokens: u32,
228    trace_dir: Option<PathBuf>,
229    tool_timeout: Duration,
230    mcp_servers: Vec<(String, McpServer)>,
231    memory: Option<Memory>,
232    session: Option<String>,
233    skill_dirs: Vec<PathBuf>,
234    subagents: Option<SubAgents>,
235    verify: Option<(String, u32)>,
236    models: IndexMap<String, Model>,
237    triage: Option<(String, String)>,
238    otel: Option<Otel>,
239    on_limit: Option<crate::limits::LimitPrompt>,
240    on_secret: Option<SecretAsker>,
241    #[cfg(feature = "agent86ui")]
242    ui: Option<Ui>,
243    /// Never printed: the builder has no `Debug`, and errors name only the secret.
244    secrets: Vec<(String, String)>,
245}
246
247impl Default for AgentBuilder {
248    fn default() -> Self {
249        let config = builtin_config();
250        Self {
251            provider: None,
252            workspace: None,
253            system: None,
254            builtins: Builtins::None,
255            tools: Vec::new(),
256            approval: ApprovalMode::Ask,
257            approver: None,
258            max_output_tokens: config.limits.max_output_tokens,
259            tool_timeout: Duration::from_secs(config.limits.tool_timeout_s),
260            limits: config.limits,
261            guardrails: config.guardrails,
262            context_window: DEFAULT_CONTEXT_WINDOW,
263            trace_dir: None,
264            mcp_servers: Vec::new(),
265            memory: None,
266            session: None,
267            skill_dirs: Vec::new(),
268            subagents: None,
269            verify: None,
270            models: IndexMap::new(),
271            triage: None,
272            otel: None,
273            on_limit: None,
274            on_secret: None,
275            #[cfg(feature = "agent86ui")]
276            ui: None,
277            secrets: Vec::new(),
278        }
279    }
280}
281
282/// The window assumed when the caller names none: small enough that a turn is
283/// compacted before most models would refuse it.
284pub const DEFAULT_CONTEXT_WINDOW: u64 = 128_000;
285
286impl AgentBuilder {
287    /// The model. Build one with [`crate::provider`]'s adapters or implement
288    /// [`Provider`] yourself (only `stream` is required).
289    pub fn provider(mut self, provider: Arc<dyn Provider>) -> Self {
290        self.provider = Some(provider);
291        self
292    }
293
294    /// The directory the tools are jailed to. Required, so an embedded agent
295    /// never silently works on the process's current directory.
296    pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
297        self.workspace = Some(path.into());
298        self
299    }
300
301    /// The system prompt; when not set, agent86's own identity
302    /// ([`crate::prompt::BASE_IDENTITY`]), followed, when `run_command` or
303    /// `python_exec` is offered, by a line naming the platform, the shell
304    /// commands run with, and the Python command
305    /// ([`crate::prompt::platform_note`]), since a model otherwise assumes Linux.
306    pub fn system_prompt(mut self, text: impl Into<String>) -> Self {
307        self.system = Some(text.into());
308        self
309    }
310
311    /// Which of agent86's tools to offer ([`Builtins::None`] when not set).
312    pub fn builtins(mut self, builtins: Builtins) -> Self {
313        self.builtins = builtins;
314        self
315    }
316
317    /// Offer `tool` too. A name already taken fails [`AgentBuilder::build`].
318    pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
319        self.tools.push(Box::new(tool));
320        self
321    }
322
323    /// The approval mode for side-effecting calls: `auto` runs them, `deny`
324    /// refuses them, and `ask` (the default) asks the [`AgentBuilder::approver`],
325    /// declining every one when there is none.
326    pub fn approval(mut self, mode: ApprovalMode) -> Self {
327        self.approval = mode;
328        self
329    }
330
331    /// Who is asked in `ask` mode: given the tool's name and what the call would do
332    /// (its arguments, and a diff for a file write), `true` lets it run. Called on
333    /// the turn's thread, one question at a time.
334    pub fn approver(
335        mut self,
336        approver: impl Fn(&str, &ApprovalPreview) -> bool + Send + Sync + 'static,
337    ) -> Self {
338        self.approver = Some(Box::new(approver));
339        self
340    }
341
342    /// Model calls one turn may make before it stops (40 by default).
343    pub fn max_steps(mut self, steps: u32) -> Self {
344        self.limits.max_steps = steps;
345        self
346    }
347
348    /// The spend, in US dollars, at which a turn stops; `0` for no cap (5 by
349    /// default). Only priced models count toward it.
350    pub fn max_cost_usd(mut self, usd: f64) -> Self {
351        self.limits.max_cost_usd = usd;
352        self
353    }
354
355    /// Seconds one turn may run; `0` for no limit (900 by default).
356    pub fn max_wall_clock_s(mut self, seconds: u64) -> Self {
357        self.limits.max_wall_clock_s = seconds;
358        self
359    }
360
361    /// Seconds a command or fetch may run (60 by default).
362    pub fn tool_timeout(mut self, timeout: Duration) -> Self {
363        self.tool_timeout = timeout;
364        self
365    }
366
367    /// The tokens of context the model holds, which history is fitted to.
368    pub fn context_window(mut self, tokens: u64) -> Self {
369        self.context_window = tokens;
370        self
371    }
372
373    /// The most tokens one model call may write (8192 by default).
374    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
375        self.max_output_tokens = tokens;
376        self
377    }
378
379    /// Ingress, egress, and observation scanning (agent86's defaults when not set:
380    /// warn, warn, on). Its `approval` is ignored; use [`AgentBuilder::approval`].
381    pub fn guardrails(mut self, guardrails: GuardrailsConfig) -> Self {
382        self.guardrails = guardrails;
383        self
384    }
385
386    /// Write the flight recorder's `trace.jsonl` in `dir`, redacted as the CLI's
387    /// is. Off when not set.
388    pub fn trace_dir(mut self, dir: impl Into<PathBuf>) -> Self {
389        self.trace_dir = Some(dir.into());
390        self
391    }
392
393    /// Start the MCP server `server` with the agent and offer its tools, named
394    /// `mcp__<name>__<tool>` and asked about unless the server marks them
395    /// read-only. A server that fails to start fails [`AgentBuilder::build`]; the
396    /// servers stop when the agent is dropped.
397    pub fn mcp_server(mut self, name: impl Into<String>, server: McpServer) -> Self {
398        self.mcp_servers.push((name.into(), server));
399        self
400    }
401
402    /// Give the agent long-term memory: the session is saved after every step and
403    /// at the end of each turn, finished turns are recalled into similar later
404    /// ones, and the model gets `remember` and `recall`. One [`Memory`] can be
405    /// shared by several agents.
406    pub fn memory(mut self, memory: Memory) -> Self {
407        self.memory = Some(memory);
408        self
409    }
410
411    /// Continue the session `id` from [`AgentBuilder::memory`] (any session saved
412    /// there, by this API, `agent86`, or Python's agent86).
413    pub fn session(mut self, id: impl Into<String>) -> Self {
414        self.session = Some(id.into());
415        self
416    }
417
418    /// Offer the skills in `dir`, a directory of `<name>/SKILL.md` folders, in
419    /// agent86's (and Claude Code's) skill format. The model sees their names and
420    /// descriptions and loads one with `use_skill`, whose `allowed-tools` then
421    /// limit it; [`Turn::skill`] runs one directly. The folders join the jail for
422    /// reading, since skills bundle files. Called again, an earlier directory wins a
423    /// name both hold.
424    pub fn skills_dir(mut self, dir: impl Into<PathBuf>) -> Self {
425        self.skill_dirs.push(dir.into());
426        self
427    }
428
429    /// A verification gate: when a turn that changed the workspace gives its final
430    /// answer, run `command` as a `run_command` call (under the approval mode, as
431    /// the model's own calls are) and send a failure back to the model, up to
432    /// `max_attempts` times, before the answer stands. [`RunResult::verification`]
433    /// says what it did.
434    pub fn verify(mut self, command: impl Into<String>, max_attempts: u32) -> Self {
435        self.verify = Some((command.into(), max_attempts));
436        self
437    }
438
439    /// Let the model delegate to sub-agents (see [`SubAgents`]).
440    pub fn subagents(mut self, subagents: SubAgents) -> Self {
441        self.subagents = Some(subagents);
442        self
443    }
444
445    /// Name a model, for a specialist whose definition says `model: <name>` and for
446    /// [`AgentBuilder::triage`]. A specialist naming a model that is not here runs
447    /// on the turn's model, with a notice.
448    pub fn model(mut self, name: impl Into<String>, model: Model) -> Self {
449        self.models.insert(name.into(), model);
450        self
451    }
452
453    /// Route each turn by its task, as agent86's `[model] router = "triage"` does:
454    /// a short, plain ask goes to the model named `cheap`, anything else to
455    /// `frontier` (both named with [`AgentBuilder::model`]); compaction summaries
456    /// use `cheap`. The [`AgentBuilder::provider`] is still required, and serves
457    /// nothing while routing is on.
458    pub fn triage(mut self, cheap: impl Into<String>, frontier: impl Into<String>) -> Self {
459        self.triage = Some((cheap.into(), frontier.into()));
460        self
461    }
462
463    /// Export OpenTelemetry spans: a `turn` span per turn, parent of a
464    /// `model_call` per model call and a `tool_call` per tool call, with the GenAI
465    /// attribute names agent86 uses. Exported on a worker thread, flushed at the end
466    /// of each turn and when the agent is dropped; a collector that cannot be
467    /// reached becomes a note ([`Agent::notes`]), never an error.
468    pub fn otel(mut self, otel: Otel) -> Self {
469        self.otel = Some(otel);
470        self
471    }
472
473    /// Asked when a turn reaches a limit (its step budget, a sub-agent's, or the
474    /// output cap before any text): given what was reached and the values offered,
475    /// return the new limit to go on with, or `None` to stop there as without this
476    /// callback. A raise lasts for the agent's life, or for one specialist's run
477    /// when [`LimitHit::run_only`] says so. Called on the turn's thread, one
478    /// question at a time with approvals.
479    pub fn on_limit(
480        mut self,
481        decide: impl Fn(&LimitHit) -> Option<u32> + Send + Sync + 'static,
482    ) -> Self {
483        self.on_limit = Some(Box::new(decide));
484        self
485    }
486
487    /// Offer the model `request_secret`, and ask `answer` when it is called: given
488    /// the variable's name and the model's reason, return the value (held for the
489    /// agent's life, at least 6 characters) or `None` to decline. Tools that run
490    /// commands get it as that environment variable, and every path back to the
491    /// model, the conversation, and the trace shows only `${secret:NAME}`. Names
492    /// that would change how programs run (`PATH`, `LD_PRELOAD`, ...) are refused
493    /// before `answer` is asked. Nothing is kept in a keyring.
494    pub fn on_secret_request(
495        mut self,
496        answer: impl Fn(&SecretRequest) -> Option<String> + Send + Sync + 'static,
497    ) -> Self {
498        self.on_secret = Some(Box::new(answer));
499        self
500    }
501
502    /// Declare a renderer (ADR 0005): offer the model `render_ui`, through which
503    /// it draws interactive UI as A2UI 1.0 messages in the renderer's catalogs.
504    /// Each validated message reaches [`Agent::run`]'s callback as
505    /// [`TurnEvent::Ui`], for the program to draw with its own widgets (Google's
506    /// React and Lit renderers take them as they are). The system prompt gains a
507    /// section with the catalogs' instructions and components on every request;
508    /// sub-agents never draw.
509    #[cfg(feature = "agent86ui")]
510    pub fn ui(mut self, ui: Ui) -> Self {
511        self.ui = Some(ui);
512        self
513    }
514
515    /// Hold a secret the program already has (an API token for a command the
516    /// agent will run), with the same rules as [`AgentBuilder::on_secret_request`]:
517    /// tools get it as the environment variable `name`, the model sees only
518    /// `${secret:NAME}`, and `write_file` and `edit_file` may put it in a file the
519    /// approver sees. `name` must be a valid variable name and the value at least 6
520    /// characters, or [`AgentBuilder::build`] fails.
521    pub fn secret(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
522        self.secrets.push((name.into(), value.into()));
523        self
524    }
525
526    /// Assemble the agent. Reads nothing but the workspace path, the memory
527    /// database, skill and specialist directories when given, and starts the MCP
528    /// servers given.
529    pub fn build(self) -> Result<Agent, BuildError> {
530        let router = self.router()?;
531        let provider = self.provider.ok_or(BuildError::MissingProvider)?;
532        let workspace = self.workspace.ok_or(BuildError::MissingWorkspace)?;
533        let mut context = ToolContext::new(&workspace).map_err(|error| BuildError::Workspace {
534            path: workspace.display().to_string(),
535            detail: error.to_string(),
536        })?;
537        context.policy.timeout = self.tool_timeout;
538        context.executor = Executor::Subprocess;
539        for (name, value) in &self.secrets {
540            let refused = |reason: &str| BuildError::Secret {
541                name: name.clone(),
542                reason: reason.to_owned(),
543            };
544            if !crate::vault::valid_name(name) {
545                return Err(refused("not a valid environment variable name"));
546            }
547            let answer = crate::vault::SecretAnswer {
548                value: value.clone(),
549                remember: false,
550            };
551            context.secrets.accept(name, answer).map_err(|_| {
552                refused(&format!(
553                    "shorter than {} characters",
554                    crate::vault::MIN_SECRET_CHARS
555                ))
556            })?;
557        }
558
559        let registry = registry_for(self.builtins);
560        // Beyond Python: the default prompt says where commands run, when they can.
561        let runs_commands = ["run_command", "python_exec"]
562            .iter()
563            .any(|name| registry.get(name).is_some());
564        for tool in self.tools {
565            registry.register(tool).map_err(BuildError::Tool)?;
566        }
567
568        let store = self.memory.as_ref().map(|memory| memory.store.clone());
569        let state = match (&self.session, &store) {
570            (None, _) => AgentState::new(),
571            (Some(_), None) => return Err(BuildError::SessionWithoutMemory),
572            (Some(id), Some(store)) => store
573                .load(id)
574                .map_err(|error| BuildError::Memory(error.0))?
575                .ok_or_else(|| BuildError::SessionNotFound(id.clone()))?,
576        };
577        if let Some(memory) = &self.memory {
578            let (episodes, sessions, days) = memory.retention;
579            store
580                .as_ref()
581                .expect("memory gives a store")
582                .enforce_retention(episodes, sessions, days)
583                .map_err(|error| BuildError::Memory(error.0))?;
584            for tool in [
585                Box::new(crate::tools::memory::RememberTool) as Box<dyn Tool>,
586                Box::new(crate::tools::memory::RecallTool),
587            ] {
588                registry.register(tool).map_err(BuildError::Tool)?;
589            }
590        }
591        context.memory = store.clone();
592
593        // Skills: only the directories named, highest precedence first, their
594        // folders readable through the jail.
595        let skills = Arc::new(crate::skills::discover_in(&self.skill_dirs));
596        if !skills.is_empty() {
597            context.policy.allow(
598                self.skill_dirs
599                    .iter()
600                    .filter(|dir| dir.is_dir())
601                    .filter_map(|dir| std::fs::canonicalize(dir).ok())
602                    .collect::<Vec<_>>(),
603            );
604            registry
605                .register(Box::new(crate::tools::skills::UseSkillTool))
606                .map_err(BuildError::Tool)?;
607        }
608        context.skills = Arc::clone(&skills);
609
610        // Sub-agents: `delegate`, and the specialists.
611        let config = builtin_config();
612        let mut agents = crate::config::AgentsConfig {
613            enabled: false,
614            ..config.agents.clone()
615        };
616        let mut notices = Vec::new();
617        if let Some(subagents) = &self.subagents {
618            agents = crate::config::AgentsConfig {
619                enabled: true,
620                max_depth: subagents.max_depth,
621                max_steps: subagents.max_steps.min(self.limits.max_steps.max(1)),
622                max_parallel: subagents
623                    .max_parallel
624                    .clamp(1, crate::config::MAX_PARALLEL_CEILING),
625            };
626            let mut specialties = if subagents.built_ins {
627                Specialties::built_in()
628            } else {
629                Specialties::default()
630            };
631            for dir in &subagents.dirs {
632                specialties.add_user_dir(dir);
633            }
634            notices.extend(specialties.notices.iter().cloned());
635            context.specialties = Arc::new(specialties);
636            registry
637                .register(Box::new(crate::tools::delegate::DelegateTool))
638                .map_err(BuildError::Tool)?;
639        }
640
641        let tracer = self
642            .otel
643            .as_ref()
644            .map(|otel| crate::otel::Tracer::to(otel.destination.clone()))
645            .unwrap_or_default();
646
647        if let Some(answer) = self.on_secret {
648            context
649                .secrets
650                .set_prompt(Some(Box::new(move |request: &SecretRequest| {
651                    answer(request).map(|value| crate::vault::SecretAnswer {
652                        value,
653                        remember: false,
654                    })
655                })));
656            registry
657                .register(Box::new(crate::tools::secret::RequestSecretTool))
658                .map_err(BuildError::Tool)?;
659        }
660        #[cfg(feature = "agent86ui")]
661        let mut ui_session = None;
662        #[cfg(feature = "agent86ui")]
663        if let Some(ui) = self.ui {
664            if ui.catalogs.is_empty() {
665                return Err(BuildError::Ui(
666                    "a renderer needs at least one catalog".into(),
667                ));
668            }
669            ui_session = Some(
670                crate::agent86ui::UiSession::new(ui.catalogs)
671                    .map_err(|error| BuildError::Ui(error.to_string()))?
672                    .with_egress(self.guardrails.egress)
673                    .with_remote_media(ui.remote_media)
674                    .with_waiter(ui.on_wait),
675            );
676        }
677        let mut session_limits = crate::limits::SessionLimits::default();
678        session_limits.prompt = self.on_limit;
679
680        let mcp = start_mcp(&self.mcp_servers, &registry)?;
681
682        let recorder = match &self.trace_dir {
683            None => Recorder::disabled(),
684            Some(dir) => {
685                std::fs::create_dir_all(dir)
686                    .map_err(|error| BuildError::Trace(error.to_string()))?;
687                let defaults = builtin_config().observability;
688                Recorder::from_config(&ObservabilityConfig {
689                    trace: true,
690                    path: dir.display().to_string(),
691                    otel: false,
692                    ..defaults
693                })
694            }
695        }
696        .with_secrets(context.secrets.clone());
697
698        let mut limits = self.limits;
699        limits.max_output_tokens = self.max_output_tokens;
700        let mut system = self.system.unwrap_or_else(|| default_system(runs_commands));
701        system.push_str(&crate::prompt::skills_section(
702            skills.values().map(AsRef::as_ref),
703        ));
704        let mut harness = Harness {
705            provider,
706            router,
707            tracer,
708            registry,
709            context,
710            limits,
711            agents,
712            system: Message {
713                role: Role::System,
714                content: system,
715                tool_calls: Vec::new(),
716                tool_call_id: None,
717                name: None,
718            },
719            max_tokens: self.max_output_tokens,
720            session_limits,
721            context_window: self.context_window,
722            gate: ApprovalGate::new(self.approval, self.approver),
723            guardrails: Guardrails::new(&self.guardrails),
724            recorder,
725            mcp,
726            memory: store,
727            cancel: Default::default(),
728            subagents: Default::default(),
729            calibration: Default::default(),
730            verify: match &self.verify {
731                Some((command, attempts)) => crate::verify::Verify::new(Some(command), *attempts),
732                None => Default::default(),
733            },
734        };
735        #[cfg(feature = "agent86ui")]
736        if let Some(session) = ui_session {
737            harness.attach_ui(session).map_err(BuildError::Tool)?;
738            // A renderer that answers waits answers `ask_user` too (ADR 0006).
739            harness
740                .offer_questions_as_forms()
741                .map_err(BuildError::Tool)?;
742        }
743        harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
744        harness.gate.queue.watch(harness.cancel.clone());
745        harness
746            .context
747            .secrets
748            .set_queue(harness.gate.queue.clone());
749        let agent = Agent {
750            harness,
751            conversation: Conversation(state),
752            notices,
753        };
754        // A resumed session's surfaces come back from its history.
755        #[cfg(feature = "agent86ui")]
756        agent.replay_surfaces();
757        Ok(agent)
758    }
759
760    /// The router for the named models: it builds nothing, it looks names up, so a
761    /// specialist's `model:` resolves with or without triage.
762    fn router(&self) -> Result<Router, BuildError> {
763        if self.models.is_empty() {
764            return match &self.triage {
765                Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
766                None => Ok(Router::default()),
767            };
768        }
769        let (triage, cheap, frontier) = match &self.triage {
770            Some((cheap, frontier)) => {
771                for name in [cheap, frontier] {
772                    if !self.models.contains_key(name) {
773                        return Err(BuildError::UnknownModel(name.clone()));
774                    }
775                }
776                (true, cheap.as_str(), frontier.as_str())
777            }
778            None => (false, "", ""),
779        };
780        let window = self.context_window;
781        let output = self.max_output_tokens;
782        let models: HashMap<String, RoutedModel> = self
783            .models
784            .iter()
785            .map(|(name, model)| {
786                (
787                    name.clone(),
788                    RoutedModel {
789                        reference: name.clone(),
790                        provider: Arc::clone(&model.provider),
791                        max_tokens: model.max_output_tokens.unwrap_or(output),
792                        context_window: model.context_window.unwrap_or(window),
793                        output_setting: "max_output_tokens".to_owned(),
794                    },
795                )
796            })
797            .collect();
798        Ok(Router::new(
799            triage,
800            cheap,
801            frontier,
802            Box::new(move |name| {
803                models
804                    .get(name)
805                    .cloned()
806                    .ok_or_else(|| format!("no model named '{name}'"))
807            }),
808        ))
809    }
810}
811
812/// Sub-agents for [`AgentBuilder::subagents`]: the model gets `delegate`, which
813/// runs a sub-agent on a task with its own step budget and a fork of the caller's
814/// tools, approvals, and jail. A *specialist* is a named sub-agent with its own
815/// instructions, tool allowlist, approval mode, model, and skills, defined in a
816/// Markdown file with frontmatter (agent86's `.agent86/agents/<name>.md` format;
817/// see `docs/subagents.md`). A specialist's authority only narrows its caller's.
818/// Adjacent specialist delegations run in parallel, each on its own thread, so a
819/// custom [`Provider`] must implement `fresh`; one with `isolation: worktree` runs
820/// in a git worktree and hands back its diff.
821#[derive(Debug, Clone)]
822pub struct SubAgents {
823    max_depth: u32,
824    max_steps: u32,
825    max_parallel: u32,
826    built_ins: bool,
827    dirs: Vec<PathBuf>,
828}
829
830impl Default for SubAgents {
831    fn default() -> Self {
832        let agents = builtin_config().agents;
833        Self {
834            max_depth: agents.max_depth,
835            max_steps: agents.max_steps,
836            max_parallel: agents.max_parallel,
837            built_ins: true,
838            dirs: Vec::new(),
839        }
840    }
841}
842
843impl SubAgents {
844    /// Delegation two levels deep, 8 steps per sub-agent, 3 in parallel, with
845    /// agent86's built-in specialists (`researcher`, `reviewer`, `planner`).
846    pub fn new() -> Self {
847        Self::default()
848    }
849
850    /// How deep delegation may nest; the main agent is depth 0.
851    pub fn max_depth(mut self, depth: u32) -> Self {
852        self.max_depth = depth;
853        self
854    }
855
856    /// Each sub-agent's step budget, kept at or below the turn's.
857    pub fn max_steps(mut self, steps: u32) -> Self {
858        self.max_steps = steps;
859        self
860    }
861
862    /// How many adjacent specialist delegations run at once (1 to 8).
863    pub fn max_parallel(mut self, parallel: u32) -> Self {
864        self.max_parallel = parallel;
865        self
866    }
867
868    /// Leave out agent86's built-in specialists.
869    pub fn without_built_ins(mut self) -> Self {
870        self.built_ins = false;
871        self
872    }
873
874    /// Add the specialists defined in `dir` (`<name>.md` files), replacing a
875    /// built-in or an earlier directory's of the same name. They are trusted as
876    /// the caller's own, so never pass a directory from a repository the user did
877    /// not write: its files become prompt text and tool scopes. A file that does
878    /// not parse is skipped, and said so in [`Agent::notes`].
879    pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
880        self.dirs.push(dir.into());
881        self
882    }
883}
884
885/// A model for [`AgentBuilder::model`].
886#[derive(Clone)]
887pub struct Model {
888    provider: Arc<dyn Provider>,
889    context_window: Option<u64>,
890    max_output_tokens: Option<u32>,
891}
892
893impl std::fmt::Debug for Model {
894    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
895        f.debug_struct("Model")
896            .field("provider", &self.provider.name())
897            .field("model", &self.provider.model())
898            .field("context_window", &self.context_window)
899            .field("max_output_tokens", &self.max_output_tokens)
900            .finish()
901    }
902}
903
904impl Model {
905    /// `provider`, with the agent's context window and output cap unless set.
906    pub fn new(provider: Arc<dyn Provider>) -> Self {
907        Self {
908            provider,
909            context_window: None,
910            max_output_tokens: None,
911        }
912    }
913
914    /// The tokens of context this model holds.
915    pub fn context_window(mut self, tokens: u64) -> Self {
916        self.context_window = Some(tokens);
917        self
918    }
919
920    /// The most tokens one call to this model may write.
921    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
922        self.max_output_tokens = Some(tokens);
923        self
924    }
925}
926
927/// A renderer for agent86UI ([`AgentBuilder::ui`]): the A2UI catalogs it
928/// draws, in order of preference.
929#[cfg(feature = "agent86ui")]
930#[derive(Clone)]
931pub struct Ui {
932    catalogs: Vec<Catalog>,
933    remote_media: bool,
934    on_wait: Option<crate::agent86ui::UiWaiter>,
935}
936
937#[cfg(feature = "agent86ui")]
938impl std::fmt::Debug for Ui {
939    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
940        f.debug_struct("Ui")
941            .field(
942                "catalogs",
943                &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
944            )
945            .field("remote_media", &self.remote_media)
946            .field("on_wait", &self.on_wait.is_some())
947            .finish()
948    }
949}
950
951#[cfg(feature = "agent86ui")]
952impl Ui {
953    /// A renderer for the specification's basic catalog, which Google's
954    /// renderers implement.
955    pub fn basic() -> Self {
956        Self::new([Catalog::basic().clone()])
957    }
958
959    /// A renderer for `catalogs` (load one with [`Catalog::from_value`]), in
960    /// order of preference.
961    pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
962        Self {
963            catalogs: catalogs.into_iter().collect(),
964            remote_media: false,
965            on_wait: None,
966        }
967    }
968
969    /// Let the model wait for the user's answer (`render_ui` with `wait`), for
970    /// a form in the middle of a task: once the call's [`TurnEvent::Ui`]
971    /// messages are out, `answer` is asked for the first [`Action`] the user
972    /// takes on one of [`UiWait::surface_ids`], or `None` when they dismiss it.
973    /// Called on the turn's thread, one question at a time with approvals, and
974    /// never once the turn is cancelled. The action's context becomes the call's
975    /// result, through the vault and the ingress guardrail as typed input does.
976    /// Without it, a waiting call is refused and the model asks without waiting.
977    pub fn on_wait(
978        mut self,
979        answer: impl Fn(&UiWait) -> Option<Action> + Send + Sync + 'static,
980    ) -> Self {
981        self.on_wait = Some(std::sync::Arc::new(answer));
982        self
983    }
984
985    /// Let `Image`, `Video`, and `AudioPlayer` load `https` URLs. Off by
986    /// default: a surface's media is then a `data:` URL or a file in the
987    /// workspace (a path relative to it, which the program serves), since a
988    /// fetch can track the user or carry data out in its URL.
989    pub fn allow_remote_media(mut self) -> Self {
990        self.remote_media = true;
991        self
992    }
993
994    /// The catalogs, in order of preference.
995    pub fn catalogs(&self) -> &[Catalog] {
996        &self.catalogs
997    }
998}
999
1000/// Where [`AgentBuilder::otel`] sends spans. OTLP is HTTP with JSON bodies.
1001#[derive(Debug, Clone)]
1002pub struct Otel {
1003    destination: crate::otel::Destination,
1004}
1005
1006impl Otel {
1007    /// An OTLP/HTTP collector's traces endpoint, such as
1008    /// `http://localhost:4318/v1/traces`, with a 10-second timeout.
1009    pub fn otlp(traces_url: impl Into<String>) -> Self {
1010        Self {
1011            destination: crate::otel::Destination::Otlp {
1012                url: traces_url.into(),
1013                headers: Vec::new(),
1014                timeout: Duration::from_secs(10),
1015            },
1016        }
1017    }
1018
1019    /// Each span as one line of JSON on stderr.
1020    pub fn console() -> Self {
1021        Self {
1022            destination: crate::otel::Destination::Console,
1023        }
1024    }
1025
1026    /// Send `name: value` with every export (an API key, for a hosted collector).
1027    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1028        if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
1029            headers.push((name.into(), value.into()));
1030        }
1031        self
1032    }
1033
1034    /// How long one export may take.
1035    pub fn timeout(mut self, timeout: Duration) -> Self {
1036        if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
1037            *limit = timeout;
1038        }
1039        self
1040    }
1041}
1042
1043/// Start `servers` on a manager attached to `registry`, failing on the first that
1044/// does not start or whose tools collide; dropping the manager stops the rest.
1045fn start_mcp(
1046    servers: &[(String, McpServer)],
1047    registry: &ToolRegistry,
1048) -> Result<Option<Arc<McpManager>>, BuildError> {
1049    if servers.is_empty() {
1050        return Ok(None);
1051    }
1052    let manager = Arc::new(McpManager::empty(&builtin_config()));
1053    manager.attach(registry);
1054    let mut seen: Vec<&str> = Vec::new();
1055    for (name, server) in servers {
1056        let failed = |reason: String| BuildError::Mcp {
1057            name: name.clone(),
1058            reason,
1059        };
1060        if seen.contains(&name.as_str()) {
1061            return Err(failed("another server was given the same name".to_owned()));
1062        }
1063        seen.push(name);
1064        let mut config = server.config.clone();
1065        config.resolve_transport().map_err(failed)?;
1066        manager
1067            .start_server(
1068                name,
1069                &config,
1070                &server.literal_refs(),
1071                &NoSecretStore,
1072                config.connect_timeout_s,
1073            )
1074            .map_err(failed)?;
1075        let (_, collisions) = manager.mount(name);
1076        if !collisions.is_empty() {
1077            return Err(BuildError::Tool(format!(
1078                "MCP server '{name}' offers tools already taken: {}",
1079                collisions.join(", ")
1080            )));
1081        }
1082    }
1083    Ok(Some(manager))
1084}
1085
1086/// An MCP server for [`AgentBuilder::mcp_server`]. Every value (arguments,
1087/// environment, URL, headers) is used exactly as given: a `${VAR}` in one is
1088/// never expanded from the process's environment or the keyring, as it would be
1089/// in a config file, so pass resolved values.
1090#[derive(Debug, Clone)]
1091pub struct McpServer {
1092    config: McpServerConfig,
1093}
1094
1095impl McpServer {
1096    fn from(value: Value) -> Self {
1097        Self {
1098            config: serde_json::from_value(value).expect("a server config always deserializes"),
1099        }
1100    }
1101
1102    /// A server agent86 starts as `command` with `args`, speaking MCP on its
1103    /// standard streams. It gets agent86's scrubbed environment plus
1104    /// [`McpServer::env`], never the whole of this process's.
1105    pub fn stdio<S: Into<String>>(
1106        command: impl Into<String>,
1107        args: impl IntoIterator<Item = S>,
1108    ) -> Self {
1109        let args: Vec<String> = args.into_iter().map(Into::into).collect();
1110        Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
1111    }
1112
1113    /// A server at `url` over streamable HTTP.
1114    pub fn http(url: impl Into<String>) -> Self {
1115        Self::from(json!({"url": url.into(), "transport": "http"}))
1116    }
1117
1118    /// A server at `url` over the older SSE transport.
1119    pub fn sse(url: impl Into<String>) -> Self {
1120        Self::from(json!({"url": url.into(), "transport": "sse"}))
1121    }
1122
1123    /// Set an environment variable for a stdio server.
1124    pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1125        self.config.env.insert(name.into(), value.into());
1126        self
1127    }
1128
1129    /// Send a header with every request to a remote server.
1130    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1131        self.config.headers.insert(name.into(), value.into());
1132        self
1133    }
1134
1135    /// How long the server has to start and list its tools (30 seconds by default).
1136    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
1137        self.config.connect_timeout_s = timeout.as_secs_f64();
1138        self
1139    }
1140
1141    /// How long one tool call may take (120 seconds by default).
1142    pub fn call_timeout(mut self, timeout: Duration) -> Self {
1143        self.config.call_timeout_s = timeout.as_secs_f64();
1144        self
1145    }
1146
1147    /// The most characters of a result the model is shown (8000 by default).
1148    pub fn max_result_chars(mut self, chars: usize) -> Self {
1149        self.config.max_result_chars = chars;
1150        self
1151    }
1152
1153    /// Every `${VAR}` in the values mapped to itself, so the manager's expansion
1154    /// leaves it as written (overrides win over the environment and the keyring).
1155    fn literal_refs(&self) -> HashMap<String, String> {
1156        let config = &self.config;
1157        config
1158            .args
1159            .iter()
1160            .chain(config.env.values())
1161            .chain(config.url.iter())
1162            .chain(config.headers.values())
1163            .flat_map(|text| var_ref_names(text))
1164            .map(|name| (name.clone(), format!("${{{name}}}")))
1165            .collect()
1166    }
1167}
1168
1169/// Long-term memory for [`AgentBuilder::memory`]: agent86's SQLite memory
1170/// database (the same file and schema the CLI uses, so its sessions and facts are
1171/// shared), opened once and cheap to clone.
1172#[derive(Clone)]
1173pub struct Memory {
1174    store: SessionStore,
1175    retention: (i64, i64, f64),
1176}
1177
1178impl std::fmt::Debug for Memory {
1179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1180        f.debug_struct("Memory")
1181            .field("retention", &self.retention)
1182            .finish_non_exhaustive()
1183    }
1184}
1185
1186impl Memory {
1187    /// Open (creating if needed) the database at `path`, embedding with the
1188    /// offline hashing embedder (`hash:256`), which needs no model download.
1189    pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1190        Self::wrap(SessionStore::open(path.as_ref()))
1191    }
1192
1193    /// [`Memory::open`] with another embedder, such as the sentence-transformers
1194    /// model `crate::memory::embeddings::build_embedder` loads. Episodes and facts
1195    /// written with one embedder are only found again with the same one.
1196    pub fn open_with(
1197        path: impl AsRef<Path>,
1198        embedder: Arc<dyn Embedder>,
1199    ) -> Result<Self, BuildError> {
1200        Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
1201    }
1202
1203    /// A database that lives only as long as this value and its clones.
1204    pub fn in_memory() -> Result<Self, BuildError> {
1205        Self::open(":memory:")
1206    }
1207
1208    fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
1209        let memory = builtin_config().memory;
1210        Ok(Self {
1211            store: store.map_err(|error| BuildError::Memory(error.0))?,
1212            retention: (
1213                memory.retention_max_episodes,
1214                memory.retention_max_sessions,
1215                memory.retention_max_age_days,
1216            ),
1217        })
1218    }
1219
1220    /// Keep at most `episodes` episodes and `sessions` sessions, and none older
1221    /// than `max_age_days` (`0` for no age limit), pruned when an agent is built
1222    /// (1000, 500, and no age limit by default). Pinned entries are kept.
1223    pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
1224        self.retention = (episodes, sessions, max_age_days);
1225        self
1226    }
1227
1228    /// The sessions saved here, newest first: (id, title).
1229    pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
1230        Ok(self
1231            .store
1232            .recent_sessions(limit)
1233            .map_err(|error| BuildError::Memory(error.0))?
1234            .into_iter()
1235            .map(|session| (session.session_id, session.title))
1236            .collect())
1237    }
1238
1239    /// The store underneath, for what this type does not cover yet (facts,
1240    /// episodes, pins). Its API makes no stability promise.
1241    pub fn store(&self) -> &SessionStore {
1242        &self.store
1243    }
1244}
1245
1246fn registry_for(builtins: Builtins) -> ToolRegistry {
1247    let registry = ToolRegistry::new();
1248    let mut tools: Vec<Box<dyn Tool>> = Vec::new();
1249    if builtins != Builtins::None {
1250        tools.push(Box::new(files::ReadFileTool));
1251        tools.push(Box::new(files::ListDirTool));
1252        tools.push(Box::new(search::SearchFilesTool));
1253        tools.push(Box::new(search::FindFilesTool));
1254    }
1255    if matches!(builtins, Builtins::Files | Builtins::All) {
1256        tools.push(Box::new(files::WriteFileTool));
1257        tools.push(Box::new(files::EditFileTool));
1258    }
1259    if builtins == Builtins::All {
1260        tools.push(Box::new(exec::RunCommandTool));
1261        tools.push(Box::new(exec::PythonExecTool));
1262        tools.push(Box::new(web::WebFetchTool));
1263    }
1264    for tool in tools {
1265        registry
1266            .register(tool)
1267            .expect("built-in tool names are unique");
1268    }
1269    registry
1270}
1271
1272/// What one [`Agent::run`] produced.
1273///
1274/// `#[non_exhaustive]` (since 1.2.0): later releases may add fields, so code
1275/// outside this crate reads the fields it needs and cannot build one or
1276/// destructure it without `..`.
1277#[derive(Debug, Clone, PartialEq)]
1278#[non_exhaustive]
1279pub struct RunResult {
1280    /// The turn's answer: the model's last message when it made no tool call,
1281    /// otherwise empty (a turn stopped by a limit or a cancel).
1282    pub answer: String,
1283    /// Everything the turn streamed, notices and `[tool] ...` lines included, as
1284    /// `agent86 run --output full` prints it.
1285    pub output: String,
1286    /// The turn's tokens, cost, steps, and tool calls.
1287    pub turn: Option<TurnSummary>,
1288    /// The conversation's usage so far.
1289    pub usage: Usage,
1290    /// What the verification gate did this turn, when one is set
1291    /// ([`AgentBuilder::verify`]).
1292    pub verification: Option<Verification>,
1293}
1294
1295/// One turn for [`Agent::run`]: a goal (a `&str` or `String` converts to one),
1296/// a skill run directly, or a specialist run directly.
1297#[derive(Debug, Clone, PartialEq, Eq)]
1298pub enum Turn {
1299    /// The model works toward the goal with every tool it is offered.
1300    Goal(String),
1301    /// The skill's instructions lead the user's message and the skill is active
1302    /// from the first step, so its `allowed-tools` apply at once.
1303    Skill { name: String, task: String },
1304    /// The specialist runs the task as a sub-agent at depth 1, and the exchange is
1305    /// kept as an ordinary user and assistant message. With `with_context`, the
1306    /// conversation so far is summarized and handed over.
1307    Specialist {
1308        name: String,
1309        task: String,
1310        with_context: bool,
1311    },
1312}
1313
1314impl Turn {
1315    pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
1316        Self::Skill {
1317            name: name.into(),
1318            task: task.into(),
1319        }
1320    }
1321
1322    pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
1323        Self::Specialist {
1324            name: name.into(),
1325            task: task.into(),
1326            with_context: false,
1327        }
1328    }
1329
1330    /// For a [`Turn::Specialist`], hand over a summary of the conversation so far.
1331    pub fn with_context(mut self) -> Self {
1332        if let Self::Specialist { with_context, .. } = &mut self {
1333            *with_context = true;
1334        }
1335        self
1336    }
1337}
1338
1339impl From<&str> for Turn {
1340    fn from(goal: &str) -> Self {
1341        Self::Goal(goal.to_owned())
1342    }
1343}
1344
1345impl From<String> for Turn {
1346    fn from(goal: String) -> Self {
1347        Self::Goal(goal)
1348    }
1349}
1350
1351impl From<&String> for Turn {
1352    fn from(goal: &String) -> Self {
1353        Self::Goal(goal.clone())
1354    }
1355}
1356
1357/// An agent: a harness and its conversation. Each [`Agent::run`] is one turn
1358/// that continues the conversation.
1359pub struct Agent {
1360    harness: Harness,
1361    conversation: Conversation,
1362    /// What building found worth saying (a specialist file skipped).
1363    notices: Vec<String>,
1364}
1365
1366impl Agent {
1367    pub fn builder() -> AgentBuilder {
1368        AgentBuilder::default()
1369    }
1370
1371    /// Run one turn: a goal, or a [`Turn`].
1372    pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1373        self.run_with_events(turn, |_| {}).await
1374    }
1375
1376    /// [`Agent::run`], reporting each [`TurnEvent`] (text, reasoning, tool calls
1377    /// and their results, usage) as it happens.
1378    pub async fn run_with_events(
1379        &mut self,
1380        turn: impl Into<Turn>,
1381        on_event: impl FnMut(TurnEvent<'_>),
1382    ) -> Result<RunResult, RunError> {
1383        let (kind, prompt, display) = match turn.into() {
1384            Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
1385            Turn::Skill { name, task } => {
1386                let skill = self
1387                    .harness
1388                    .context
1389                    .skills
1390                    .get(&name)
1391                    .cloned()
1392                    .ok_or(RunError::UnknownSkill(name.clone()))?;
1393                let display = format!("/{name} {task}").trim_end().to_owned();
1394                (TurnKind::Skill(skill), task, display)
1395            }
1396            Turn::Specialist {
1397                name,
1398                task,
1399                with_context,
1400            } => {
1401                if !self.harness.agents.enabled
1402                    || self.harness.context.specialties.get(&name).is_none()
1403                {
1404                    return Err(RunError::UnknownSpecialist(name));
1405                }
1406                let display = format!("/agent {name} {task}");
1407                (TurnKind::Agent { name, with_context }, task, display)
1408            }
1409        };
1410        self.run_kind(kind, &prompt, &display, on_event).await
1411    }
1412
1413    /// Whether [`Agent::continue_turn`] can continue the conversation's last turn:
1414    /// it stopped before it finished (a provider failure, a tripped limit, a
1415    /// cancel, or a process that ended mid-turn, for a conversation saved with
1416    /// [`Conversation::to_json`] or in [`Memory`]), nothing was added since, and the
1417    /// skill it ran under is still there.
1418    pub fn can_continue(&self) -> bool {
1419        self.harness.continuable(&self.conversation.0).is_ok()
1420    }
1421
1422    /// Continue the conversation's unfinished last turn from its last step, with
1423    /// no new message. The turn's step count, cost, and tool-error streak carry
1424    /// over, so a limit it tripped trips again unless it was raised (with
1425    /// [`AgentBuilder::on_limit`], or a larger budget when the agent is built
1426    /// again). Every side-effecting call goes through the approval gate again,
1427    /// and the model is told that time has passed, so it checks before relying on
1428    /// what it saw. [`RunError::NotContinuable`] says why when there is nothing to
1429    /// continue, without calling the model.
1430    pub async fn continue_turn(&mut self) -> Result<RunResult, RunError> {
1431        self.continue_turn_with_events(|_| {}).await
1432    }
1433
1434    /// [`Agent::continue_turn`], reporting each [`TurnEvent`] as it happens.
1435    pub async fn continue_turn_with_events(
1436        &mut self,
1437        on_event: impl FnMut(TurnEvent<'_>),
1438    ) -> Result<RunResult, RunError> {
1439        let continuation = self
1440            .harness
1441            .continuable(&self.conversation.0)
1442            .map_err(|refusal| RunError::NotContinuable(refusal.0))?;
1443        self.run_kind(TurnKind::Continue(Box::new(continuation)), "", "", on_event)
1444            .await
1445    }
1446
1447    /// Run a turn of `kind` and save the conversation, whatever came of it.
1448    async fn run_kind(
1449        &mut self,
1450        kind: TurnKind,
1451        prompt: &str,
1452        display: &str,
1453        mut on_event: impl FnMut(TurnEvent<'_>),
1454    ) -> Result<RunResult, RunError> {
1455        let output = self
1456            .harness
1457            .run_kind(
1458                &mut self.conversation.0,
1459                &kind,
1460                prompt,
1461                display,
1462                &mut on_event,
1463            )
1464            .await;
1465        // Saved after a failed turn too, as the CLI does; a failed write loses this
1466        // save, never the turn (the harness saved after every step already).
1467        if let Some(store) = &self.harness.memory {
1468            let _ = store.persist(&self.conversation.0);
1469        }
1470        let output = output?;
1471        Ok(RunResult {
1472            answer: final_answer(&self.conversation.0.messages).to_owned(),
1473            output,
1474            turn: self.conversation.0.last_turn.clone(),
1475            usage: self.conversation.0.usage,
1476            verification: self.harness.verify.last(),
1477        })
1478    }
1479
1480    /// Hand the model what the user did on a surface (a button pressed), when no
1481    /// `render_ui` call was waiting for it: it becomes the next user message,
1482    /// `[ui action] <name> on <surfaceId>: <context as JSON>` (plus the event's
1483    /// `userMessage` on its own line), and runs a turn as [`Agent::run`] does,
1484    /// through the vault and the ingress guardrail like typed input. Recorded as
1485    /// `ui_action`, without its values. Call it after the turn that drew the
1486    /// surface has ended; actions taken during a turn wait for it, as typed
1487    /// input does.
1488    #[cfg(feature = "agent86ui")]
1489    pub async fn ui_action(&mut self, action: Action) -> Result<RunResult, RunError> {
1490        self.ui_action_with_events(action, |_| {}).await
1491    }
1492
1493    /// [`Agent::ui_action`], reporting each [`TurnEvent`] as it happens.
1494    #[cfg(feature = "agent86ui")]
1495    pub async fn ui_action_with_events(
1496        &mut self,
1497        action: Action,
1498        on_event: impl FnMut(TurnEvent<'_>),
1499    ) -> Result<RunResult, RunError> {
1500        let text = self
1501            .harness
1502            .accept_ui_action(&self.conversation.0.session_id, &action)
1503            .map_err(RunError::UiAction)?;
1504        self.run_with_events(Turn::Goal(text), on_event).await
1505    }
1506
1507    /// A handle that stops the running turn at its next safe point (before a model
1508    /// call, while streaming, or between tool calls), from any thread.
1509    pub fn cancel_handle(&self) -> CancelToken {
1510        self.harness.cancel.clone()
1511    }
1512
1513    /// The conversation so far, to read or to save with [`Conversation::to_json`].
1514    pub fn conversation(&self) -> &Conversation {
1515        &self.conversation
1516    }
1517
1518    /// Continue an earlier conversation instead of starting a new one.
1519    /// With agent86UI, the surfaces are rebuilt from its `render_ui` calls, as
1520    /// on resuming a session; [`Agent::surfaces`] gives them to draw.
1521    pub fn with_conversation(mut self, conversation: Conversation) -> Self {
1522        self.conversation = conversation;
1523        #[cfg(feature = "agent86ui")]
1524        self.replay_surfaces();
1525        self
1526    }
1527
1528    /// Rebuild the renderer's surfaces from the conversation's history.
1529    #[cfg(feature = "agent86ui")]
1530    fn replay_surfaces(&self) {
1531        if let Some(ui) = &self.harness.context.ui {
1532            ui.replay(&self.conversation.0, &self.harness.context);
1533        }
1534    }
1535
1536    /// Every surface up now, each as the one `createSurface` message that draws
1537    /// it as it is (its components and data model), in surface id order. After
1538    /// resuming a session ([`AgentBuilder::session`] or
1539    /// [`Agent::with_conversation`]) the surfaces are rebuilt from the
1540    /// history's `render_ui` calls, so a program that reopens draws these to
1541    /// show the user where they were. What the user typed but never submitted is
1542    /// the renderer's alone, so it is not here. Empty without a renderer.
1543    #[cfg(feature = "agent86ui")]
1544    pub fn surfaces(&self) -> Vec<AgentMessage> {
1545        self.harness
1546            .context
1547            .ui
1548            .as_ref()
1549            .map(|ui| ui.snapshot())
1550            .unwrap_or_default()
1551    }
1552
1553    /// The session's id, under which [`AgentBuilder::memory`] saves it.
1554    pub fn session_id(&self) -> &str {
1555        self.conversation.id()
1556    }
1557
1558    /// The names of the secrets held, never their values.
1559    pub fn secret_names(&self) -> Vec<String> {
1560        self.harness.context.secrets.names()
1561    }
1562
1563    /// What is worth telling the user, oldest first: specialist files that were
1564    /// skipped, what the MCP servers reported (a server that dropped, reconnected,
1565    /// or changed its tools), and why spans could not be exported.
1566    pub fn notes(&self) -> Vec<String> {
1567        let mut notes = self.notices.clone();
1568        if let Some(mcp) = &self.harness.mcp {
1569            notes.extend(mcp.notes());
1570        }
1571        notes.extend(self.harness.tracer.note());
1572        notes
1573    }
1574
1575    /// The skills [`Turn::skill`] can run, in precedence order.
1576    pub fn skills(&self) -> Vec<String> {
1577        self.harness.context.skills.keys().cloned().collect()
1578    }
1579
1580    /// The specialists [`Turn::specialist`] and `delegate` can run.
1581    pub fn specialists(&self) -> Vec<String> {
1582        if !self.harness.agents.enabled {
1583            return Vec::new();
1584        }
1585        self.harness
1586            .context
1587            .specialties
1588            .names()
1589            .into_iter()
1590            .map(str::to_owned)
1591            .collect()
1592    }
1593
1594    /// The names of the tools the model is offered.
1595    pub fn tool_names(&self) -> Vec<String> {
1596        self.harness.registry.names()
1597    }
1598
1599    /// The harness underneath, for what this module does not cover yet. Its API
1600    /// makes no stability promise.
1601    pub fn harness(&self) -> &Harness {
1602        &self.harness
1603    }
1604}
1605
1606/// A conversation: its messages, steps, and usage. It is saved as the JSON the
1607/// session database keeps (`state_json`, the format agent86 and Python's agent86
1608/// share), so a saved conversation opens in either.
1609/// [`Conversation::default`] is a new conversation with a fresh id.
1610#[derive(Debug, Clone, Default, PartialEq)]
1611pub struct Conversation(AgentState);
1612
1613/// One message of a [`Conversation`].
1614#[derive(Debug, Clone, PartialEq)]
1615pub struct ConversationMessage {
1616    pub role: Role,
1617    /// The text: the user's words, the model's reply, or a tool's result.
1618    pub text: String,
1619    /// The tools an assistant message called.
1620    pub tool_calls: Vec<ToolCall>,
1621    /// For a tool's result, the id of the call it answers.
1622    pub answers: Option<String>,
1623}
1624
1625impl Conversation {
1626    /// A new, empty conversation with a fresh id.
1627    pub fn new() -> Self {
1628        Self::default()
1629    }
1630
1631    /// Its id, which the session database files it under.
1632    pub fn id(&self) -> &str {
1633        &self.0.session_id
1634    }
1635
1636    /// Its messages, oldest first (the system prompt is not one of them).
1637    pub fn messages(&self) -> Vec<ConversationMessage> {
1638        self.0
1639            .messages
1640            .iter()
1641            .map(|message| ConversationMessage {
1642                role: message.role,
1643                text: message.content.clone(),
1644                tool_calls: message.tool_calls.clone(),
1645                answers: message.tool_call_id.clone(),
1646            })
1647            .collect()
1648    }
1649
1650    /// The model calls made so far.
1651    pub fn steps(&self) -> usize {
1652        self.0.step_count()
1653    }
1654
1655    /// The tokens and cost so far.
1656    pub fn usage(&self) -> Usage {
1657        self.0.usage
1658    }
1659
1660    /// The last turn's summary, or `None` before the first.
1661    pub fn last_turn(&self) -> Option<&TurnSummary> {
1662        self.0.last_turn.as_ref()
1663    }
1664
1665    /// The conversation as the session database's JSON.
1666    pub fn to_json(&self) -> String {
1667        serde_json::to_string(&self.0).expect("a conversation always serializes")
1668    }
1669
1670    /// A conversation from [`Conversation::to_json`]'s JSON, or a session
1671    /// database's `state_json`.
1672    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1673        serde_json::from_str(json).map(Self)
1674    }
1675}
1676
1677/// The function behind an [`FnTool`]: given the validated-as-JSON arguments and
1678/// the tool context (its workspace jail, `ctx.policy.resolve_within`), the text
1679/// the model sees, or an error message.
1680type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1681
1682/// A tool from a closure, for the common case where implementing [`Tool`] is more
1683/// than needed. Read-only unless [`FnTool::side_effecting`] says otherwise.
1684pub struct FnTool {
1685    name: String,
1686    description: String,
1687    parameters: Value,
1688    side_effecting: bool,
1689    run: Box<ToolFn>,
1690}
1691
1692impl FnTool {
1693    /// A tool named `name` (letters, digits, `_`, `-`), described to the model by
1694    /// `description`, taking arguments matching the JSON Schema `parameters`.
1695    pub fn new(
1696        name: impl Into<String>,
1697        description: impl Into<String>,
1698        parameters: Value,
1699        run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
1700            + Send
1701            + Sync
1702            + 'static,
1703    ) -> Self {
1704        Self {
1705            name: name.into(),
1706            description: description.into(),
1707            parameters,
1708            side_effecting: false,
1709            run: Box::new(run),
1710        }
1711    }
1712
1713    /// Mark the tool as having effects outside the conversation, so every call goes
1714    /// through the approval gate.
1715    pub fn side_effecting(mut self) -> Self {
1716        self.side_effecting = true;
1717        self
1718    }
1719}
1720
1721impl Tool for FnTool {
1722    fn name(&self) -> &str {
1723        &self.name
1724    }
1725
1726    fn description(&self) -> &str {
1727        &self.description
1728    }
1729
1730    fn side_effecting(&self) -> bool {
1731        self.side_effecting
1732    }
1733
1734    fn parameters(&self) -> Value {
1735        self.parameters.clone()
1736    }
1737
1738    fn execute(
1739        &self,
1740        args: &Map<String, Value>,
1741        ctx: &ToolContext,
1742    ) -> Result<ToolResult, ToolError> {
1743        match (self.run)(args, ctx) {
1744            Ok(content) => Ok(ToolResult {
1745                call_id: String::new(),
1746                name: self.name.clone(),
1747                ok: true,
1748                content,
1749                error: None,
1750                metadata: Map::new(),
1751            }),
1752            Err(message) => Err(ToolError::Raised {
1753                exception: "ToolError".to_owned(),
1754                message,
1755            }),
1756        }
1757    }
1758}
1759
1760/// The model layer: the [`Provider`] trait, which only needs `stream`, the types
1761/// a provider speaks, and agent86's own adapters, which run any OpenAI-compatible
1762/// endpoint (OpenAI, OpenRouter, Groq, vLLM, LM Studio, llama.cpp), Anthropic,
1763/// Ollama, and Google Gemini, with agent86's retries, redaction, and pricing.
1764pub mod providers {
1765    pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
1766    pub use crate::provider::google::{GoogleConfig, GoogleProvider};
1767    pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
1768    pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
1769    pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
1770    pub use crate::types::{
1771        Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
1772    };
1773}