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        if let Some(ui) = self.ui {
624            if ui.catalogs.is_empty() {
625                return Err(BuildError::Ui(
626                    "a renderer needs at least one catalog".into(),
627                ));
628            }
629            let session = crate::agent86ui::UiSession::new(ui.catalogs)
630                .map_err(|error| BuildError::Ui(error.to_string()))?
631                .with_egress(self.guardrails.egress)
632                .with_remote_media(ui.remote_media)
633                .with_waiter(ui.on_wait);
634            context.ui = Some(Arc::new(session));
635            registry
636                .register(Box::new(crate::tools::render_ui::RenderUiTool))
637                .map_err(BuildError::Tool)?;
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        harness.context.can_delegate = harness.delegation_offered(&harness.context, 0);
695        harness.gate.queue.watch(harness.cancel.clone());
696        harness
697            .context
698            .secrets
699            .set_queue(harness.gate.queue.clone());
700        let agent = Agent {
701            harness,
702            conversation: Conversation(state),
703            notices,
704        };
705        // A resumed session's surfaces come back from its history.
706        #[cfg(feature = "agent86ui")]
707        agent.replay_surfaces();
708        Ok(agent)
709    }
710
711    /// The router for the named models: it builds nothing, it looks names up, so a
712    /// specialist's `model:` resolves with or without triage.
713    fn router(&self) -> Result<Router, BuildError> {
714        if self.models.is_empty() {
715            return match &self.triage {
716                Some((cheap, _)) => Err(BuildError::UnknownModel(cheap.clone())),
717                None => Ok(Router::default()),
718            };
719        }
720        let (triage, cheap, frontier) = match &self.triage {
721            Some((cheap, frontier)) => {
722                for name in [cheap, frontier] {
723                    if !self.models.contains_key(name) {
724                        return Err(BuildError::UnknownModel(name.clone()));
725                    }
726                }
727                (true, cheap.as_str(), frontier.as_str())
728            }
729            None => (false, "", ""),
730        };
731        let window = self.context_window;
732        let output = self.max_output_tokens;
733        let models: HashMap<String, RoutedModel> = self
734            .models
735            .iter()
736            .map(|(name, model)| {
737                (
738                    name.clone(),
739                    RoutedModel {
740                        reference: name.clone(),
741                        provider: Arc::clone(&model.provider),
742                        max_tokens: model.max_output_tokens.unwrap_or(output),
743                        context_window: model.context_window.unwrap_or(window),
744                        output_setting: "max_output_tokens".to_owned(),
745                    },
746                )
747            })
748            .collect();
749        Ok(Router::new(
750            triage,
751            cheap,
752            frontier,
753            Box::new(move |name| {
754                models
755                    .get(name)
756                    .cloned()
757                    .ok_or_else(|| format!("no model named '{name}'"))
758            }),
759        ))
760    }
761}
762
763/// Sub-agents for [`AgentBuilder::subagents`]: the model gets `delegate`, which
764/// runs a sub-agent on a task with its own step budget and a fork of the caller's
765/// tools, approvals, and jail. A *specialist* is a named sub-agent with its own
766/// instructions, tool allowlist, approval mode, model, and skills, defined in a
767/// Markdown file with frontmatter (agent86's `.agent86/agents/<name>.md` format;
768/// see `docs/subagents.md`). A specialist's authority only narrows its caller's.
769/// Adjacent specialist delegations run in parallel, each on its own thread, so a
770/// custom [`Provider`] must implement `fresh`; one with `isolation: worktree` runs
771/// in a git worktree and hands back its diff.
772#[derive(Debug, Clone)]
773pub struct SubAgents {
774    max_depth: u32,
775    max_steps: u32,
776    max_parallel: u32,
777    built_ins: bool,
778    dirs: Vec<PathBuf>,
779}
780
781impl Default for SubAgents {
782    fn default() -> Self {
783        let agents = builtin_config().agents;
784        Self {
785            max_depth: agents.max_depth,
786            max_steps: agents.max_steps,
787            max_parallel: agents.max_parallel,
788            built_ins: true,
789            dirs: Vec::new(),
790        }
791    }
792}
793
794impl SubAgents {
795    /// Delegation two levels deep, 8 steps per sub-agent, 3 in parallel, with
796    /// agent86's built-in specialists (`researcher`, `reviewer`, `planner`).
797    pub fn new() -> Self {
798        Self::default()
799    }
800
801    /// How deep delegation may nest; the main agent is depth 0.
802    pub fn max_depth(mut self, depth: u32) -> Self {
803        self.max_depth = depth;
804        self
805    }
806
807    /// Each sub-agent's step budget, kept at or below the turn's.
808    pub fn max_steps(mut self, steps: u32) -> Self {
809        self.max_steps = steps;
810        self
811    }
812
813    /// How many adjacent specialist delegations run at once (1 to 8).
814    pub fn max_parallel(mut self, parallel: u32) -> Self {
815        self.max_parallel = parallel;
816        self
817    }
818
819    /// Leave out agent86's built-in specialists.
820    pub fn without_built_ins(mut self) -> Self {
821        self.built_ins = false;
822        self
823    }
824
825    /// Add the specialists defined in `dir` (`<name>.md` files), replacing a
826    /// built-in or an earlier directory's of the same name. They are trusted as
827    /// the caller's own, so never pass a directory from a repository the user did
828    /// not write: its files become prompt text and tool scopes. A file that does
829    /// not parse is skipped, and said so in [`Agent::notes`].
830    pub fn specialists_dir(mut self, dir: impl Into<PathBuf>) -> Self {
831        self.dirs.push(dir.into());
832        self
833    }
834}
835
836/// A model for [`AgentBuilder::model`].
837#[derive(Clone)]
838pub struct Model {
839    provider: Arc<dyn Provider>,
840    context_window: Option<u64>,
841    max_output_tokens: Option<u32>,
842}
843
844impl std::fmt::Debug for Model {
845    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
846        f.debug_struct("Model")
847            .field("provider", &self.provider.name())
848            .field("model", &self.provider.model())
849            .field("context_window", &self.context_window)
850            .field("max_output_tokens", &self.max_output_tokens)
851            .finish()
852    }
853}
854
855impl Model {
856    /// `provider`, with the agent's context window and output cap unless set.
857    pub fn new(provider: Arc<dyn Provider>) -> Self {
858        Self {
859            provider,
860            context_window: None,
861            max_output_tokens: None,
862        }
863    }
864
865    /// The tokens of context this model holds.
866    pub fn context_window(mut self, tokens: u64) -> Self {
867        self.context_window = Some(tokens);
868        self
869    }
870
871    /// The most tokens one call to this model may write.
872    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
873        self.max_output_tokens = Some(tokens);
874        self
875    }
876}
877
878/// A renderer for agent86UI ([`AgentBuilder::ui`]): the A2UI catalogs it
879/// draws, in order of preference.
880#[cfg(feature = "agent86ui")]
881#[derive(Clone)]
882pub struct Ui {
883    catalogs: Vec<Catalog>,
884    remote_media: bool,
885    on_wait: Option<crate::agent86ui::UiWaiter>,
886}
887
888#[cfg(feature = "agent86ui")]
889impl std::fmt::Debug for Ui {
890    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
891        f.debug_struct("Ui")
892            .field(
893                "catalogs",
894                &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
895            )
896            .field("remote_media", &self.remote_media)
897            .field("on_wait", &self.on_wait.is_some())
898            .finish()
899    }
900}
901
902#[cfg(feature = "agent86ui")]
903impl Ui {
904    /// A renderer for the specification's basic catalog, which Google's
905    /// renderers implement.
906    pub fn basic() -> Self {
907        Self::new([Catalog::basic().clone()])
908    }
909
910    /// A renderer for `catalogs` (load one with [`Catalog::from_value`]), in
911    /// order of preference.
912    pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
913        Self {
914            catalogs: catalogs.into_iter().collect(),
915            remote_media: false,
916            on_wait: None,
917        }
918    }
919
920    /// Let the model wait for the user's answer (`render_ui` with `wait`), for
921    /// a form in the middle of a task: once the call's [`TurnEvent::Ui`]
922    /// messages are out, `answer` is asked for the first [`Action`] the user
923    /// takes on one of [`UiWait::surface_ids`], or `None` when they dismiss it.
924    /// Called on the turn's thread, one question at a time with approvals, and
925    /// never once the turn is cancelled. The action's context becomes the call's
926    /// result, through the vault and the ingress guardrail as typed input does.
927    /// Without it, a waiting call is refused and the model asks without waiting.
928    pub fn on_wait(
929        mut self,
930        answer: impl Fn(&UiWait) -> Option<Action> + Send + Sync + 'static,
931    ) -> Self {
932        self.on_wait = Some(std::sync::Arc::new(answer));
933        self
934    }
935
936    /// Let `Image`, `Video`, and `AudioPlayer` load `https` URLs. Off by
937    /// default: a surface's media is then a `data:` URL or a file in the
938    /// workspace (a path relative to it, which the program serves), since a
939    /// fetch can track the user or carry data out in its URL.
940    pub fn allow_remote_media(mut self) -> Self {
941        self.remote_media = true;
942        self
943    }
944
945    /// The catalogs, in order of preference.
946    pub fn catalogs(&self) -> &[Catalog] {
947        &self.catalogs
948    }
949}
950
951/// Where [`AgentBuilder::otel`] sends spans. OTLP is HTTP with JSON bodies.
952#[derive(Debug, Clone)]
953pub struct Otel {
954    destination: crate::otel::Destination,
955}
956
957impl Otel {
958    /// An OTLP/HTTP collector's traces endpoint, such as
959    /// `http://localhost:4318/v1/traces`, with a 10-second timeout.
960    pub fn otlp(traces_url: impl Into<String>) -> Self {
961        Self {
962            destination: crate::otel::Destination::Otlp {
963                url: traces_url.into(),
964                headers: Vec::new(),
965                timeout: Duration::from_secs(10),
966            },
967        }
968    }
969
970    /// Each span as one line of JSON on stderr.
971    pub fn console() -> Self {
972        Self {
973            destination: crate::otel::Destination::Console,
974        }
975    }
976
977    /// Send `name: value` with every export (an API key, for a hosted collector).
978    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
979        if let crate::otel::Destination::Otlp { headers, .. } = &mut self.destination {
980            headers.push((name.into(), value.into()));
981        }
982        self
983    }
984
985    /// How long one export may take.
986    pub fn timeout(mut self, timeout: Duration) -> Self {
987        if let crate::otel::Destination::Otlp { timeout: limit, .. } = &mut self.destination {
988            *limit = timeout;
989        }
990        self
991    }
992}
993
994/// Start `servers` on a manager attached to `registry`, failing on the first that
995/// does not start or whose tools collide; dropping the manager stops the rest.
996fn start_mcp(
997    servers: &[(String, McpServer)],
998    registry: &ToolRegistry,
999) -> Result<Option<Arc<McpManager>>, BuildError> {
1000    if servers.is_empty() {
1001        return Ok(None);
1002    }
1003    let manager = Arc::new(McpManager::empty(&builtin_config()));
1004    manager.attach(registry);
1005    let mut seen: Vec<&str> = Vec::new();
1006    for (name, server) in servers {
1007        let failed = |reason: String| BuildError::Mcp {
1008            name: name.clone(),
1009            reason,
1010        };
1011        if seen.contains(&name.as_str()) {
1012            return Err(failed("another server was given the same name".to_owned()));
1013        }
1014        seen.push(name);
1015        let mut config = server.config.clone();
1016        config.resolve_transport().map_err(failed)?;
1017        manager
1018            .start_server(
1019                name,
1020                &config,
1021                &server.literal_refs(),
1022                &NoSecretStore,
1023                config.connect_timeout_s,
1024            )
1025            .map_err(failed)?;
1026        let (_, collisions) = manager.mount(name);
1027        if !collisions.is_empty() {
1028            return Err(BuildError::Tool(format!(
1029                "MCP server '{name}' offers tools already taken: {}",
1030                collisions.join(", ")
1031            )));
1032        }
1033    }
1034    Ok(Some(manager))
1035}
1036
1037/// An MCP server for [`AgentBuilder::mcp_server`]. Every value (arguments,
1038/// environment, URL, headers) is used exactly as given: a `${VAR}` in one is
1039/// never expanded from the process's environment or the keyring, as it would be
1040/// in a config file, so pass resolved values.
1041#[derive(Debug, Clone)]
1042pub struct McpServer {
1043    config: McpServerConfig,
1044}
1045
1046impl McpServer {
1047    fn from(value: Value) -> Self {
1048        Self {
1049            config: serde_json::from_value(value).expect("a server config always deserializes"),
1050        }
1051    }
1052
1053    /// A server agent86 starts as `command` with `args`, speaking MCP on its
1054    /// standard streams. It gets agent86's scrubbed environment plus
1055    /// [`McpServer::env`], never the whole of this process's.
1056    pub fn stdio<S: Into<String>>(
1057        command: impl Into<String>,
1058        args: impl IntoIterator<Item = S>,
1059    ) -> Self {
1060        let args: Vec<String> = args.into_iter().map(Into::into).collect();
1061        Self::from(json!({"command": command.into(), "args": args, "transport": "stdio"}))
1062    }
1063
1064    /// A server at `url` over streamable HTTP.
1065    pub fn http(url: impl Into<String>) -> Self {
1066        Self::from(json!({"url": url.into(), "transport": "http"}))
1067    }
1068
1069    /// A server at `url` over the older SSE transport.
1070    pub fn sse(url: impl Into<String>) -> Self {
1071        Self::from(json!({"url": url.into(), "transport": "sse"}))
1072    }
1073
1074    /// Set an environment variable for a stdio server.
1075    pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1076        self.config.env.insert(name.into(), value.into());
1077        self
1078    }
1079
1080    /// Send a header with every request to a remote server.
1081    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1082        self.config.headers.insert(name.into(), value.into());
1083        self
1084    }
1085
1086    /// How long the server has to start and list its tools (30 seconds by default).
1087    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
1088        self.config.connect_timeout_s = timeout.as_secs_f64();
1089        self
1090    }
1091
1092    /// How long one tool call may take (120 seconds by default).
1093    pub fn call_timeout(mut self, timeout: Duration) -> Self {
1094        self.config.call_timeout_s = timeout.as_secs_f64();
1095        self
1096    }
1097
1098    /// The most characters of a result the model is shown (8000 by default).
1099    pub fn max_result_chars(mut self, chars: usize) -> Self {
1100        self.config.max_result_chars = chars;
1101        self
1102    }
1103
1104    /// Every `${VAR}` in the values mapped to itself, so the manager's expansion
1105    /// leaves it as written (overrides win over the environment and the keyring).
1106    fn literal_refs(&self) -> HashMap<String, String> {
1107        let config = &self.config;
1108        config
1109            .args
1110            .iter()
1111            .chain(config.env.values())
1112            .chain(config.url.iter())
1113            .chain(config.headers.values())
1114            .flat_map(|text| var_ref_names(text))
1115            .map(|name| (name.clone(), format!("${{{name}}}")))
1116            .collect()
1117    }
1118}
1119
1120/// Long-term memory for [`AgentBuilder::memory`]: agent86's SQLite memory
1121/// database (the same file and schema the CLI uses, so its sessions and facts are
1122/// shared), opened once and cheap to clone.
1123#[derive(Clone)]
1124pub struct Memory {
1125    store: SessionStore,
1126    retention: (i64, i64, f64),
1127}
1128
1129impl std::fmt::Debug for Memory {
1130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1131        f.debug_struct("Memory")
1132            .field("retention", &self.retention)
1133            .finish_non_exhaustive()
1134    }
1135}
1136
1137impl Memory {
1138    /// Open (creating if needed) the database at `path`, embedding with the
1139    /// offline hashing embedder (`hash:256`), which needs no model download.
1140    pub fn open(path: impl AsRef<Path>) -> Result<Self, BuildError> {
1141        Self::wrap(SessionStore::open(path.as_ref()))
1142    }
1143
1144    /// [`Memory::open`] with another embedder, such as the sentence-transformers
1145    /// model `crate::memory::embeddings::build_embedder` loads. Episodes and facts
1146    /// written with one embedder are only found again with the same one.
1147    pub fn open_with(
1148        path: impl AsRef<Path>,
1149        embedder: Arc<dyn Embedder>,
1150    ) -> Result<Self, BuildError> {
1151        Self::wrap(SessionStore::open_with(path.as_ref(), embedder))
1152    }
1153
1154    /// A database that lives only as long as this value and its clones.
1155    pub fn in_memory() -> Result<Self, BuildError> {
1156        Self::open(":memory:")
1157    }
1158
1159    fn wrap(store: Result<SessionStore, crate::session::StoreError>) -> Result<Self, BuildError> {
1160        let memory = builtin_config().memory;
1161        Ok(Self {
1162            store: store.map_err(|error| BuildError::Memory(error.0))?,
1163            retention: (
1164                memory.retention_max_episodes,
1165                memory.retention_max_sessions,
1166                memory.retention_max_age_days,
1167            ),
1168        })
1169    }
1170
1171    /// Keep at most `episodes` episodes and `sessions` sessions, and none older
1172    /// than `max_age_days` (`0` for no age limit), pruned when an agent is built
1173    /// (1000, 500, and no age limit by default). Pinned entries are kept.
1174    pub fn retention(mut self, episodes: i64, sessions: i64, max_age_days: f64) -> Self {
1175        self.retention = (episodes, sessions, max_age_days);
1176        self
1177    }
1178
1179    /// The sessions saved here, newest first: (id, title).
1180    pub fn sessions(&self, limit: usize) -> Result<Vec<(String, Option<String>)>, BuildError> {
1181        Ok(self
1182            .store
1183            .recent_sessions(limit)
1184            .map_err(|error| BuildError::Memory(error.0))?
1185            .into_iter()
1186            .map(|session| (session.session_id, session.title))
1187            .collect())
1188    }
1189
1190    /// The store underneath, for what this type does not cover yet (facts,
1191    /// episodes, pins). Its API makes no stability promise.
1192    pub fn store(&self) -> &SessionStore {
1193        &self.store
1194    }
1195}
1196
1197fn registry_for(builtins: Builtins) -> ToolRegistry {
1198    let registry = ToolRegistry::new();
1199    let mut tools: Vec<Box<dyn Tool>> = Vec::new();
1200    if builtins != Builtins::None {
1201        tools.push(Box::new(files::ReadFileTool));
1202        tools.push(Box::new(files::ListDirTool));
1203        tools.push(Box::new(search::SearchFilesTool));
1204        tools.push(Box::new(search::FindFilesTool));
1205    }
1206    if matches!(builtins, Builtins::Files | Builtins::All) {
1207        tools.push(Box::new(files::WriteFileTool));
1208        tools.push(Box::new(files::EditFileTool));
1209    }
1210    if builtins == Builtins::All {
1211        tools.push(Box::new(exec::RunCommandTool));
1212        tools.push(Box::new(exec::PythonExecTool));
1213        tools.push(Box::new(web::WebFetchTool));
1214    }
1215    for tool in tools {
1216        registry
1217            .register(tool)
1218            .expect("built-in tool names are unique");
1219    }
1220    registry
1221}
1222
1223/// What one [`Agent::run`] produced.
1224///
1225/// `#[non_exhaustive]` (since 1.2.0): later releases may add fields, so code
1226/// outside this crate reads the fields it needs and cannot build one or
1227/// destructure it without `..`.
1228#[derive(Debug, Clone, PartialEq)]
1229#[non_exhaustive]
1230pub struct RunResult {
1231    /// The turn's answer: the model's last message when it made no tool call,
1232    /// otherwise empty (a turn stopped by a limit or a cancel).
1233    pub answer: String,
1234    /// Everything the turn streamed, notices and `[tool] ...` lines included, as
1235    /// `agent86 run --output full` prints it.
1236    pub output: String,
1237    /// The turn's tokens, cost, steps, and tool calls.
1238    pub turn: Option<TurnSummary>,
1239    /// The conversation's usage so far.
1240    pub usage: Usage,
1241}
1242
1243/// One turn for [`Agent::run`]: a goal (a `&str` or `String` converts to one),
1244/// a skill run directly, or a specialist run directly.
1245#[derive(Debug, Clone, PartialEq, Eq)]
1246pub enum Turn {
1247    /// The model works toward the goal with every tool it is offered.
1248    Goal(String),
1249    /// The skill's instructions lead the user's message and the skill is active
1250    /// from the first step, so its `allowed-tools` apply at once.
1251    Skill { name: String, task: String },
1252    /// The specialist runs the task as a sub-agent at depth 1, and the exchange is
1253    /// kept as an ordinary user and assistant message. With `with_context`, the
1254    /// conversation so far is summarized and handed over.
1255    Specialist {
1256        name: String,
1257        task: String,
1258        with_context: bool,
1259    },
1260}
1261
1262impl Turn {
1263    pub fn skill(name: impl Into<String>, task: impl Into<String>) -> Self {
1264        Self::Skill {
1265            name: name.into(),
1266            task: task.into(),
1267        }
1268    }
1269
1270    pub fn specialist(name: impl Into<String>, task: impl Into<String>) -> Self {
1271        Self::Specialist {
1272            name: name.into(),
1273            task: task.into(),
1274            with_context: false,
1275        }
1276    }
1277
1278    /// For a [`Turn::Specialist`], hand over a summary of the conversation so far.
1279    pub fn with_context(mut self) -> Self {
1280        if let Self::Specialist { with_context, .. } = &mut self {
1281            *with_context = true;
1282        }
1283        self
1284    }
1285}
1286
1287impl From<&str> for Turn {
1288    fn from(goal: &str) -> Self {
1289        Self::Goal(goal.to_owned())
1290    }
1291}
1292
1293impl From<String> for Turn {
1294    fn from(goal: String) -> Self {
1295        Self::Goal(goal)
1296    }
1297}
1298
1299impl From<&String> for Turn {
1300    fn from(goal: &String) -> Self {
1301        Self::Goal(goal.clone())
1302    }
1303}
1304
1305/// An agent: a harness and its conversation. Each [`Agent::run`] is one turn
1306/// that continues the conversation.
1307pub struct Agent {
1308    harness: Harness,
1309    conversation: Conversation,
1310    /// What building found worth saying (a specialist file skipped).
1311    notices: Vec<String>,
1312}
1313
1314impl Agent {
1315    pub fn builder() -> AgentBuilder {
1316        AgentBuilder::default()
1317    }
1318
1319    /// Run one turn: a goal, or a [`Turn`].
1320    pub async fn run(&mut self, turn: impl Into<Turn>) -> Result<RunResult, RunError> {
1321        self.run_with_events(turn, |_| {}).await
1322    }
1323
1324    /// [`Agent::run`], reporting each [`TurnEvent`] (text, reasoning, tool calls
1325    /// and their results, usage) as it happens.
1326    pub async fn run_with_events(
1327        &mut self,
1328        turn: impl Into<Turn>,
1329        mut on_event: impl FnMut(TurnEvent<'_>),
1330    ) -> Result<RunResult, RunError> {
1331        let (kind, prompt, display) = match turn.into() {
1332            Turn::Goal(goal) => (TurnKind::Plain, goal.clone(), goal),
1333            Turn::Skill { name, task } => {
1334                let skill = self
1335                    .harness
1336                    .context
1337                    .skills
1338                    .get(&name)
1339                    .cloned()
1340                    .ok_or(RunError::UnknownSkill(name.clone()))?;
1341                let display = format!("/{name} {task}").trim_end().to_owned();
1342                (TurnKind::Skill(skill), task, display)
1343            }
1344            Turn::Specialist {
1345                name,
1346                task,
1347                with_context,
1348            } => {
1349                if !self.harness.agents.enabled
1350                    || self.harness.context.specialties.get(&name).is_none()
1351                {
1352                    return Err(RunError::UnknownSpecialist(name));
1353                }
1354                let display = format!("/agent {name} {task}");
1355                (TurnKind::Agent { name, with_context }, task, display)
1356            }
1357        };
1358        let output = self
1359            .harness
1360            .run_kind(
1361                &mut self.conversation.0,
1362                &kind,
1363                &prompt,
1364                &display,
1365                &mut on_event,
1366            )
1367            .await;
1368        // Saved after a failed turn too, as the CLI does; a failed write loses this
1369        // save, never the turn (the harness saved after every step already).
1370        if let Some(store) = &self.harness.memory {
1371            let _ = store.persist(&self.conversation.0);
1372        }
1373        let output = output?;
1374        Ok(RunResult {
1375            answer: final_answer(&self.conversation.0.messages).to_owned(),
1376            output,
1377            turn: self.conversation.0.last_turn.clone(),
1378            usage: self.conversation.0.usage,
1379        })
1380    }
1381
1382    /// Hand the model what the user did on a surface (a button pressed), when no
1383    /// `render_ui` call was waiting for it: it becomes the next user message,
1384    /// `[ui action] <name> on <surfaceId>: <context as JSON>` (plus the event's
1385    /// `userMessage` on its own line), and runs a turn as [`Agent::run`] does,
1386    /// through the vault and the ingress guardrail like typed input. Recorded as
1387    /// `ui_action`, without its values. Call it after the turn that drew the
1388    /// surface has ended; actions taken during a turn wait for it, as typed
1389    /// input does.
1390    #[cfg(feature = "agent86ui")]
1391    pub async fn ui_action(&mut self, action: Action) -> Result<RunResult, RunError> {
1392        self.ui_action_with_events(action, |_| {}).await
1393    }
1394
1395    /// [`Agent::ui_action`], reporting each [`TurnEvent`] as it happens.
1396    #[cfg(feature = "agent86ui")]
1397    pub async fn ui_action_with_events(
1398        &mut self,
1399        action: Action,
1400        on_event: impl FnMut(TurnEvent<'_>),
1401    ) -> Result<RunResult, RunError> {
1402        let ui = self
1403            .harness
1404            .context
1405            .ui
1406            .clone()
1407            .ok_or_else(|| RunError::UiAction("this agent has no renderer".into()))?;
1408        ui.check_action(&action, None).map_err(RunError::UiAction)?;
1409        self.harness.recorder.event(
1410            &self.conversation.0.session_id,
1411            "ui_action",
1412            vec![
1413                ("surface", json!(action.surface_id)),
1414                ("name", json!(action.name)),
1415                ("component", json!(action.source_component_id)),
1416                ("waited", json!(false)),
1417            ],
1418        );
1419        let text = crate::agent86ui::action_text(&action);
1420        self.run_with_events(Turn::Goal(text), on_event).await
1421    }
1422
1423    /// A handle that stops the running turn at its next safe point (before a model
1424    /// call, while streaming, or between tool calls), from any thread.
1425    pub fn cancel_handle(&self) -> CancelToken {
1426        self.harness.cancel.clone()
1427    }
1428
1429    /// The conversation so far, to read or to save with [`Conversation::to_json`].
1430    pub fn conversation(&self) -> &Conversation {
1431        &self.conversation
1432    }
1433
1434    /// Continue an earlier conversation instead of starting a new one.
1435    /// With agent86UI, the surfaces are rebuilt from its `render_ui` calls, as
1436    /// on resuming a session; [`Agent::surfaces`] gives them to draw.
1437    pub fn with_conversation(mut self, conversation: Conversation) -> Self {
1438        self.conversation = conversation;
1439        #[cfg(feature = "agent86ui")]
1440        self.replay_surfaces();
1441        self
1442    }
1443
1444    /// Rebuild the renderer's surfaces from the conversation's history.
1445    #[cfg(feature = "agent86ui")]
1446    fn replay_surfaces(&self) {
1447        if let Some(ui) = &self.harness.context.ui {
1448            ui.replay(&self.conversation.0, &self.harness.context);
1449        }
1450    }
1451
1452    /// Every surface up now, each as the one `createSurface` message that draws
1453    /// it as it is (its components and data model), in surface id order. After
1454    /// resuming a session ([`AgentBuilder::session`] or
1455    /// [`Agent::with_conversation`]) the surfaces are rebuilt from the
1456    /// history's `render_ui` calls, so a program that reopens draws these to
1457    /// show the user where they were. What the user typed but never submitted is
1458    /// the renderer's alone, so it is not here. Empty without a renderer.
1459    #[cfg(feature = "agent86ui")]
1460    pub fn surfaces(&self) -> Vec<AgentMessage> {
1461        self.harness
1462            .context
1463            .ui
1464            .as_ref()
1465            .map(|ui| ui.snapshot())
1466            .unwrap_or_default()
1467    }
1468
1469    /// The session's id, under which [`AgentBuilder::memory`] saves it.
1470    pub fn session_id(&self) -> &str {
1471        self.conversation.id()
1472    }
1473
1474    /// The names of the secrets held, never their values.
1475    pub fn secret_names(&self) -> Vec<String> {
1476        self.harness.context.secrets.names()
1477    }
1478
1479    /// What is worth telling the user, oldest first: specialist files that were
1480    /// skipped, what the MCP servers reported (a server that dropped, reconnected,
1481    /// or changed its tools), and why spans could not be exported.
1482    pub fn notes(&self) -> Vec<String> {
1483        let mut notes = self.notices.clone();
1484        if let Some(mcp) = &self.harness.mcp {
1485            notes.extend(mcp.notes());
1486        }
1487        notes.extend(self.harness.tracer.note());
1488        notes
1489    }
1490
1491    /// The skills [`Turn::skill`] can run, in precedence order.
1492    pub fn skills(&self) -> Vec<String> {
1493        self.harness.context.skills.keys().cloned().collect()
1494    }
1495
1496    /// The specialists [`Turn::specialist`] and `delegate` can run.
1497    pub fn specialists(&self) -> Vec<String> {
1498        if !self.harness.agents.enabled {
1499            return Vec::new();
1500        }
1501        self.harness
1502            .context
1503            .specialties
1504            .names()
1505            .into_iter()
1506            .map(str::to_owned)
1507            .collect()
1508    }
1509
1510    /// The names of the tools the model is offered.
1511    pub fn tool_names(&self) -> Vec<String> {
1512        self.harness.registry.names()
1513    }
1514
1515    /// The harness underneath, for what this module does not cover yet. Its API
1516    /// makes no stability promise.
1517    pub fn harness(&self) -> &Harness {
1518        &self.harness
1519    }
1520}
1521
1522/// A conversation: its messages, steps, and usage. It is saved as the JSON the
1523/// session database keeps (`state_json`, the format agent86 and Python's agent86
1524/// share), so a saved conversation opens in either.
1525/// [`Conversation::default`] is a new conversation with a fresh id.
1526#[derive(Debug, Clone, Default, PartialEq)]
1527pub struct Conversation(AgentState);
1528
1529/// One message of a [`Conversation`].
1530#[derive(Debug, Clone, PartialEq)]
1531pub struct ConversationMessage {
1532    pub role: Role,
1533    /// The text: the user's words, the model's reply, or a tool's result.
1534    pub text: String,
1535    /// The tools an assistant message called.
1536    pub tool_calls: Vec<ToolCall>,
1537    /// For a tool's result, the id of the call it answers.
1538    pub answers: Option<String>,
1539}
1540
1541impl Conversation {
1542    /// A new, empty conversation with a fresh id.
1543    pub fn new() -> Self {
1544        Self::default()
1545    }
1546
1547    /// Its id, which the session database files it under.
1548    pub fn id(&self) -> &str {
1549        &self.0.session_id
1550    }
1551
1552    /// Its messages, oldest first (the system prompt is not one of them).
1553    pub fn messages(&self) -> Vec<ConversationMessage> {
1554        self.0
1555            .messages
1556            .iter()
1557            .map(|message| ConversationMessage {
1558                role: message.role,
1559                text: message.content.clone(),
1560                tool_calls: message.tool_calls.clone(),
1561                answers: message.tool_call_id.clone(),
1562            })
1563            .collect()
1564    }
1565
1566    /// The model calls made so far.
1567    pub fn steps(&self) -> usize {
1568        self.0.step_count()
1569    }
1570
1571    /// The tokens and cost so far.
1572    pub fn usage(&self) -> Usage {
1573        self.0.usage
1574    }
1575
1576    /// The last turn's summary, or `None` before the first.
1577    pub fn last_turn(&self) -> Option<&TurnSummary> {
1578        self.0.last_turn.as_ref()
1579    }
1580
1581    /// The conversation as the session database's JSON.
1582    pub fn to_json(&self) -> String {
1583        serde_json::to_string(&self.0).expect("a conversation always serializes")
1584    }
1585
1586    /// A conversation from [`Conversation::to_json`]'s JSON, or a session
1587    /// database's `state_json`.
1588    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
1589        serde_json::from_str(json).map(Self)
1590    }
1591}
1592
1593/// The function behind an [`FnTool`]: given the validated-as-JSON arguments and
1594/// the tool context (its workspace jail, `ctx.policy.resolve_within`), the text
1595/// the model sees, or an error message.
1596type ToolFn = dyn Fn(&Map<String, Value>, &ToolContext) -> Result<String, String> + Send + Sync;
1597
1598/// A tool from a closure, for the common case where implementing [`Tool`] is more
1599/// than needed. Read-only unless [`FnTool::side_effecting`] says otherwise.
1600pub struct FnTool {
1601    name: String,
1602    description: String,
1603    parameters: Value,
1604    side_effecting: bool,
1605    run: Box<ToolFn>,
1606}
1607
1608impl FnTool {
1609    /// A tool named `name` (letters, digits, `_`, `-`), described to the model by
1610    /// `description`, taking arguments matching the JSON Schema `parameters`.
1611    pub fn new(
1612        name: impl Into<String>,
1613        description: impl Into<String>,
1614        parameters: Value,
1615        run: impl Fn(&Map<String, Value>, &ToolContext) -> Result<String, String>
1616            + Send
1617            + Sync
1618            + 'static,
1619    ) -> Self {
1620        Self {
1621            name: name.into(),
1622            description: description.into(),
1623            parameters,
1624            side_effecting: false,
1625            run: Box::new(run),
1626        }
1627    }
1628
1629    /// Mark the tool as having effects outside the conversation, so every call goes
1630    /// through the approval gate.
1631    pub fn side_effecting(mut self) -> Self {
1632        self.side_effecting = true;
1633        self
1634    }
1635}
1636
1637impl Tool for FnTool {
1638    fn name(&self) -> &str {
1639        &self.name
1640    }
1641
1642    fn description(&self) -> &str {
1643        &self.description
1644    }
1645
1646    fn side_effecting(&self) -> bool {
1647        self.side_effecting
1648    }
1649
1650    fn parameters(&self) -> Value {
1651        self.parameters.clone()
1652    }
1653
1654    fn execute(
1655        &self,
1656        args: &Map<String, Value>,
1657        ctx: &ToolContext,
1658    ) -> Result<ToolResult, ToolError> {
1659        match (self.run)(args, ctx) {
1660            Ok(content) => Ok(ToolResult {
1661                call_id: String::new(),
1662                name: self.name.clone(),
1663                ok: true,
1664                content,
1665                error: None,
1666                metadata: Map::new(),
1667            }),
1668            Err(message) => Err(ToolError::Raised {
1669                exception: "ToolError".to_owned(),
1670                message,
1671            }),
1672        }
1673    }
1674}
1675
1676/// The model layer: the [`Provider`] trait, which only needs `stream`, the types
1677/// a provider speaks, and agent86's own adapters, which run any OpenAI-compatible
1678/// endpoint (OpenAI, OpenRouter, Groq, vLLM, LM Studio, llama.cpp), Anthropic,
1679/// Ollama, and Google Gemini, with agent86's retries, redaction, and pricing.
1680pub mod providers {
1681    pub use crate::provider::anthropic::{AnthropicConfig, AnthropicProvider};
1682    pub use crate::provider::google::{GoogleConfig, GoogleProvider};
1683    pub use crate::provider::ollama::{OllamaConfig, OllamaProvider};
1684    pub use crate::provider::openai::{OpenAiConfig, OpenAiProvider};
1685    pub use crate::provider::{collect_completion, DeltaStream, Provider, ProviderError};
1686    pub use crate::types::{
1687        Completion, CompletionDelta, CompletionRequest, Message, StopReason, ToolSpec,
1688    };
1689}