Skip to main content

aidaemon_sdk/
lib.rs

1//! # aidaemon-sdk (experimental)
2//!
3//! One dependency for building agents on the aidaemon kernel. The kernel
4//! ([`aidaemon_core`], re-exported at the crate root) owns the loop, typed
5//! outcomes, receipts, limits, events and interrupt/resume. Everything else
6//! is an optional module, enabled by a feature of the same name:
7//!
8//! | Module | Feature | What it adds |
9//! |---|---|---|
10//! | [`providers`] | `providers` (default) | OpenAI-compatible and Anthropic models, streaming |
11//! | [`tools`] | `tools` (default) | Workspace file tools, search, sandboxed shell, web fetch, checklist |
12//! | [`policies`] | `policies` (default) | Approvals, scope and egress guards, streak guard, redaction, instructions, context window, conversation compaction, memory, tracing |
13//! | [`secrets`] | `secrets` (default; `keychain` for the OS store) | Secret stores whose values come out as `Secret` and are redacted from every run |
14//! | [`agents`] | `agents` (default) | Agents as tools, child budgets |
15//! | [`coding_agents`] | `coding-agents` (+ `mcp`) | Coding agents (Claude Code, Codex, ACP), permission hosts, and MCP peer-CLI coordination (`coding_agents::peer`) |
16//! | [`store`] | `sqlite` (default) | Durable runs on SQLite, crash recovery queries, upkeep (`store::maintenance`: planner statistics, live snapshots) |
17//! | [`mcp`] | `mcp` | MCP client (`McpServer`) and reusable MCP server + stdio bridge (`LocalMcpServer`, `serve_stdio`, `run_stdio_bridge`) |
18//! | [`eval`] | `eval` | YAML scenarios, N-of-M pass rates, baseline comparison |
19//! | [`memory`] | `memory` (+ `fastembed`) | Long-term memory: facts, episodes, hybrid recall; every part swappable |
20//! | [`events`] | `events` | The immutable event store, its payloads and the run aggregate |
21//! | [`work`] | `work` | **Internal, unstable:** the daemon's goals, mandates, tasks and notifications. Not for applications; schedule your own work with [`ServiceHost`] |
22//! | [`channels`] | `channels` | The `Channel` contract and the runner that connects channels to agents |
23//! | [`channels::telegram`], [`channels::slack`], [`channels::discord`] | `telegram`, `slack`, `discord` | Built-in channel adapters |
24//! | `channels::conformance` | `conformance` | The channel conformance kit, for your own adapter's tests |
25//! | [`secrets`] | `secrets` | Where an agent keeps its secrets: the `SecretStore` trait, the OS keychain, an env file, an in-memory store |
26//! | [`testing`] | `testing` | Scripted provider for tests (and Tokio's `test-util`, for paused time); the shared behavior suite (`testing::behavior`) |
27//! | [`tool`] | `macros` (default) | `#[tool]`: a tool from a plain function, schema derived |
28//! | [`mod@preset`] | `providers` + `policies` (default) | A short start: provider, safeguards, store and default tools in a few lines |
29//! | [`structured`] | always | Typed output: a model call or an agent's final answer as your type, one repair retry |
30//!
31//! Background work is in the kernel, at the crate root: a [`Service`]
32//! states its [`Schedule`] (every so often, every tick, continuously, or
33//! daily at a UTC time) and a [`ServiceHost`] runs it, with backoff after
34//! failures, one run at a time per service, and one [`ServiceEvent::Ended`]
35//! per run (its number, outcome and duration) for a [`ServiceObserver`].
36//! The `scheduled_worker` example drives an agent from one.
37//!
38//! ```no_run
39//! # #[cfg(all(feature = "providers", feature = "tools", feature = "policies"))]
40//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
41//! use aidaemon_sdk::prelude::*;
42//! use aidaemon_sdk::{Authority, AuthorityHook};
43//!
44//! let workspace = tools::Workspace::new(".")?;
45//! let mut builder = Agent::builder("helper")
46//!     .model("claude-sonnet-5-5")
47//!     .instructions("You maintain this repository. Verify changes with tests.")
48//!     .provider(providers::Anthropic::builder().api_key("<key>").build()?)
49//!     .hook(AuthorityHook::new(Authority::full()))
50//!     .hook(policies::ScopeGuard::new([workspace.root()]))
51//!     .hook(policies::EgressGuard::new())
52//!     .hook(policies::ApprovalPolicy::new(policies::ApprovalMode::DestructiveOnly))
53//!     .hook(policies::UntrustedOutput::default());
54//! for tool in tools::default_tools(workspace) {
55//!     builder = builder.tool_arc(tool);
56//! }
57//! let agent = builder.build()?;
58//!
59//! let mut outcome = agent.run("cli:synthetic-user-1", "Fix the failing test").await?;
60//! while let RunStatus::Interrupted { interruption } = &outcome.status {
61//!     println!("approve {}? (auto-approving in this example)", interruption.call.name);
62//!     outcome = agent.resume(outcome.state, Resolution::Approve).await?;
63//! }
64//! println!("{:?}: {}", outcome.status, outcome.final_text.unwrap_or_default());
65//! # Ok(())
66//! # }
67//! ```
68//!
69//! See the SDK guide at <https://docs.aidaemon.ai/sdk>.
70
71// Feature unification only (cargo-hakari); keeps the unused-dependency lint quiet.
72use workspace_hack as _;
73
74pub use aidaemon_core::*;
75
76/// Test helpers: the kernel's scripted provider and response builders and,
77/// with the `macros`, `agents` and `channels` features, the
78/// [`behavior`](testing::behavior) suite every assembled agent should pass.
79#[cfg(feature = "testing")]
80pub mod testing {
81    pub use aidaemon_core::testing::*;
82
83    #[cfg(all(
84        feature = "macros",
85        feature = "agents",
86        feature = "channels",
87        feature = "providers",
88        feature = "policies"
89    ))]
90    pub mod behavior;
91}
92
93pub mod schema;
94pub mod structured;
95
96#[cfg(all(feature = "providers", feature = "policies"))]
97pub mod preset;
98#[cfg(all(feature = "providers", feature = "policies"))]
99pub use preset::{Preset, PresetError, preset};
100
101#[cfg(feature = "runtime")]
102pub mod runtime;
103
104#[doc(hidden)]
105#[path = "macro_support.rs"]
106pub mod __private;
107
108/// Write a tool as a plain function: `#[tool]` derives its JSON schema from
109/// the parameters (with `schemars`) and emits a unit struct, named after the
110/// function in `PascalCase`, that implements [`Tool`].
111///
112/// ```
113/// use aidaemon_sdk::{tool, Tool};
114///
115/// /// Look up an order: customer, item and total.
116/// #[tool(read_only)]
117/// async fn lookup_order(
118///     /// The order id, like `ORD-1001`.
119///     order_id: String,
120/// ) -> String {
121///     format!("{order_id}: Acme Kettle, 45.00 (synthetic)")
122/// }
123///
124/// let spec = LookupOrder.spec();
125/// assert_eq!(spec.name, "lookup_order");
126/// assert_eq!(spec.parameters["additionalProperties"], false);
127/// ```
128///
129/// - **Description:** the function's doc comment (required; or pass
130///   `description = "..."`). A parameter's doc comment becomes its
131///   description in the schema.
132/// - **Name:** the function's name, or `name = "..."`.
133/// - **Arguments:** each parameter is one key of the argument object
134///   (owned types implementing `Deserialize` and `JsonSchema`; `Option<T>`
135///   is optional). `#[serde(...)]` and `#[schemars(...)]` attributes on a
136///   parameter are kept. Or mark one parameter `#[args]` to take the whole
137///   object as your own type (`#[derive(Deserialize, JsonSchema)]`). A
138///   `&ToolContext` parameter, anywhere, receives the call's context
139///   (session, cancellation, the application's `extensions`).
140/// - **Returns:** `String`, `&str`, `ToolOutput`, `serde_json::Value`, or a
141///   `Result` of one of them whose error displays (an error reaches the
142///   model as a failed call). The function may be sync or async.
143/// - **Annotations** are explicit, never guessed. With no preset a tool is
144///   [`ToolAnnotations::DESTRUCTIVE`], the same conservative default as a
145///   hand-written tool. `read_only`, `write` and `destructive` pick
146///   [`ToolAnnotations::READ_ONLY`], [`ToolAnnotations::WRITE`] or
147///   [`ToolAnnotations::DESTRUCTIVE`]; `idempotent = bool` and
148///   `egress = bool` (alias `open_world`) then override that one field. A
149///   read-only tool that contacts another host must say `egress = true`.
150/// - **Trust:** output is untrusted unless you pass `trusted` (the result
151///   is the owner's own data, not content someone else wrote).
152/// - **Effects and access:** `effects = path` names a
153///   `fn(&Args) -> CallEffects`, `access = path` a
154///   `fn(&Args) -> AccessManifest` (with `#[args]`, `Args` is your type).
155///   Without `effects` a tool gets the kernel's defaults: no effects for a
156///   read-only call that is not egress; otherwise the effects its `access`
157///   implies ([`CallEffects::from_access`]: a written path is a write, a
158///   host an egress), so an owner's denial binds the rest of the run; and
159///   unknown with neither.
160/// - `timeout_secs = N` overrides `Limits::tool_timeout`; `crate = path`
161///   points the generated code at a re-export of `aidaemon_sdk`.
162///
163/// Arguments are checked before anything runs: a call that is not an
164/// object, has a key the schema does not declare, or does not deserialize
165/// is refused by `validate` and answered with an error result by `call`.
166#[cfg(feature = "macros")]
167pub use aidaemon_macros::tool;
168
169#[cfg(feature = "providers")]
170pub use aidaemon_providers as providers;
171
172#[cfg(feature = "tools")]
173pub use aidaemon_tools as tools;
174
175#[cfg(feature = "policies")]
176pub use aidaemon_policies as policies;
177
178#[cfg(feature = "secrets")]
179pub use aidaemon_secrets as secrets;
180
181#[cfg(feature = "agents")]
182pub use aidaemon_agents as agents;
183
184#[cfg(feature = "coding-agents")]
185pub use aidaemon_coding_agents as coding_agents;
186
187#[cfg(feature = "sqlite")]
188pub use aidaemon_store_sqlite as store;
189
190#[cfg(feature = "mcp")]
191pub use aidaemon_mcp as mcp;
192
193#[cfg(feature = "eval")]
194pub use aidaemon_eval as eval;
195
196#[cfg(feature = "memory")]
197pub use aidaemon_memory as memory;
198
199#[cfg(feature = "events")]
200pub use aidaemon_events as events;
201
202#[cfg(feature = "work")]
203pub use aidaemon_work as work;
204
205#[cfg(feature = "surfaces")]
206pub use aidaemon_surfaces as surfaces;
207
208/// Chat channels: the contract, the runner, and the built-in adapters.
209#[cfg(feature = "channels")]
210pub mod channels {
211    pub use aidaemon_channels::*;
212
213    /// The typed status a channel can render natively: helper runs, plan
214    /// cards and steps ([`card`]), drawn as text by
215    /// [`live_status::render_card`].
216    pub use aidaemon_core::card;
217
218    #[cfg(feature = "discord")]
219    pub use aidaemon_channel_discord as discord;
220    #[cfg(feature = "slack")]
221    pub use aidaemon_channel_slack as slack;
222    #[cfg(feature = "telegram")]
223    pub use aidaemon_channel_telegram as telegram;
224}
225
226/// The names most agents need, plus the enabled modules.
227pub mod prelude {
228    pub use aidaemon_core::{
229        Agent, AgentBuilder, CallResult, Event, Hook, HookContext, Limits, Message, Provider,
230        Receipt, ReceiptStatus, Resolution, Role, RunOutcome, RunState, RunStatus, SourceTrust,
231        StopDecision, Tool, ToolAnnotations, ToolCall, ToolContext, ToolDecision, ToolError,
232        ToolInfo, ToolOutput, ToolResult, ToolSpec,
233    };
234
235    #[cfg(feature = "macros")]
236    pub use crate::tool;
237
238    #[cfg(all(feature = "providers", feature = "policies"))]
239    pub use crate::preset::{Preset, PresetError, preset};
240
241    /// `agent.as_tool(..)`: an agent as another agent's tool.
242    #[cfg(feature = "agents")]
243    pub use crate::agents::{self, AgentExt};
244    #[cfg(feature = "channels")]
245    pub use crate::channels;
246    #[cfg(feature = "eval")]
247    pub use crate::eval;
248    #[cfg(feature = "mcp")]
249    pub use crate::mcp;
250    #[cfg(feature = "memory")]
251    pub use crate::memory;
252    #[cfg(feature = "policies")]
253    pub use crate::policies;
254    #[cfg(feature = "providers")]
255    pub use crate::providers;
256    #[cfg(feature = "sqlite")]
257    pub use crate::store;
258    #[cfg(feature = "tools")]
259    pub use crate::tools;
260}