Skip to main content

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//! - **The runtime digital twin** ([`twin`], R0.10 wave 2): deterministic
78//!   re-execution of recorded runs that answers what plain replay cannot —
79//!   seeded [`twin::FaultSchedule`]s landing at decision points and the
80//!   effect boundary, seeded schedule randomization of each super-step's
81//!   parallel task set, counterfactual branches over one changed decision
82//!   compared as [`replay::BranchDiff`] evidence, and shadow policies whose
83//!   decisions journal with roles and propensities alongside the acting
84//!   floor's. Bounded by the honest edge: only decisions that change *when
85//!   and whether* effects execute are evaluable, and every
86//!   [`twin::TwinReport`] says so.
87//! - **Governed memory** ([`memory`], R0.8 wave 1): the record model
88//!   ([`memory::MemoryRecord`] — content-addressed, scoped, attributed,
89//!   superseding, expiring), structured retrieval with a token-bounded
90//!   deterministic assembly ([`memory::MemoryQuery`] +
91//!   [`memory::ContextBudget`]), and the journaled seam: reads are
92//!   [`record::RunEventKind::MemoryRead`] ([`record::Effect::ReadOnly`],
93//!   served byte-identically by exact replay), writes are
94//!   [`record::RunEventKind::MemoryWrite`] ([`record::Effect::Idempotent`]
95//!   under a derived key). The store backends and endpoints live in
96//!   `rusty-agent-server`; these are the pure contracts both sides agree on.
97//! - **Learning candidates** ([`learn`], R0.8 wave 3): the candidate
98//!   pipeline — content-addressed [`learn::Candidate`]s (identity is
99//!   integrity), the evaluation composition seam ([`learn::CandidateEvaluator`]
100//!   with its replay + experiment + verdict payload), the declared
101//!   [`learn::PromotionEnvelope`] and its gate ([`learn::admit_promotion`],
102//!   out-of-envelope promotions requiring a scoped
103//!   [`effects::ApprovalToken`]), canary binding by seeded draw, and the
104//!   active-version pointer with byte-exact rollback. Every transition
105//!   journals through the `CandidateCreated` / `CandidateEvaluated` /
106//!   `CandidatePromoted` / `CandidateRolledBack` event kinds.
107//! - **WASM nodes** (`wasm_node`, feature `wasm`): sandboxed WebAssembly
108//!   modules run as graph nodes via Wasmtime.
109//! - **Rusty Capsules** ([`capsule`], R0.9 wave 1): the content-addressed
110//!   [`capsule::CapsuleManifest`] — identity, version, build digest, the
111//!   declared WIT-world interface, the closed [`capsule::CapabilityGrant`]
112//!   set (the whole reach), and the [`capsule::ResourceBudget`] — plus the
113//!   journaled payloads ([`capsule::CapsuleResolution`] /
114//!   [`capsule::CapsuleUse`] / [`capsule::CapsuleDenial`]) that make
115//!   capability enforcement attributable. The capability host
116//!   (`capsule_host`, feature `wasm`) instantiates components against the
117//!   declared world with imports linked only where granted — deny by
118//!   default, structurally — and the registry resolving `RunManifest`
119//!   capsule pins to content addresses lives in `rusty-agent-server`; these are
120//!   the pure contracts both sides agree on.
121//! - **Signed run receipts** ([`receipt`], R0.9 wave 3): the Ed25519-signed
122//!   [`receipt::RunReceipt`] over the journal head, the run manifest
123//!   digests and resolved capsule ids, the effect and denials ledgers, and
124//!   the policy versions — plus [`receipt::verify_receipt`], which
125//!   re-walks the journal's own digests and answers with a typed
126//!   [`receipt::VerifiedRun`] or a [`receipt::ReceiptRejection`] naming the
127//!   mismatched component. The key lifecycle (first-boot generation,
128//!   journaled rotation, the key history old receipts verify against)
129//!   lives in `rusty-agent-server`; these are the pure contracts both sides
130//!   agree on.
131//!
132//! ## Quick sketch
133//!
134//! ```no_run
135//! use rusty_agent_runtime::prelude::*;
136//!
137//! # async fn demo() -> Result<()> {
138//! let spec = StateSpec::new().channel("messages", Reducer::AddMessages);
139//!
140//! let mut builder = GraphBuilder::new();
141//! builder.add_node("agent", |ctx: NodeContext| async move {
142//!     let _state = ctx.state();
143//!     Ok(NodeOutput::update("messages", serde_json::json!({"role": "assistant", "content": "hi"})))
144//! });
145//! builder.set_entry_point("agent");
146//! let graph = builder.compile()?;
147//!
148//! let outcome = Executor::new()
149//!     .run(&graph, &spec, State::new(), RunConfig::new("thread-1"))
150//!     .await?;
151//! # let _ = outcome;
152//! # Ok(())
153//! # }
154//! ```
155
156pub mod a2a;
157pub mod agents;
158pub mod capsule;
159#[cfg(feature = "wasm")]
160pub mod capsule_host;
161pub mod checkpoint;
162#[cfg(feature = "postgres")]
163pub mod checkpoint_postgres;
164pub mod durable;
165pub mod effects;
166pub mod error;
167pub mod executor;
168pub mod graph;
169pub mod journal;
170pub mod learn;
171pub mod llm;
172pub mod mcp;
173pub mod memory;
174pub mod middleware;
175pub mod node;
176pub mod react;
177pub mod receipt;
178pub mod record;
179pub mod remote;
180pub mod replay;
181pub mod state;
182pub mod team_trace;
183pub mod tool;
184pub mod twin;
185#[cfg(feature = "wasm")]
186pub mod wasm_node;
187
188/// Convenience re-exports of the main public API.
189pub mod prelude {
190    pub use crate::a2a::{A2aNode, A2A_PROTOCOL_VERSION};
191    pub use crate::agents::{
192        agent_id_from_recipient, AgentBudget, AgentId, CapabilityManifest, ContextGrant,
193        CoordinationContract, CoordinationKind, CoordinationMessage, CoordinationOutcome,
194        CoordinationStatus, CoordinationViolation, DelegateContract, Delegation, EscalationNotice,
195        FanOutContract, MemberDisposition, MemberFailurePolicy, MemberSettlement, QuorumContract,
196        QuorumOutcome, QuorumResolver, QuorumResolverRecord, QuorumTally, RaceContract,
197        RestartPolicy, StateScope, SupervisionAttempt, SupervisionPolicy, SupervisionTrigger,
198        AGENT_RECIPIENT_PREFIX, COORDINATION_RESULT_KIND, ESCALATION_MESSAGE_KIND,
199    };
200    pub use crate::capsule::{
201        any_grant_of_kind, derive_capsule_id, network_grant_covers, CapabilityGrant,
202        CapabilityKind, CapsuleDenial, CapsuleId, CapsuleIdentity, CapsuleInterface,
203        CapsuleManifest, CapsuleResolution, CapsuleUse, FilesystemMode, ResourceBudget,
204        SUPPORTED_WORLDS, WORLD_V1,
205    };
206    pub use crate::checkpoint::{
207        Checkpoint, Checkpointer, InMemoryCheckpointer, JsonFileCheckpointer,
208    };
209    #[cfg(feature = "postgres")]
210    pub use crate::checkpoint_postgres::PostgresCheckpointer;
211    pub use crate::durable::{
212        backoff_delay_ms, backoff_delay_ms_with, classify_retry, classify_retry_with_policy,
213        resolve_retry_parameters, resolve_timeout_bound_ms, retry_decision_event,
214        retry_legal_actions, retry_selected_action, timeout_decision_event, timeout_legal_actions,
215        timeout_selected_action, ArtifactContract, ErrorClass, LatencyPercentiles,
216        ResolvedRetryParameters, RetryDecision, TaskBudget, TaskEnvelope, BASE_RETRY_DELAY_MS,
217        MAX_RETRY_DELAY_MS, TASK_ENVELOPE_FORMAT_VERSION,
218    };
219    pub use crate::effects::{
220        admit_compensatable, admit_irreversible, admit_retry, admit_speculation, derive_effect_id,
221        ApprovalToken, CompensatableEffect, CompensationHandler, CompensationRegistry, EffectId,
222        EffectViolation, IdempotentEffect, IrreversibleEffect, PureEffect, ReadOnlyEffect,
223        TypedEffect, EFFECT_ID_DOMAIN,
224    };
225    pub use crate::error::{Result, RustyError};
226    pub use crate::executor::{ExecutionOutcome, Executor, GraphEvent, RunConfig};
227    pub use crate::graph::{ConditionalRouter, Edge, Graph, GraphBuilder, Route, Send};
228    pub use crate::journal::{
229        Clock, EventDraft, Journal, JournalSnapshot, RngSource, PARENT_EVENT_KEY,
230    };
231    pub use crate::learn::{
232        admit_promotion, canary_admits, candidate_effect_key, derive_candidate_id,
233        detect_policy_drift, distill_retry_parameters, distill_timeout_parameters,
234        evaluation_effect_key, promotion_effect_id, promotion_effect_key, rollback_effect_key,
235        AutoPromotion, CanaryBinding, Candidate, CandidateContent, CandidateEvaluation,
236        CandidateEvaluator, CandidateId, CandidateKind, CandidateOverlay, CandidateRecord,
237        CandidateStatus, DriftBaseline, DriftThresholds, EnvelopeRule, EvaluationRequest,
238        EvaluationThresholds, EvaluationVerdict, EvidenceSpan, GrantDirection, LearnError,
239        PolicyDriftReport, PromotionAuthority, PromotionDecision, PromotionEnvelope,
240        PromotionReceipt, PromotionRefusal, ReplayDivergence, ReplaySummary, RetryLearningConfig,
241        RollbackReceipt, SurfaceKey, TimeoutLearningConfig, TwinCandidateEvaluator, VersionPointer,
242        CANARY_DRAW_DOMAIN, PROMOTION_EFFECT_KIND,
243    };
244    pub use crate::llm::{
245        ChatMessage, ChatModel, ChatResponse, OpenAiCompatibleClient, Role, ToolCall, Usage,
246    };
247    pub use crate::memory::{
248        apply_query, assemble, derive_memory_id, estimated_tokens, memory_effect_key,
249        memory_read_request, BudgetOverflow, ContextBudget, InMemoryMemoryStore, JournaledMemory,
250        MemoryAssembly, MemoryEvidence, MemoryKind, MemoryProvenance, MemoryQuery, MemoryRecord,
251        MemoryReplaySource, MemoryScope, MemorySource, MemoryStore, ProvenanceAuthor, ScopeAddress,
252        TokenAccounting, ValidityWindow, DEFAULT_TOKEN_MARGIN_PERCENT, MEMORY_SCHEMA_VERSION,
253        TOKEN_BYTES_PER_ESTIMATE,
254    };
255    pub use crate::middleware::{
256        Decision, InterceptPoint, Middleware, MiddlewareChain, MiddlewareChatModel, ModelCall,
257        NodeCall, Rejection, RequestLogger, ToolCallBlocklist, ToolInvocation,
258    };
259    pub use crate::node::{Command, Node, NodeConfig, NodeContext, NodeOutput};
260    pub use crate::react::{
261        create_react_agent, create_react_agent_replaying, create_react_agent_streaming,
262        create_react_agent_with_recording,
263    };
264    pub use crate::receipt::{
265        derive_key_id, manifest_digest, mint_receipt, verify_receipt, PublicKey, ReceiptRejection,
266        RunReceipt, SigningKey, SigningKeyRotation, VerifiedRun, RECEIPT_FORMAT_VERSION,
267    };
268    pub use crate::record::{
269        derive_policy_version, ArtifactRef, BackoffParameters, CapsuleVersion, CheckpointHeader,
270        ConcurrencyPolicyParameters, DecisionAction, DecisionEvent, DecisionFamily,
271        DecisionOutcome, DecisionRole, Effect, EffectReceipt, EventStatus, ExecutorPolicy,
272        JournalRef, PayloadRef, PolicyVersion, RetryPolicyParameters, RunEvent, RunEventKind,
273        RunManifest, TimeoutPolicyParameters, CURRENT_FORMAT_VERSION, POLICY_MAX_ATTEMPTS_ENVELOPE,
274        POLICY_MAX_DELAY_ENVELOPE_MS,
275    };
276    pub use crate::replay::{
277        BranchDiff, BranchTotals, ChannelDiff, ExactReplay, FixtureMetadata, LogicalClockParams,
278        RecordingChatModel, RecordingTool, ReplayFixture, ReplayOutcome, ReplayParams,
279        ReplaySource, ReplayingChatModel, ReplayingTool, ServedEffect, StepDiff,
280        FIXTURE_FORMAT_VERSION,
281    };
282    pub use crate::state::{Reducer, State, StateSpec};
283    pub use crate::team_trace::{TeamTrace, TeamTraceNode};
284    pub use crate::tool::{Tool, ToolExecutor, ToolRegistry};
285    pub use crate::twin::{
286        CounterfactualBranch, CounterfactualFork, DecisionContext, FaultAnchor, FaultInjection,
287        FaultSchedule, InjectedFault, Interleaving, ParameterizedPolicy, RecordedAnswer,
288        StaticFloor, Twin, TwinMetrics, TwinOutcome, TwinPolicy, TwinReport, TwinRunConfig,
289        TwinWorkItem, TwinWorld, UnevaluableCase, DEFAULT_CONCURRENCY_LADDER,
290        DEFAULT_TIMEOUT_LADDER, MIN_TIMEOUT_RUNG_MS, TWIN_FORK_POLICY_VERSION, TWIN_REPORT_BOUND,
291    };
292}