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 cli;
19mod components;
20#[cfg(feature = "cookbook")]
21mod cookbook_tools;
22mod embed;
23mod fairness;
24mod functions;
25mod memory;
26mod model_privacy;
27mod multimodal;
28mod pattern;
29mod planning;
30mod reply;
31mod roles;
32mod runner_projection;
33/// Cookbook recipes for this lib, embedded at build time.
34pub static RECIPES: sim_cookbook::EmbeddedDir =
35    include!(concat!(env!("OUT_DIR"), "/cookbook_recipes.rs"));
36
37#[cfg(test)]
38mod tests;
39mod tool_projection;
40mod tools;
41mod util;
42
43use sim_kernel::{
44    AbiVersion, CapabilityName, Cx, Expr, Lib, LibManifest, LibTarget, Linker, Result, Symbol,
45    Version,
46};
47use sim_lib_server::{
48    EvalSite, install_server_lib, register_address_resolver, register_line_driver,
49};
50
51const AGENT_LIB_ID: &str = "agent";
52const SANDBOX_CAPABILITY: &str = "sandbox";
53const SANDBOX_SUBPROCESS_CAPABILITY: &str = "sandbox-subprocess";
54const SANDBOX_WASM_CAPABILITY: &str = "sandbox-wasm";
55const VOICE_CAPABILITY: &str = "voice";
56const FILE_READ_CAPABILITY: &str = "file-read";
57const FILE_WRITE_CAPABILITY: &str = "file-write";
58const NETWORK_CAPABILITY: &str = "network";
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};
87use cli::{agent_cli_exports, register_agent_cli};
88pub use components::RunnerBackend;
89pub(crate) use components::{
90    AgentComponent, ComponentBackend, RecorderBackend, capabilities_option, component_kind_symbol,
91    maybe_f64_option, maybe_u32_option, parse_component_options, path_option, string_option,
92    symbol_option,
93};
94pub(crate) use embed::{cosine, embed};
95pub use fairness::*;
96use functions::{agent_exports, register_agent_functions};
97pub(crate) use memory::lock_entries;
98pub(crate) use memory::resolve_memory_backend;
99pub use memory::{
100    BlackboardMemory, FileMemory, MemoryBackend, MemoryKind, PersonaMemory, VectorMemory,
101    WorkingMemory,
102};
103pub use multimodal::{
104    FakeAsrFixture, FakeAsrRunner, FakeAsrSegment, FakeSensorFrame, FakeSensorStream,
105    FakeVisionFixture, FakeVisionRunner,
106};
107pub use pattern::{AgentPattern, AgentPatternSlot};
108pub use planning::{
109    Decomposition, PlanningOutput, PlanningTask, Reflection, decompose, decompose_and_run, reflect,
110};
111pub use roles::{AgentRole, stamp_envelope_role, stamp_frame_role};
112pub use runner_projection::{ExternalRunnerSpec, external_runner_value};
113pub use sim_lib_agent_runner_core::{
114    ModelBid, ModelCard, ModelEvent, ModelEventSink, ModelRequest, ModelResponse, ModelRunner,
115    ModelUsage,
116};
117pub use tool_projection::{ToolSpec, install_tool};
118pub use tools::Tool;
119pub(crate) use tools::ToolFilter;
120pub(crate) use util::{
121    expr_to_value, installed_codecs, keyword, string_from_value, stringish_from_value,
122    symbol_from_value, u32_from_expr, u32_from_value,
123};
124
125/// The agent runtime library, registering agent functions, tools, and CLI
126/// exports as a loadable SIM [`Lib`].
127pub struct AgentLib;
128
129impl Lib for AgentLib {
130    fn manifest(&self) -> LibManifest {
131        LibManifest {
132            id: Symbol::new(AGENT_LIB_ID),
133            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
134            abi: AbiVersion { major: 0, minor: 1 },
135            target: LibTarget::HostRegistered,
136            requires: Vec::new(),
137            capabilities: Vec::new(),
138            exports: {
139                let mut exports = agent_exports();
140                exports.extend(agent_cli_exports());
141                exports
142            },
143        }
144    }
145
146    fn load(&self, cx: &mut sim_kernel::LoadCx, linker: &mut Linker<'_>) -> Result<()> {
147        register_agent_functions(cx, linker)?;
148        register_agent_cli(cx, linker)
149    }
150}
151
152/// Installs the agent library into `cx`, pulling in the server lib, registering
153/// the agent address resolver and line driver, and loading [`AgentLib`].
154pub fn install_agent_lib(cx: &mut Cx) -> Result<()> {
155    install_server_lib(cx)?;
156    register_address_resolver(Symbol::new("agent"), resolve_agent_address)?;
157    register_line_driver(Symbol::new("agent"), agent_line_driver_factory)?;
158    sim_lib_core::install_once(cx, &AgentLib)?;
159    #[cfg(feature = "cookbook")]
160    cookbook_tools::install_cookbook_tools(cx)?;
161    Ok(())
162}
163
164/// A pluggable agent building block (runner, tool, memory, planner, and so on)
165/// that participates in evaluation as an [`EvalSite`].
166pub trait Component: EvalSite {
167    /// Returns the kind of component this is.
168    fn kind(&self) -> ComponentKind;
169    /// Returns the component's name symbol.
170    fn name(&self) -> &Symbol;
171    /// Returns the capabilities this component requires or grants.
172    fn capabilities(&self) -> &[CapabilityName];
173    /// Produces a self-describing expression for inspection of this component.
174    fn reflect(&self, cx: &mut Cx) -> Result<Expr>;
175}
176
177#[derive(Clone, Debug, PartialEq, Eq)]
178/// The role a [`Component`] plays within an agent.
179pub enum ComponentKind {
180    /// Drives a model to produce responses.
181    Runner,
182    /// Exposes a callable tool the agent may invoke.
183    Tool,
184    /// Stores and retrieves agent memory.
185    Memory,
186    /// Decomposes tasks and plans agent execution.
187    Planner,
188    /// Scores or ranks candidate responses.
189    Judge,
190    /// Routes work among targets.
191    Router,
192    /// Shapes the agent's voice or style.
193    Persona,
194    /// Retrieves external context or documents.
195    Retriever,
196    /// Confines execution within a sandbox.
197    Sandbox,
198    /// Records transcripts, audits, or metrics.
199    Recorder,
200    /// Handles speech synthesis or recognition.
201    Voice,
202    /// Describes the agent network's topology.
203    Topology,
204    /// A custom component kind named by the given symbol.
205    Custom(Symbol),
206}