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