Expand description
§aidaemon-sdk (experimental)
One dependency for building agents on the aidaemon kernel. The kernel
(aidaemon_core, re-exported at the crate root) owns the loop, typed
outcomes, receipts, limits, events and interrupt/resume. Everything else
is an optional module, enabled by a feature of the same name:
| Module | Feature | What it adds |
|---|---|---|
providers | providers (default) | OpenAI-compatible and Anthropic models, streaming |
tools | tools (default) | Workspace file tools, search, sandboxed shell, web fetch, checklist |
policies | policies (default) | Approvals, scope and egress guards, streak guard, redaction, instructions, context window, conversation compaction, memory, tracing |
secrets | secrets (default; keychain for the OS store) | Secret stores whose values come out as Secret and are redacted from every run |
agents | agents (default) | Agents as tools, child budgets |
[coding_agents] | coding-agents (+ mcp) | Coding agents (Claude Code, Codex, ACP), permission hosts, and MCP peer-CLI coordination (coding_agents::peer) |
store | sqlite (default) | Durable runs on SQLite, crash recovery queries, upkeep (store::maintenance: planner statistics, live snapshots) |
[mcp] | mcp | MCP client (McpServer) and reusable MCP server + stdio bridge (LocalMcpServer, serve_stdio, run_stdio_bridge) |
[eval] | eval | YAML scenarios, N-of-M pass rates, baseline comparison |
memory | memory (+ fastembed) | Long-term memory: facts, episodes, hybrid recall; every part swappable |
[events] | events | The immutable event store, its payloads and the run aggregate |
[work] | work | Internal, unstable: the daemon’s goals, mandates, tasks and notifications. Not for applications; schedule your own work with ServiceHost |
[channels] | channels | The Channel contract and the runner that connects channels to agents |
[channels::telegram], [channels::slack], [channels::discord] | telegram, slack, discord | Built-in channel adapters |
channels::conformance | conformance | The channel conformance kit, for your own adapter’s tests |
secrets | secrets | Where an agent keeps its secrets: the SecretStore trait, the OS keychain, an env file, an in-memory store |
[testing] | testing | Scripted provider for tests (and Tokio’s test-util, for paused time); the shared behavior suite (testing::behavior) |
tool | macros (default) | #[tool]: a tool from a plain function, schema derived |
preset | providers + policies (default) | A short start: provider, safeguards, store and default tools in a few lines |
structured | always | Typed output: a model call or an agent’s final answer as your type, one repair retry |
Background work is in the kernel, at the crate root: a Service
states its Schedule (every so often, every tick, continuously, or
daily at a UTC time) and a ServiceHost runs it, with backoff after
failures, one run at a time per service, and one ServiceEvent::Ended
per run (its number, outcome and duration) for a ServiceObserver.
The scheduled_worker example drives an agent from one.
use aidaemon_sdk::prelude::*;
use aidaemon_sdk::{Authority, AuthorityHook};
let workspace = tools::Workspace::new(".")?;
let mut builder = Agent::builder("helper")
.model("claude-sonnet-5-5")
.instructions("You maintain this repository. Verify changes with tests.")
.provider(providers::Anthropic::builder().api_key("<key>").build()?)
.hook(AuthorityHook::new(Authority::full()))
.hook(policies::ScopeGuard::new([workspace.root()]))
.hook(policies::EgressGuard::new())
.hook(policies::ApprovalPolicy::new(policies::ApprovalMode::DestructiveOnly))
.hook(policies::UntrustedOutput::default());
for tool in tools::default_tools(workspace) {
builder = builder.tool_arc(tool);
}
let agent = builder.build()?;
let mut outcome = agent.run("cli:synthetic-user-1", "Fix the failing test").await?;
while let RunStatus::Interrupted { interruption } = &outcome.status {
println!("approve {}? (auto-approving in this example)", interruption.call.name);
outcome = agent.resume(outcome.state, Resolution::Approve).await?;
}
println!("{:?}: {}", outcome.status, outcome.final_text.unwrap_or_default());See the SDK guide at https://docs.aidaemon.ai/sdk.
Re-exports§
pub use preset::Preset;pub use preset::PresetError;pub use preset::preset;pub use aidaemon_providers as providers;pub use aidaemon_tools as tools;pub use aidaemon_policies as policies;pub use aidaemon_secrets as secrets;pub use aidaemon_agents as agents;pub use aidaemon_store_sqlite as store;pub use aidaemon_memory as memory;
Modules§
- card
- The typed state every status card renders from.
- mandate_
card - The owner’s confirmation card for a mandate as it travels in
crate::OwnerApprovalRequest::warnings: five essentials the owner reads at a glance (each a"<label>: <text>"line with a label fromEssential), then every other line as a detail. Here, below both the work crate that builds it and the channels that render it. - prelude
- The names most agents need, plus the enabled modules.
- preset
- A short start: an agent with a provider, the required safeguards, a run store and, if you give it a workspace, the default tools, in a few lines.
- redaction
- Secret redaction at the kernel boundary.
- schema
- JSON Schemas from Rust types, shaped the way model providers take them.
- structured
- Typed structured output: a model call, or an agent’s final answer, returned as your own type.
Structs§
- Access
Manifest - What one call will touch, declared by the tool from its arguments. Policies use it for scope checks and sandboxes for confinement. Empty means “not declared”, not “touches nothing”.
- Agent
- An agent is configuration: a stable id, a model, instructions, tools and hooks. It holds no per-run state, is cheap to clone, and can run many sessions concurrently.
- Agent
Builder - Builder for
Agent.providerandmodelare required, and an agent with tools must cover everySafeguard::REQUIREDsafeguard (seeAgentBuilder::attestandAgentBuilder::allow_unguarded). - Approval
Card - An approval card’s content as facts, so every channel says the same thing in its own formatting: who asks, what will happen, why the owner is asked, and the one high-impact effect worth a warning.
- Audio
- Audio the model should hear, on a user message: base64 data in a
container named the OpenAI way (
ogg/opus,mp3,wav,flac,aac). Providers without audio input drop it.Debugomits the bytes. - Authority
- What a run is allowed to do: a level plus an optional tool allow-list.
- Authority
Hook - Enforces the granted
Authority(level and tool set) on every call, and declaresSafeguard::Authorityso the agent builder accepts it. It never prompts: a composition root that wants approvals for some calls adds its own hook. - Call
Effects - The effects of one call, declared by its tool from the arguments.
- Call
Result - One tool call of a run and what the model was told about it (see
RunOutcome::tool_results). - Cancellation
Token - Re-exported so tools can observe cancellation without adding the dependency. A token which can be used to signal a cancellation request to one or more tasks.
- Cooldown
- An account (or one model of it) that will not answer until
until. - Default
Failover - The default
FailoverPolicy. - Effect
Key - One effect of a call on one target.
- Endpoint
Publisher - Sets the live origin of one
EndpointSource. - Endpoint
Source - The origins a service is reachable at, live origin first.
- Extensions
- Typed application values a tool can read from its
ToolContext, keyed by type: at most one value per type. The application sets them on the agent withcrate::AgentBuilder::tool_extensions; every call’s context carries them. Cloning is cheap (values are shared). - Failover
- A provider chain: each step is tried in order until one answers.
- Failover
Step - One link of a
Failoverchain: a provider, the model it is asked for, how long an attempt may take to start answering, and how many attempts it gets before the chain moves on. - Finish
- A tool’s request to end the run once its batch completes. The run ends
with
crate::RunStatus::Finishedandreplyas its final text, without another model call and without consultingon_stophooks. - FnService
- A
Servicefrom a closure. - FnTool
- Build a tool from a closure. Handy for tests and small integrations.
- Hook
Context - Read-only view of the run handed to every hook.
- InFlight
- A tool batch that was executing when the state was last saved. Present only in checkpoints taken mid-turn; used for crash recovery.
- Interruption
- Why the run paused.
- Limit
Grants - How far hooks have raised each limit for this run (see
crate::Hook::on_limit), on top of the agent’sLimits. - Limits
- Hard budgets for one run. Turns, tokens and tool calls are checked at the
top of every turn; tool calls and wall-clock time are also checked before
every call in a batch, and the model call and each tool are bounded by the
remaining wall-clock budget.
max_turnscannot be switched off: it is clamped toHARD_TURN_CAP. - Loaded
Tools - The deferred tools whose schemas the model is sent. Cheap to clone; clones share the set.
- Memory
Store - In-process store for tests and short-lived agents.
- Message
- A provider-neutral transcript entry.
- Model
Request - One provider call. Hooks may edit it in
crate::Hook::before_model. - Model
Response - A complete (non-streamed) model reply.
- Nested
Calls - The way a running tool has a call judged by its run (see the module
docs). Present in
crate::ToolContext::nestedwhile the run drives the tool’s call. - Owner
Approval Request - What the owner is asked to approve.
- Pending
- The unfinished tool batch of an interrupted turn.
- Pending
Finish - A finish a dispatched call returned in the current batch, kept until the batch ends (across an interruption or a restart) and then applied.
- Project
Ref - The project a turn works in: a unit of work the host keeps (an app’s
project, a bot placed in one), with the folder it lives in when it has
one. Memory and tools key project-scoped state on
ProjectRef::id, which stays the same when the project is renamed or its folder moves. - Provider
Switch - A move from one step of a
Failoverchain to the next, reported asStreamEvent::Switchedand then ascrate::Event::ProviderSwitched. - Quota
Guard - A provider wrapper for one account. After a failure that no other model of the account can avoid (a used-up quota, an account that cannot pay, a rejected credential) it answers every call with that error, without sending it, until the cooldown ends: until the quota’s stated reset, or for a fixed time when there is none.
- Receipt
- The durable record of one tool call. Every call produces exactly one, refusals included, so “what actually happened” never depends on what the model says happened.
- Redaction
Scope - A set of registered secrets: what an agent’s runs redact, beside its
hooks’
Redacters. - Request
Options - How a provider should answer, beyond the messages and tools. Providers map what their API supports and ignore the rest.
- Retry
- Retry layer: exponential backoff on retryable errors.
- RunId
- RunOutcome
- The typed result of
crate::Agent::runorcrate::Agent::resume. - RunSnapshot
- What a
StopConditioncan see. - RunState
- Everything needed to continue a run, as plain serializable data.
- Service
Context - What a service can see of its host and of the run it is in.
- Service
Error - Why a service’s run failed.
- Service
Host - Runs
Services until told to stop. - Service
Waker - Ends the host’s wait for the next tick.
- Shared
Declines - Owner declines shared by a family of runs: a run and the child runs it starts (and their children). A decline recorded in any of them reaches every other one before its next call, so a parent is refused an effect the owner declined inside its child, and a running child is refused one the owner declined in its parent after the child started.
- Store
Error - Stuck
Config - Thresholds for loop detection. Configurable on purpose: OpenHands hardcoded theirs and legitimate polling got flagged (their issue #762).
- Tool
Annotations - Effect hints that drive scheduling and policy.
- Tool
Call - One tool invocation requested by the model.
- Tool
Context - Trusted, harness-provided context for one call.
- Tool
Error - A tool failure the harness could not turn into normal output. The loop still reports it to the model as an error result; it never ends the run.
- Tool
Info - What
before_toolhooks know about the tool behind a call. - Tool
Load - Deferred tools a run loaded, surfaced after the result of the call
that answers
after_tool_call(the batch whose call loaded them). - Tool
Output - What a tool hands back to the model, plus structured details for receipts.
- Tool
Spec - What the model sees about a tool: the OpenAI-style function object.
- Tool
Surfacing - Deferred tools as a provider that can surface tools mid-conversation
sends them, so loading one never changes the request’s tool block (and
with it the whole cached prefix). Providers without that ignore it:
ModelRequest::toolsalready holds every tool the model may call. - Untrusted
Hook - Marks untrusted output as data and interrupts egress calls made after the
run read untrusted content. Declares
Safeguard::UntrustedOutput. - Usage
- Token accounting for one call or a whole run.
Enums§
- Access
Level - How much a run may change.
ReadOnly < Write. - Approval
Risk - How much is at stake in an approval request.
- AskReason
- Why the owner is asked.
- Build
Error - Misconfiguration caught when building an agent.
- Card
Action - What allowing the call does.
- Channel
Visibility - Visibility level of the channel the message originated from.
- Core
Error - Errors from
run/resumeitself. Things that happen inside a run (tool failures, provider outages, limits) are reported throughcrate::RunStatus, not here. - Effect
Class - What kind of thing a call does.
- Event
- Everything observable about a run, in order. One stream feeds UIs, tracing exporters, stores and eval assertions.
- Failover
Action - What a
Failoverdoes after a failed attempt. - Finish
Outcome - How a tool-driven finish judged the work.
- High
Impact - An effect that deserves a warning on the card.
- Hook
Failure - How a hook failed to give an answer.
- Hook
Point - A moment of the loop at which hooks run.
- Image
- An image the model should look at. Carried on user messages and on tool
results; providers map it to their own wire format and ignore it on other
roles.
Debugomits the encoded bytes so transcripts stay loggable. - Interrupt
Kind - Who an interruption is waiting for.
- Invocation
Stage - How far a call got before its outcome was decided.
- Limit
Decision - What an
on_limithook decides about a limit the run has reached. - Limit
Kind - Message
Origin - Who put a message into the transcript. Policies use this instead of matching text to tell real user input from harness feedback, and providers use it to tell a hook’s per-request note from the transcript.
- Model
Decision - What an
after_modelhook decides about a response. - Model
Error Decision - What an
on_model_errorhook decides about a failed model call. - Nested
Verdict - The run’s answer about a nested call.
- Outbound
- What a call carries out of the machine, for a call that only reads. A fetch changes nothing, yet its URL can carry private data to whoever runs the server, so it counts once the run has read untrusted content.
- Provider
Error - Receipt
Status - Resolution
- How to settle the call an interrupted run is waiting on.
- Response
Format - The shape a reply must take.
- Role
- Who authored a message in the transcript.
- RunStatus
- Why a run ended. Every exit path maps to exactly one variant, so callers never have to parse prose to learn what happened.
- Safeguard
- A safety property every agent with tools must have before it can run.
- Same
Tool Streak - The consecutive-call allowance of a tool: how long a run may call it in a row before the same-tool guard treats the streak as a loop.
- Schedule
- When a service runs (see
ServiceHostfor the exact rules). - Service
Event - What happened to a service. Every
ServiceEvent::Launchedis followed by exactly oneServiceEvent::Endedwith the samerun. - Service
RunEnd - How one run of a service ended.
- Source
Trust - Who authored the content a tool returned.
Untrustedis content someone other than the owner wrote (a web page, an inbound message, a third-party file); it may carry instructions aimed at the model. The default isUntrusted, so a tool that does not say otherwise taints the run. - Stop
Decision - What an
on_stophook decides when the model replies without tool calls. - Stream
Event - One item of a streamed reply. A well-formed stream yields any number of
deltas and ends with exactly one
Donecarrying the complete response. - Stuck
Decision - What to do when the stuck detector fires.
- Stuck
Signal - Switch
Reason - Why a
Failoverchain moved on from a step. - Tool
Choice - How the model may use tools on this call.
- Tool
Decision - What a
before_toolhook decides about one call. - Untrusted
Mode - How strictly the untrusted-content rule applies.
- User
Role - Role assigned to a user based on config (owner_ids).
Constants§
- AUTHORITY_
BLOCKED - Prefix of the reason the
crate::AuthorityHookgives when a call is outside what the run may do. - EGRESS_
BLOCKED - Prefix of the reason an outbound secret scan (the
crate::Safeguard::Egresshook) gives when it refuses a call. - HARD_
TURN_ CAP - Turn cap that applies even if
Limits::max_turnsis set higher. A run that needs more than this is a bug, not a task. - LOAD_
TOOLS - The built-in tool that loads deferred tools.
- OWNER_
DECLINED - Prefix of the reason recorded when the owner declines an approval.
- OWNER_
UNANSWERED - Prefix of the reason for a call whose owner card got no answer (it expired, could not be delivered, or the turn was cancelled). Not a refusal: nothing is remembered as declined.
- RUN_
STATE_ SCHEMA - Version of the
RunStateserialization format this kernel writes and can resume. State saved before the field existed reads as version 1. Bump it when a change would make older saved state resume wrongly, and teachresumeto migrate or refuse the old version. - UNTRUSTED_
BLOCKED - Prefix of the refusal a rejected egress call returns to the model after the run read untrusted content.
- UNTRUSTED_
EGRESS_ INTERRUPT - Prefix of the interruption reason raised by
UntrustedHook.
Traits§
- Authority
Ceiling - A limit on what a run may do that can tighten while the run is in flight,
read before every call.
Nonemeans no extra limit right now. - Event
Sink - Receives events synchronously as they happen. Keep it cheap; forward to a
channel if the consumer is slow. Events carry no timestamps: a sink is
called the moment each happens, so it stamps them with whatever clock it
keeps (receipts carry each call’s
duration_ms, andEvent::Finishedthe run’selapsed_ms). - Failover
Policy - Decides what follows a failed attempt. The default (
DefaultFailover) retries whatProviderError::is_retryableallows on the same step, then moves on; it moves on at once from every other error (another provider may accept what this one refused) and stops only on a context overflow (the caller must shrink the request). A request withcrate::RequestOptions::single_attemptstops at its first error whatever the policy says, unless it also setscrate::RequestOptions::fallback_when_unspentand the error proves the attempt used nothing: then it moves on to the next step. - Hook
- Extension point for every policy. All methods have no-op defaults, so a hook implements only what it needs. Hooks run in registration order and outside the model’s context window: they cost no tokens and the model cannot argue its way past them.
- Interrupt
Resolver - Settles interruptions inside
Agent::run_resolving: a clean-check verifier, an approval UI, a policy.Noneleaves the run interrupted. - Provider
- A model backend. Implementations translate
ModelRequestto their wire format and back. Retries and fallbacks are wrappers (Retry), not loop logic. - RunStore
- Durable home for runs: an append-only event journal plus the latest state snapshot. The loop saves state after every turn and at every exit, so a crash loses at most the turn in flight.
- Service
- Work a
ServiceHostruns in the background. - Service
Gate - Decides whether a tick launches anything.
- Service
Observer - Receives every
ServiceEvent, for logs and dashboards. - Stop
Condition - A custom stop rule, checked with the built-in limits at the top of each
turn. Return
Some(reason)to end the run. Closures implement it. - Tool
- An LLM-callable capability. Only
specandcallare required.
Functions§
- check_
argument_ types check_argumentswithoutrequiredkeys (at any depth): what the kernel enforces for every call whatever the tool’s ownTool::validatesays. Which keys a call may leave out is the tool’s contract (a dispatcher may fill defaults); what a present value is, is not.- check_
arguments - Check
argumentsagainst a tool’s declared JSON schema: an object when the schema says"type": "object", everyrequiredkey present and not null, and each present value of the declaredtype(string,integer(a whole number),number,boolean,array,object,null, or a list of these), within itsenum, with nested objects and array items checked the same way. Anullfor a key that is not required counts as absent. Keywords beyond these are not enforced. - collect_
stream - Drain a stream into its final response. Useful for implementing
completeon a streaming provider. - is_
untrusted_ egress - Whether
interruptionwas raised byUntrustedHook: its kind isInterruptKind::Untrustedand its reason carries the hook’s prefix. - strip_
reserved_ arguments - Minimal schema check: the arguments must be an object containing every
requiredkey. Full JSON Schema validation is left to tools that need it. Drop every top-level argument key starting with_. Those keys are the dispatcher’s (an application passes its own facts to a tool throughToolContext, never through arguments), so a model that sends one is impersonating it. The kernel applies this to every call a model proposes before anything reads it, and the daemon’s dispatcher uses the same function.