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