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/// Capability name granting authority to register or replace model placements.
77pub const AI_RUNNER_PLACEMENT_CAPABILITY: &str = "ai-runner-placement";
78
79#[cfg(test)]
80pub(crate) use agents::component_name;
81pub use agents::{Agent, AgentFabric, AgentManifest, AgentRef, Budget, ComponentRef, TopologyRef};
82use agents::{agent_line_driver_factory, resolve_agent_address};
83pub use atelier::{
84    AgentMission, AtelierAction, GuardCapability, GuardDecision, GuardEvaluation, GuardRefusal,
85    RadarChunk, RadarError, RadarHint, RadarIndex, RadarQuery, RadarReport, RadarResult,
86    SelfHostingScenario, SourceSpan, cassette_content_hash, evaluate_guarded_action, guard_action,
87    retrieve_radar_hints, self_hosting_scenarios, validate_self_hosting_scenarios,
88};
89pub(crate) use capabilities::{
90    edit_capability, exec_capability, find_capability, fs_read_capability, fs_write_capability,
91    net_http_capability, require_component_capability, require_fs_read_capability,
92    require_fs_write_capability, require_net_http_capability,
93};
94use cli::{agent_cli_exports, register_agent_cli};
95pub use components::RunnerBackend;
96pub(crate) use components::{
97    AgentComponent, ComponentBackend, RecorderBackend, capabilities_option, component_kind_symbol,
98    maybe_f64_option, maybe_u32_option, parse_component_options, path_option, string_option,
99    symbol_option,
100};
101pub use config_probe::{
102    AgentModelConfigProbe, AgentModelProviderPresence, agent_model_config_probe_symbol,
103    model_defaults_config_lib_symbol,
104};
105pub(crate) use embed::{cosine, embed};
106pub use fairness::*;
107use functions::{agent_exports, register_agent_functions};
108pub(crate) use memory::lock_entries;
109pub(crate) use memory::resolve_memory_backend;
110pub use memory::{
111    BlackboardMemory, FileMemory, MemoryBackend, MemoryKind, PersonaMemory, VectorMemory,
112    WorkingMemory,
113};
114pub use multimodal::{
115    FakeAsrFixture, FakeAsrRunner, FakeAsrSegment, FakeSensorFrame, FakeSensorStream,
116    FakeVisionFixture, FakeVisionRunner,
117};
118pub use pattern::{AgentPattern, AgentPatternSlot};
119pub use planning::{
120    Decomposition, PlanningOutput, PlanningTask, Reflection, decompose, decompose_and_run, reflect,
121};
122pub use roles::{AgentRole, stamp_envelope_role, stamp_frame_role};
123pub use runner_projection::{ExternalRunnerSpec, external_runner_value};
124pub use sim_lib_agent_runner_core::{
125    ModelBid, ModelCard, ModelEvent, ModelEventSink, ModelRequest, ModelResponse, ModelRunner,
126    ModelUsage,
127};
128pub use tool_projection::{ToolSpec, install_tool};
129pub use tools::Tool;
130pub(crate) use tools::ToolFilter;
131pub(crate) use util::{
132    installed_codecs, keyword, string_from_value, stringish_from_value, symbol_from_value,
133    u32_from_expr, u32_from_value, value_from_expr,
134};
135
136/// The agent runtime library, registering agent functions, tools, and CLI
137/// exports as a loadable SIM [`Lib`].
138pub struct AgentLib;
139
140impl Lib for AgentLib {
141    fn manifest(&self) -> LibManifest {
142        LibManifest {
143            id: Symbol::new(AGENT_LIB_ID),
144            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
145            abi: AbiVersion { major: 0, minor: 1 },
146            target: LibTarget::HostRegistered,
147            requires: Vec::new(),
148            capabilities: Vec::new(),
149            exports: {
150                let mut exports = agent_exports();
151                exports.extend(agent_cli_exports());
152                exports
153            },
154        }
155    }
156
157    fn load(&self, cx: &mut sim_kernel::LoadCx, linker: &mut Linker<'_>) -> Result<()> {
158        register_agent_functions(cx, linker)?;
159        register_agent_cli(cx, linker)
160    }
161}
162
163/// Installs the agent library into `cx`, pulling in the server lib, registering
164/// the agent address resolver and line driver, and loading [`AgentLib`].
165pub fn install_agent_lib(cx: &mut Cx) -> Result<()> {
166    install_server_lib(cx)?;
167    register_address_resolver(Symbol::new("agent"), resolve_agent_address)?;
168    register_line_driver(Symbol::new("agent"), agent_line_driver_factory)?;
169    sim_lib_core::install_once(cx, &AgentLib)?;
170    core_tools::install_core_tools(cx)?;
171    #[cfg(feature = "cookbook")]
172    cookbook_tools::install_cookbook_tools(cx)?;
173    Ok(())
174}
175
176/// A pluggable agent building block (runner, tool, memory, planner, and so on)
177/// that participates in evaluation as an [`EvalSite`].
178pub trait Component: EvalSite {
179    /// Returns the kind of component this is.
180    fn kind(&self) -> ComponentKind;
181    /// Returns the component's name symbol.
182    fn name(&self) -> &Symbol;
183    /// Returns the capabilities this component requires or grants.
184    fn capabilities(&self) -> &[CapabilityName];
185    /// Produces a self-describing expression for inspection of this component.
186    fn reflect(&self, cx: &mut Cx) -> Result<Expr>;
187}
188
189#[derive(Clone, Debug, PartialEq, Eq)]
190/// The role a [`Component`] plays within an agent.
191pub enum ComponentKind {
192    /// Drives a model to produce responses.
193    Runner,
194    /// Exposes a callable tool the agent may invoke.
195    Tool,
196    /// Stores and retrieves agent memory.
197    Memory,
198    /// Decomposes tasks and plans agent execution.
199    Planner,
200    /// Scores or ranks candidate responses.
201    Judge,
202    /// Routes work among targets.
203    Router,
204    /// Shapes the agent's voice or style.
205    Persona,
206    /// Retrieves external context or documents.
207    Retriever,
208    /// Confines execution within a sandbox.
209    Sandbox,
210    /// Records transcripts, audits, or metrics.
211    Recorder,
212    /// Handles speech synthesis or recognition.
213    Voice,
214    /// Describes the agent network's topology.
215    Topology,
216    /// A custom component kind named by the given symbol.
217    Custom(Symbol),
218}