rusty_agent_runtime/lib.rs
1//! # Rusty Core
2//!
3//! Rusty Core (the `rusty-agent-runtime` crate) is a LangGraph-style agentic
4//! core engine in Rust. It models
5//! agent workflows as **cyclic graphs over shared state**:
6//!
7//! - **State & channels** ([`state`]): every state key is a *channel* with a
8//! per-key [`state::Reducer`] defining merge semantics. Nodes return partial
9//! updates; the engine merges them via reducers. `LastValue`-style channels
10//! (the default) accept **at most one write per super-step**, otherwise an
11//! [`error::RustyError::InvalidUpdate`] is raised.
12//! - **Nodes** ([`node`]): async functions (or [`node::Node`] trait impls)
13//! receiving a [`node::NodeContext`] (immutable state snapshot + config +
14//! interrupt/resume helpers) and returning a [`node::NodeOutput`] — partial
15//! state updates plus an optional [`node::Command`] for dynamic routing.
16//! - **Graph** ([`graph`]): a thin builder ([`graph::GraphBuilder`]) with
17//! normal edges, conditional edges returning a [`graph::Route`] (including
18//! dynamic fan-out via [`graph::Send`]), and structural validation when
19//! you call [`graph::GraphBuilder::compile`].
20//! - **Execution** ([`executor`]): a Pregel/BSP-inspired super-step loop —
21//! *plan → run active nodes in parallel over an immutable snapshot →
22//! barrier → merge writes via reducers → route → checkpoint* — emitting
23//! [`executor::GraphEvent`]s for streaming.
24//! - **Persistence** ([`checkpoint`]): thread-scoped, versioned snapshots via
25//! the [`checkpoint::Checkpointer`] trait; includes an in-memory saver
26//! and a durable pure-`serde_json` file saver, plus a `postgres`-feature
27//! `PostgresCheckpointer` (see the `checkpoint_postgres` module).
28//! - **LLM & tools** ([`llm`], [`tool`]): a [`llm::ChatModel`] abstraction
29//! with an OpenAI-compatible client, and a [`tool::ToolRegistry`] /
30//! [`tool::ToolExecutor`] for parallel tool-call dispatch — everything
31//! needed for the prebuilt ReAct pattern ([`react`]).
32//! - **MCP** ([`mcp`]): call any MCP server's tools from [`tool::Tool`]
33//! impls over stdio transport; MCP tool servers register into the
34//! registry/executor exactly like native tools.
35//! - **Middleware** ([`middleware`]): ordered interception layers around
36//! node runs, model calls, and tool calls — observe, mutate, reject, or
37//! short-circuit with tower-style onion semantics. Layers attach to the
38//! executor via [`executor::Executor::layer`].
39//! - **Remote nodes** ([`remote`]): a [`remote::RemoteNode`] executes node
40//! work on a remote worker over HTTP behind the same [`node::Node`] trait;
41//! HITL interrupts cross the wire.
42//! - **A2A client** ([`a2a`], R0.9 wave 4): an [`a2a::A2aNode`] delegates a
43//! node's work to a remote A2A agent behind the same [`node::Node`] trait —
44//! journaled as one replay-servable `RemoteCall` event with the derived
45//! `messageId` idempotency handle, replay-served outcomes with no outbound
46//! calls, and `tasks/cancel` propagation on run cancellation.
47//! - **Durable work** ([`durable`]): the shared R0.6 contracts for
48//! effectively-once distributed activities — the [`durable::ErrorClass`]
49//! retry taxonomy, the [`durable::RetryDecision`] policy mapping, and the
50//! serde-versioned [`durable::TaskEnvelope`]. Queue, leases, and workers
51//! live in `rusty-agent-server` / `rusty-worker`; these are the pure contracts
52//! both sides agree on.
53//! - **Agent fabric** ([`agents`], R0.7): the durable-agent
54//! contracts — stable [`agents::AgentId`] identity with its
55//! `agent:{id}` mailbox/thread addressing grammar, the versioned
56//! [`agents::CapabilityManifest`] (accepted message kinds, declared
57//! [`agents::StateScope`]s, budget ceiling), the agent
58//! [`record::RunEventKind`] variants (`AgentSpawn`, `MailboxSend`, …),
59//! and the typed coordination patterns (wave 3:
60//! [`agents::CoordinationContract`] — delegate / fan-out / race /
61//! quorum — with their outcomes and violation vocabulary).
62//! The registry, activation leases, turn-serialized mailbox, and the
63//! pattern runtime live in `rusty-agent-server`; these are the pure contracts
64//! both sides agree on. [`team_trace`] is the read-side half: it
65//! stitches verified journal snapshots back into one cross-journal
66//! causal tree.
67//! - **Effect kernel v2** ([`effects`], R0.7): the R0.5 [`record::Effect`]
68//! taxonomy moved into the type system — marker traits declare an effect's
69//! safety class at compile time, deterministic [`effects::EffectId`]s let
70//! recovery ask whether an effect already committed, and irreversible
71//! effects execute only behind an explicit [`effects::ApprovalToken`].
72//! Opt-in: the untyped [`record::Effect`] path behaves exactly as before.
73//! - **Replay** ([`replay`]): exact replay of journaled runs — model, tool,
74//! remote, and WASM calls are served from the journal instead of executed —
75//! plus branch diffs between journal snapshots and portable
76//! [`replay::ReplayFixture`] bundles for CI.
77//! - **Governed memory** ([`memory`], R0.8 wave 1): the record model
78//! ([`memory::MemoryRecord`] — content-addressed, scoped, attributed,
79//! superseding, expiring), structured retrieval with a token-bounded
80//! deterministic assembly ([`memory::MemoryQuery`] +
81//! [`memory::ContextBudget`]), and the journaled seam: reads are
82//! [`record::RunEventKind::MemoryRead`] ([`record::Effect::ReadOnly`],
83//! served byte-identically by exact replay), writes are
84//! [`record::RunEventKind::MemoryWrite`] ([`record::Effect::Idempotent`]
85//! under a derived key). The store backends and endpoints live in
86//! `rusty-agent-server`; these are the pure contracts both sides agree on.
87//! - **Learning candidates** ([`learn`], R0.8 wave 3): the candidate
88//! pipeline — content-addressed [`learn::Candidate`]s (identity is
89//! integrity), the evaluation composition seam ([`learn::CandidateEvaluator`]
90//! with its replay + experiment + verdict payload), the declared
91//! [`learn::PromotionEnvelope`] and its gate ([`learn::admit_promotion`],
92//! out-of-envelope promotions requiring a scoped
93//! [`effects::ApprovalToken`]), canary binding by seeded draw, and the
94//! active-version pointer with byte-exact rollback. Every transition
95//! journals through the `CandidateCreated` / `CandidateEvaluated` /
96//! `CandidatePromoted` / `CandidateRolledBack` event kinds.
97//! - **WASM nodes** (`wasm_node`, feature `wasm`): sandboxed WebAssembly
98//! modules run as graph nodes via Wasmtime.
99//! - **Rusty Capsules** ([`capsule`], R0.9 wave 1): the content-addressed
100//! [`capsule::CapsuleManifest`] — identity, version, build digest, the
101//! declared WIT-world interface, the closed [`capsule::CapabilityGrant`]
102//! set (the whole reach), and the [`capsule::ResourceBudget`] — plus the
103//! journaled payloads ([`capsule::CapsuleResolution`] /
104//! [`capsule::CapsuleUse`] / [`capsule::CapsuleDenial`]) that make
105//! capability enforcement attributable. The capability host
106//! (`capsule_host`, feature `wasm`) instantiates components against the
107//! declared world with imports linked only where granted — deny by
108//! default, structurally — and the registry resolving `RunManifest`
109//! capsule pins to content addresses lives in `rusty-agent-server`; these are
110//! the pure contracts both sides agree on.
111//! - **Signed run receipts** ([`receipt`], R0.9 wave 3): the Ed25519-signed
112//! [`receipt::RunReceipt`] over the journal head, the run manifest
113//! digests and resolved capsule ids, the effect and denials ledgers, and
114//! the policy versions — plus [`receipt::verify_receipt`], which
115//! re-walks the journal's own digests and answers with a typed
116//! [`receipt::VerifiedRun`] or a [`receipt::ReceiptRejection`] naming the
117//! mismatched component. The key lifecycle (first-boot generation,
118//! journaled rotation, the key history old receipts verify against)
119//! lives in `rusty-agent-server`; these are the pure contracts both sides
120//! agree on.
121//!
122//! ## Quick sketch
123//!
124//! ```no_run
125//! use rusty_agent_runtime::prelude::*;
126//!
127//! # async fn demo() -> Result<()> {
128//! let spec = StateSpec::new().channel("messages", Reducer::AddMessages);
129//!
130//! let mut builder = GraphBuilder::new();
131//! builder.add_node("agent", |ctx: NodeContext| async move {
132//! let _state = ctx.state();
133//! Ok(NodeOutput::update("messages", serde_json::json!({"role": "assistant", "content": "hi"})))
134//! });
135//! builder.set_entry_point("agent");
136//! let graph = builder.compile()?;
137//!
138//! let outcome = Executor::new()
139//! .run(&graph, &spec, State::new(), RunConfig::new("thread-1"))
140//! .await?;
141//! # let _ = outcome;
142//! # Ok(())
143//! # }
144//! ```
145
146pub mod a2a;
147pub mod agents;
148pub mod capsule;
149#[cfg(feature = "wasm")]
150pub mod capsule_host;
151pub mod checkpoint;
152#[cfg(feature = "postgres")]
153pub mod checkpoint_postgres;
154pub mod durable;
155pub mod effects;
156pub mod error;
157pub mod executor;
158pub mod graph;
159pub mod journal;
160pub mod learn;
161pub mod llm;
162pub mod mcp;
163pub mod memory;
164pub mod middleware;
165pub mod node;
166pub mod react;
167pub mod receipt;
168pub mod record;
169pub mod remote;
170pub mod replay;
171pub mod state;
172pub mod team_trace;
173pub mod tool;
174#[cfg(feature = "wasm")]
175pub mod wasm_node;
176
177/// Convenience re-exports of the main public API.
178pub mod prelude {
179 pub use crate::a2a::{A2aNode, A2A_PROTOCOL_VERSION};
180 pub use crate::agents::{
181 agent_id_from_recipient, AgentBudget, AgentId, CapabilityManifest, ContextGrant,
182 CoordinationContract, CoordinationKind, CoordinationMessage, CoordinationOutcome,
183 CoordinationStatus, CoordinationViolation, DelegateContract, Delegation, EscalationNotice,
184 FanOutContract, MemberDisposition, MemberFailurePolicy, MemberSettlement, QuorumContract,
185 QuorumOutcome, QuorumResolver, QuorumResolverRecord, QuorumTally, RaceContract,
186 RestartPolicy, StateScope, SupervisionAttempt, SupervisionPolicy, SupervisionTrigger,
187 AGENT_RECIPIENT_PREFIX, COORDINATION_RESULT_KIND, ESCALATION_MESSAGE_KIND,
188 };
189 pub use crate::capsule::{
190 any_grant_of_kind, derive_capsule_id, network_grant_covers, CapabilityGrant,
191 CapabilityKind, CapsuleDenial, CapsuleId, CapsuleIdentity, CapsuleInterface,
192 CapsuleManifest, CapsuleResolution, CapsuleUse, FilesystemMode, ResourceBudget,
193 SUPPORTED_WORLDS, WORLD_V1,
194 };
195 pub use crate::checkpoint::{
196 Checkpoint, Checkpointer, InMemoryCheckpointer, JsonFileCheckpointer,
197 };
198 #[cfg(feature = "postgres")]
199 pub use crate::checkpoint_postgres::PostgresCheckpointer;
200 pub use crate::durable::{
201 backoff_delay_ms, classify_retry, retry_decision_event, retry_legal_actions,
202 retry_selected_action, ArtifactContract, ErrorClass, RetryDecision, TaskBudget,
203 TaskEnvelope, BASE_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, TASK_ENVELOPE_FORMAT_VERSION,
204 };
205 pub use crate::effects::{
206 admit_compensatable, admit_irreversible, admit_retry, admit_speculation, derive_effect_id,
207 ApprovalToken, CompensatableEffect, CompensationHandler, CompensationRegistry, EffectId,
208 EffectViolation, IdempotentEffect, IrreversibleEffect, PureEffect, ReadOnlyEffect,
209 TypedEffect, EFFECT_ID_DOMAIN,
210 };
211 pub use crate::error::{Result, RustyError};
212 pub use crate::executor::{ExecutionOutcome, Executor, GraphEvent, RunConfig};
213 pub use crate::graph::{ConditionalRouter, Edge, Graph, GraphBuilder, Route, Send};
214 pub use crate::journal::{
215 Clock, EventDraft, Journal, JournalSnapshot, RngSource, PARENT_EVENT_KEY,
216 };
217 pub use crate::learn::{
218 admit_promotion, canary_admits, candidate_effect_key, derive_candidate_id,
219 evaluation_effect_key, promotion_effect_id, promotion_effect_key, rollback_effect_key,
220 AutoPromotion, CanaryBinding, Candidate, CandidateContent, CandidateEvaluation,
221 CandidateEvaluator, CandidateId, CandidateKind, CandidateOverlay, CandidateRecord,
222 CandidateStatus, EnvelopeRule, EvaluationRequest, EvaluationThresholds, EvaluationVerdict,
223 EvidenceSpan, GrantDirection, LearnError, PromotionAuthority, PromotionDecision,
224 PromotionEnvelope, PromotionReceipt, PromotionRefusal, ReplayDivergence, ReplaySummary,
225 RollbackReceipt, SurfaceKey, VersionPointer, CANARY_DRAW_DOMAIN, PROMOTION_EFFECT_KIND,
226 };
227 pub use crate::llm::{
228 ChatMessage, ChatModel, ChatResponse, OpenAiCompatibleClient, Role, ToolCall, Usage,
229 };
230 pub use crate::memory::{
231 apply_query, assemble, derive_memory_id, estimated_tokens, memory_effect_key,
232 memory_read_request, BudgetOverflow, ContextBudget, InMemoryMemoryStore, JournaledMemory,
233 MemoryAssembly, MemoryEvidence, MemoryKind, MemoryProvenance, MemoryQuery, MemoryRecord,
234 MemoryReplaySource, MemoryScope, MemorySource, MemoryStore, ProvenanceAuthor, ScopeAddress,
235 TokenAccounting, ValidityWindow, DEFAULT_TOKEN_MARGIN_PERCENT, MEMORY_SCHEMA_VERSION,
236 TOKEN_BYTES_PER_ESTIMATE,
237 };
238 pub use crate::middleware::{
239 Decision, InterceptPoint, Middleware, MiddlewareChain, MiddlewareChatModel, ModelCall,
240 NodeCall, Rejection, RequestLogger, ToolCallBlocklist, ToolInvocation,
241 };
242 pub use crate::node::{Command, Node, NodeConfig, NodeContext, NodeOutput};
243 pub use crate::react::{
244 create_react_agent, create_react_agent_replaying, create_react_agent_streaming,
245 create_react_agent_with_recording,
246 };
247 pub use crate::receipt::{
248 derive_key_id, manifest_digest, mint_receipt, verify_receipt, PublicKey, ReceiptRejection,
249 RunReceipt, SigningKey, SigningKeyRotation, VerifiedRun, RECEIPT_FORMAT_VERSION,
250 };
251 pub use crate::record::{
252 derive_policy_version, ArtifactRef, CapsuleVersion, CheckpointHeader,
253 ConcurrencyPolicyParameters, DecisionAction, DecisionEvent, DecisionFamily,
254 DecisionOutcome, Effect, EffectReceipt, EventStatus, ExecutorPolicy, JournalRef,
255 PayloadRef, PolicyVersion, RetryPolicyParameters, RunEvent, RunEventKind, RunManifest,
256 TimeoutPolicyParameters, CURRENT_FORMAT_VERSION,
257 };
258 pub use crate::replay::{
259 BranchDiff, BranchTotals, ChannelDiff, ExactReplay, FixtureMetadata, LogicalClockParams,
260 RecordingChatModel, RecordingTool, ReplayFixture, ReplayOutcome, ReplayParams,
261 ReplaySource, ReplayingChatModel, ReplayingTool, ServedEffect, StepDiff,
262 FIXTURE_FORMAT_VERSION,
263 };
264 pub use crate::state::{Reducer, State, StateSpec};
265 pub use crate::team_trace::{TeamTrace, TeamTraceNode};
266 pub use crate::tool::{Tool, ToolExecutor, ToolRegistry};
267}