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