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#[cfg(test)]
34mod tests;
35mod tool_projection;
36mod tools;
37mod util;
38
39use sim_kernel::{
40    AbiVersion, CapabilityName, Cx, Expr, Lib, LibManifest, LibTarget, Linker, Result, Symbol,
41    Version,
42};
43use sim_lib_server::{
44    EvalSite, install_server_lib, register_address_resolver, register_line_driver,
45};
46
47const AGENT_LIB_ID: &str = "agent";
48const SANDBOX_CAPABILITY: &str = "sandbox";
49const SANDBOX_SUBPROCESS_CAPABILITY: &str = "sandbox-subprocess";
50const SANDBOX_WASM_CAPABILITY: &str = "sandbox-wasm";
51const VOICE_CAPABILITY: &str = "voice";
52const FILE_READ_CAPABILITY: &str = "file-read";
53const FILE_WRITE_CAPABILITY: &str = "file-write";
54const NETWORK_CAPABILITY: &str = "network";
55const AGENT_SPAWN_CAPABILITY: &str = "agent-spawn";
56const AGENT_REPLACE_CAPABILITY: &str = "agent-replace";
57const AGENT_REFLECT_CAPABILITY: &str = "agent-reflect";
58const SWARM_LAUNCH_CAPABILITY: &str = "swarm-launch";
59const TOOL_EXPORT_KIND: &str = "tool";
60/// Capability name granting an agent the right to drive an AI model runner.
61pub const AI_RUNNER_CAPABILITY: &str = "ai-runner";
62/// Capability name granting an AI runner outbound network access.
63pub const AI_RUNNER_NETWORK_CAPABILITY: &str = "ai-runner-network";
64/// Capability name granting an AI runner access to a local (on-host) model.
65pub const AI_RUNNER_LOCAL_CAPABILITY: &str = "ai-runner-local";
66/// Capability name granting an AI runner access to secret material (e.g. API keys).
67pub const AI_RUNNER_SECRET_CAPABILITY: &str = "ai-runner-secret";
68/// Capability name granting an AI runner use of a response cache.
69pub const AI_RUNNER_CACHE_CAPABILITY: &str = "ai-runner-cache";
70/// Capability name granting an AI runner permission to emit raw request/response logs.
71pub const AI_RUNNER_RAW_LOG_CAPABILITY: &str = "ai-runner-raw-log";
72
73#[cfg(test)]
74pub(crate) use agents::component_name;
75pub use agents::{Agent, AgentFabric, AgentManifest, AgentRef, Budget, ComponentRef, TopologyRef};
76use agents::{agent_line_driver_factory, resolve_agent_address};
77pub use atelier::{
78    AgentMission, AtelierAction, GuardCapability, GuardDecision, GuardEvaluation, GuardRefusal,
79    RadarChunk, RadarError, RadarHint, RadarIndex, RadarQuery, RadarReport, RadarResult,
80    SelfHostingScenario, SourceSpan, cassette_content_hash, evaluate_guarded_action, guard_action,
81    retrieve_radar_hints, self_hosting_scenarios, validate_self_hosting_scenarios,
82};
83use cli::{agent_cli_exports, register_agent_cli};
84pub use components::RunnerBackend;
85pub(crate) use components::{
86    AgentComponent, ComponentBackend, RecorderBackend, capabilities_option, component_kind_symbol,
87    maybe_f64_option, maybe_u32_option, parse_component_options, path_option, string_option,
88    symbol_option,
89};
90pub(crate) use embed::{cosine, embed};
91pub use fairness::*;
92use functions::{agent_exports, register_agent_functions};
93pub(crate) use memory::lock_entries;
94pub(crate) use memory::resolve_memory_backend;
95pub use memory::{
96    BlackboardMemory, FileMemory, MemoryBackend, MemoryKind, PersonaMemory, VectorMemory,
97    WorkingMemory,
98};
99pub use multimodal::{
100    FakeAsrFixture, FakeAsrRunner, FakeAsrSegment, FakeSensorFrame, FakeSensorStream,
101    FakeVisionFixture, FakeVisionRunner,
102};
103pub use pattern::{AgentPattern, AgentPatternSlot};
104pub use planning::{
105    Decomposition, PlanningOutput, PlanningTask, Reflection, decompose, decompose_and_run, reflect,
106};
107pub use roles::{AgentRole, stamp_envelope_role, stamp_frame_role};
108pub use runner_projection::{ExternalRunnerSpec, external_runner_value};
109pub use sim_lib_agent_runner_core::{
110    ModelBid, ModelCard, ModelEvent, ModelEventSink, ModelRequest, ModelResponse, ModelRunner,
111    ModelUsage,
112};
113pub use tool_projection::{ToolSpec, install_tool};
114pub use tools::Tool;
115pub(crate) use tools::ToolFilter;
116pub(crate) use util::{
117    expr_to_value, installed_codecs, keyword, string_from_value, stringish_from_value,
118    symbol_from_value, u32_from_expr, u32_from_value,
119};
120
121/// The agent runtime library, registering agent functions, tools, and CLI
122/// exports as a loadable SIM [`Lib`].
123pub struct AgentLib;
124
125impl Lib for AgentLib {
126    fn manifest(&self) -> LibManifest {
127        LibManifest {
128            id: Symbol::new(AGENT_LIB_ID),
129            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
130            abi: AbiVersion { major: 0, minor: 1 },
131            target: LibTarget::HostRegistered,
132            requires: Vec::new(),
133            capabilities: Vec::new(),
134            exports: {
135                let mut exports = agent_exports();
136                exports.extend(agent_cli_exports());
137                exports
138            },
139        }
140    }
141
142    fn load(&self, cx: &mut sim_kernel::LoadCx, linker: &mut Linker<'_>) -> Result<()> {
143        register_agent_functions(cx, linker)?;
144        register_agent_cli(cx, linker)
145    }
146}
147
148/// Installs the agent library into `cx`, pulling in the server lib, registering
149/// the agent address resolver and line driver, and loading [`AgentLib`].
150pub fn install_agent_lib(cx: &mut Cx) -> Result<()> {
151    install_server_lib(cx)?;
152    register_address_resolver(Symbol::new("agent"), resolve_agent_address)?;
153    register_line_driver(Symbol::new("agent"), agent_line_driver_factory)?;
154    sim_lib_core::install_once(cx, &AgentLib)?;
155    #[cfg(feature = "cookbook")]
156    cookbook_tools::install_cookbook_tools(cx)?;
157    Ok(())
158}
159
160/// A pluggable agent building block (runner, tool, memory, planner, and so on)
161/// that participates in evaluation as an [`EvalSite`].
162pub trait Component: EvalSite {
163    /// Returns the kind of component this is.
164    fn kind(&self) -> ComponentKind;
165    /// Returns the component's name symbol.
166    fn name(&self) -> &Symbol;
167    /// Returns the capabilities this component requires or grants.
168    fn capabilities(&self) -> &[CapabilityName];
169    /// Produces a self-describing expression for inspection of this component.
170    fn reflect(&self, cx: &mut Cx) -> Result<Expr>;
171}
172
173#[derive(Clone, Debug, PartialEq, Eq)]
174/// The role a [`Component`] plays within an agent.
175pub enum ComponentKind {
176    /// Drives a model to produce responses.
177    Runner,
178    /// Exposes a callable tool the agent may invoke.
179    Tool,
180    /// Stores and retrieves agent memory.
181    Memory,
182    /// Decomposes tasks and plans agent execution.
183    Planner,
184    /// Scores or ranks candidate responses.
185    Judge,
186    /// Routes work among targets.
187    Router,
188    /// Shapes the agent's voice or style.
189    Persona,
190    /// Retrieves external context or documents.
191    Retriever,
192    /// Confines execution within a sandbox.
193    Sandbox,
194    /// Records transcripts, audits, or metrics.
195    Recorder,
196    /// Handles speech synthesis or recognition.
197    Voice,
198    /// Describes the agent network's topology.
199    Topology,
200    /// A custom component kind named by the given symbol.
201    Custom(Symbol),
202}