Skip to main content

sim_lib_agent/
lib.rs

1//! Agent runtime surfaces for SIM: agents, tools, memory, patterns, fixtures,
2//! fairness facets, and model-fabric contract re-exports.
3//!
4//! Model placement is resolved through the `model/at` catalog. In-process
5//! runners and registry `site` exports share that catalog: a loaded native or
6//! wasm library can register an opaque site value under a placement symbol, and
7//! this crate adapts that value into an `EvalSite` without adding site behavior
8//! to the kernel. `model/cached` wraps placements in a content-addressed
9//! cassette, so successful inference replies are replayable by normalized
10//! request content, model identity, parameters, result shape, and capabilities.
11
12#![forbid(unsafe_code)]
13#![deny(missing_docs)]
14#![allow(deprecated)]
15
16mod agents;
17pub mod atelier;
18mod capabilities;
19mod cli;
20mod components;
21mod config_probe;
22#[cfg(feature = "cookbook")]
23mod cookbook_tools;
24mod core_tools;
25mod embed;
26mod fairness;
27mod functions;
28mod memory;
29mod model_privacy;
30mod multimodal;
31mod pattern;
32mod planning;
33mod reply;
34mod roles;
35mod runner_projection;
36/// Cookbook recipes for this lib, embedded at build time.
37pub static RECIPES: sim_cookbook::EmbeddedDir =
38    include!(concat!(env!("OUT_DIR"), "/cookbook_recipes.rs"));
39
40#[cfg(test)]
41mod tests;
42mod tool_projection;
43mod tools;
44mod util;
45
46use sim_kernel::{
47    AbiVersion, CapabilityName, Cx, Expr, Lib, LibManifest, LibTarget, Linker, Result, Symbol,
48    Version,
49};
50use sim_lib_server::{
51    EvalSite, install_server_lib, register_address_resolver, register_line_driver,
52};
53
54const AGENT_LIB_ID: &str = "agent";
55const SANDBOX_CAPABILITY: &str = "sandbox";
56const SANDBOX_SUBPROCESS_CAPABILITY: &str = "sandbox-subprocess";
57const SANDBOX_WASM_CAPABILITY: &str = "sandbox-wasm";
58const VOICE_CAPABILITY: &str = "voice";
59const AGENT_SPAWN_CAPABILITY: &str = "agent-spawn";
60const AGENT_REPLACE_CAPABILITY: &str = "agent-replace";
61const AGENT_REFLECT_CAPABILITY: &str = "agent-reflect";
62const SWARM_LAUNCH_CAPABILITY: &str = "swarm-launch";
63const TOOL_EXPORT_KIND: &str = "tool";
64/// Capability name granting an agent the right to drive an AI model runner.
65pub const AI_RUNNER_CAPABILITY: &str = "ai-runner";
66/// Capability name granting an AI runner outbound network access.
67pub const AI_RUNNER_NETWORK_CAPABILITY: &str = "ai-runner-network";
68/// Capability name granting an AI runner access to a local (on-host) model.
69pub const AI_RUNNER_LOCAL_CAPABILITY: &str = "ai-runner-local";
70/// Capability name granting an AI runner access to secret material (e.g. API keys).
71pub const AI_RUNNER_SECRET_CAPABILITY: &str = "ai-runner-secret";
72/// Capability name granting an AI runner use of a response cache.
73pub const AI_RUNNER_CACHE_CAPABILITY: &str = "ai-runner-cache";
74/// Capability name granting an AI runner permission to emit raw request/response logs.
75pub const AI_RUNNER_RAW_LOG_CAPABILITY: &str = "ai-runner-raw-log";
76
77#[cfg(test)]
78pub(crate) use agents::component_name;
79pub use agents::{Agent, AgentFabric, AgentManifest, AgentRef, Budget, ComponentRef, TopologyRef};
80use agents::{agent_line_driver_factory, resolve_agent_address};
81pub use atelier::{
82    AgentMission, AtelierAction, GuardCapability, GuardDecision, GuardEvaluation, GuardRefusal,
83    RadarChunk, RadarError, RadarHint, RadarIndex, RadarQuery, RadarReport, RadarResult,
84    SelfHostingScenario, SourceSpan, cassette_content_hash, evaluate_guarded_action, guard_action,
85    retrieve_radar_hints, self_hosting_scenarios, validate_self_hosting_scenarios,
86};
87pub(crate) use capabilities::{
88    edit_capability, exec_capability, find_capability, fs_read_capability, fs_write_capability,
89    net_http_capability, require_component_capability, require_fs_read_capability,
90    require_fs_write_capability, require_net_http_capability,
91};
92use cli::{agent_cli_exports, register_agent_cli};
93pub use components::RunnerBackend;
94pub(crate) use components::{
95    AgentComponent, ComponentBackend, RecorderBackend, capabilities_option, component_kind_symbol,
96    maybe_f64_option, maybe_u32_option, parse_component_options, path_option, string_option,
97    symbol_option,
98};
99pub use config_probe::{
100    AgentModelConfigProbe, AgentModelProviderPresence, agent_model_config_probe_symbol,
101    model_defaults_config_lib_symbol,
102};
103pub(crate) use embed::{cosine, embed};
104pub use fairness::*;
105use functions::{agent_exports, register_agent_functions};
106pub(crate) use memory::lock_entries;
107pub(crate) use memory::resolve_memory_backend;
108pub use memory::{
109    BlackboardMemory, FileMemory, MemoryBackend, MemoryKind, PersonaMemory, VectorMemory,
110    WorkingMemory,
111};
112pub use multimodal::{
113    FakeAsrFixture, FakeAsrRunner, FakeAsrSegment, FakeSensorFrame, FakeSensorStream,
114    FakeVisionFixture, FakeVisionRunner,
115};
116pub use pattern::{AgentPattern, AgentPatternSlot};
117pub use planning::{
118    Decomposition, PlanningOutput, PlanningTask, Reflection, decompose, decompose_and_run, reflect,
119};
120pub use roles::{AgentRole, stamp_envelope_role, stamp_frame_role};
121pub use runner_projection::{ExternalRunnerSpec, external_runner_value};
122pub use sim_lib_agent_runner_core::{
123    ModelBid, ModelCard, ModelEvent, ModelEventSink, ModelRequest, ModelResponse, ModelRunner,
124    ModelUsage,
125};
126pub use tool_projection::{ToolSpec, install_tool};
127pub use tools::Tool;
128pub(crate) use tools::ToolFilter;
129pub(crate) use util::{
130    installed_codecs, keyword, string_from_value, stringish_from_value, symbol_from_value,
131    u32_from_expr, u32_from_value, value_from_expr,
132};
133
134/// The agent runtime library, registering agent functions, tools, and CLI
135/// exports as a loadable SIM [`Lib`].
136pub struct AgentLib;
137
138impl Lib for AgentLib {
139    fn manifest(&self) -> LibManifest {
140        LibManifest {
141            id: Symbol::new(AGENT_LIB_ID),
142            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
143            abi: AbiVersion { major: 0, minor: 1 },
144            target: LibTarget::HostRegistered,
145            requires: Vec::new(),
146            capabilities: Vec::new(),
147            exports: {
148                let mut exports = agent_exports();
149                exports.extend(agent_cli_exports());
150                exports
151            },
152        }
153    }
154
155    fn load(&self, cx: &mut sim_kernel::LoadCx, linker: &mut Linker<'_>) -> Result<()> {
156        register_agent_functions(cx, linker)?;
157        register_agent_cli(cx, linker)
158    }
159}
160
161/// Installs the agent library into `cx`, pulling in the server lib, registering
162/// the agent address resolver and line driver, and loading [`AgentLib`].
163pub fn install_agent_lib(cx: &mut Cx) -> Result<()> {
164    install_server_lib(cx)?;
165    register_address_resolver(Symbol::new("agent"), resolve_agent_address)?;
166    register_line_driver(Symbol::new("agent"), agent_line_driver_factory)?;
167    sim_lib_core::install_once(cx, &AgentLib)?;
168    core_tools::install_core_tools(cx)?;
169    #[cfg(feature = "cookbook")]
170    cookbook_tools::install_cookbook_tools(cx)?;
171    Ok(())
172}
173
174/// A pluggable agent building block (runner, tool, memory, planner, and so on)
175/// that participates in evaluation as an [`EvalSite`].
176pub trait Component: EvalSite {
177    /// Returns the kind of component this is.
178    fn kind(&self) -> ComponentKind;
179    /// Returns the component's name symbol.
180    fn name(&self) -> &Symbol;
181    /// Returns the capabilities this component requires or grants.
182    fn capabilities(&self) -> &[CapabilityName];
183    /// Produces a self-describing expression for inspection of this component.
184    fn reflect(&self, cx: &mut Cx) -> Result<Expr>;
185}
186
187#[derive(Clone, Debug, PartialEq, Eq)]
188/// The role a [`Component`] plays within an agent.
189pub enum ComponentKind {
190    /// Drives a model to produce responses.
191    Runner,
192    /// Exposes a callable tool the agent may invoke.
193    Tool,
194    /// Stores and retrieves agent memory.
195    Memory,
196    /// Decomposes tasks and plans agent execution.
197    Planner,
198    /// Scores or ranks candidate responses.
199    Judge,
200    /// Routes work among targets.
201    Router,
202    /// Shapes the agent's voice or style.
203    Persona,
204    /// Retrieves external context or documents.
205    Retriever,
206    /// Confines execution within a sandbox.
207    Sandbox,
208    /// Records transcripts, audits, or metrics.
209    Recorder,
210    /// Handles speech synthesis or recognition.
211    Voice,
212    /// Describes the agent network's topology.
213    Topology,
214    /// A custom component kind named by the given symbol.
215    Custom(Symbol),
216}