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//! - **The configuration registry** ([`registry`], R0.11): the
108//! prompt/configuration registry — named, owned [`registry::ArtifactRecord`]s
109//! indexing the candidate pipeline (a commit *is* a candidate, never a fork
110//! of it), environment tags on surface keys ([`learn::EnvironmentTag`]) so
111//! one deployment promotes per environment through the unchanged pointer
112//! machinery, [`registry::diff_candidates`] views computed on read,
113//! never stored, and admission-time resolution (wave 2): a run's named
114//! artifacts bind through the tagged version pointer to a candidate
115//! ([`registry::pointer_admission`]) whose content the manifest pins by
116//! digest, the digest ↔ version join journaled as
117//! [`registry::ConfigResolution`]. The store backends and endpoints live in
118//! `rusty-agent-server`; these are the pure contracts both sides agree on.
119//! - **The credential/connection broker** ([`broker`], R0.11 wave 3): no
120//! tool ever holds a raw credential. The connection entity
121//! ([`broker::ConnectionRecord`] — consent scope set as the ceiling
122//! everything narrows against, status, health), the sealed-storage shape
123//! ([`broker::StoredConnection`] — ciphertext and a wrapped data key
124//! only, plaintext on neither backend ever), and the handle lifecycle:
125//! short-lived, opaque, non-serializable [`broker::CredentialHandle`]s
126//! whose validity is self-contained in signed claims while revocation
127//! reads live connection state at every resolution — a revoked
128//! connection fails closed at the next tool call with a typed,
129//! journaled [`broker::BrokerDenial`]. [`broker::CredentialMediator`] /
130//! [`broker::MediatedTool`] mediate `ToolExecutor` dispatch, and behind
131//! `wasm` [`broker::BrokeredCapsuleHost`] turns capsule `Secret`
132//! grants into broker-issued handles; in both, resolution returns the
133//! credential bytes to the host-side connector, never to tool code.
134//! The store backends, envelope cryptography, master key, and
135//! endpoints live in `rusty-agent-server`; these are the pure
136//! contracts both sides agree on.
137//! - **WASM nodes** (`wasm_node`, feature `wasm`): sandboxed WebAssembly
138//! modules run as graph nodes via Wasmtime.
139//! - **Rusty Capsules** ([`capsule`], R0.9 wave 1): the content-addressed
140//! [`capsule::CapsuleManifest`] — identity, version, build digest, the
141//! declared WIT-world interface, the closed [`capsule::CapabilityGrant`]
142//! set (the whole reach), and the [`capsule::ResourceBudget`] — plus the
143//! journaled payloads ([`capsule::CapsuleResolution`] /
144//! [`capsule::CapsuleUse`] / [`capsule::CapsuleDenial`]) that make
145//! capability enforcement attributable. The capability host
146//! (`capsule_host`, feature `wasm`) instantiates components against the
147//! declared world with imports linked only where granted — deny by
148//! default, structurally — and the registry resolving `RunManifest`
149//! capsule pins to content addresses lives in `rusty-agent-server`; these are
150//! the pure contracts both sides agree on.
151//! - **Signed run receipts** ([`receipt`], R0.9 wave 3): the Ed25519-signed
152//! [`receipt::RunReceipt`] over the journal head, the run manifest
153//! digests and resolved capsule ids, the effect and denials ledgers, and
154//! the policy versions — plus [`receipt::verify_receipt`], which
155//! re-walks the journal's own digests and answers with a typed
156//! [`receipt::VerifiedRun`] or a [`receipt::ReceiptRejection`] naming the
157//! mismatched component. The key lifecycle (first-boot generation,
158//! journaled rotation, the key history old receipts verify against)
159//! lives in `rusty-agent-server`; these are the pure contracts both sides
160//! agree on.
161//!
162//! ## Quick sketch
163//!
164//! ```no_run
165//! use rusty_agent_runtime::prelude::*;
166//!
167//! # async fn demo() -> Result<()> {
168//! let spec = StateSpec::new().channel("messages", Reducer::AddMessages);
169//!
170//! let mut builder = GraphBuilder::new();
171//! builder.add_node("agent", |ctx: NodeContext| async move {
172//! let _state = ctx.state();
173//! Ok(NodeOutput::update("messages", serde_json::json!({"role": "assistant", "content": "hi"})))
174//! });
175//! builder.set_entry_point("agent");
176//! let graph = builder.compile()?;
177//!
178//! let outcome = Executor::new()
179//! .run(&graph, &spec, State::new(), RunConfig::new("thread-1"))
180//! .await?;
181//! # let _ = outcome;
182//! # Ok(())
183//! # }
184//! ```
185
186pub mod a2a;
187pub mod agents;
188pub mod broker;
189pub mod capsule;
190#[cfg(feature = "wasm")]
191pub mod capsule_host;
192pub mod checkpoint;
193#[cfg(feature = "postgres")]
194pub mod checkpoint_postgres;
195pub mod durable;
196pub mod effects;
197pub mod error;
198pub mod executor;
199pub mod graph;
200pub mod journal;
201pub mod learn;
202pub mod llm;
203pub mod mcp;
204pub mod memory;
205pub mod middleware;
206pub mod node;
207pub mod react;
208pub mod receipt;
209pub mod record;
210pub mod registry;
211pub mod remote;
212pub mod replay;
213pub mod state;
214pub mod team_trace;
215pub mod tool;
216pub mod twin;
217#[cfg(feature = "wasm")]
218pub mod wasm_node;
219
220/// Convenience re-exports of the main public API.
221pub mod prelude {
222 pub use crate::a2a::{A2aNode, A2A_PROTOCOL_VERSION};
223 pub use crate::agents::{
224 agent_id_from_recipient, AgentBudget, AgentId, CapabilityManifest, ContextGrant,
225 CoordinationContract, CoordinationKind, CoordinationMessage, CoordinationOutcome,
226 CoordinationStatus, CoordinationViolation, DelegateContract, Delegation, EscalationNotice,
227 FanOutContract, MemberDisposition, MemberFailurePolicy, MemberSettlement, QuorumContract,
228 QuorumOutcome, QuorumResolver, QuorumResolverRecord, QuorumTally, RaceContract,
229 RestartPolicy, StateScope, SupervisionAttempt, SupervisionPolicy, SupervisionTrigger,
230 AGENT_RECIPIENT_PREFIX, COORDINATION_RESULT_KIND, ESCALATION_MESSAGE_KIND,
231 };
232 #[cfg(feature = "wasm")]
233 pub use crate::broker::BrokeredCapsuleHost;
234 pub use crate::broker::{
235 new_connection_id, new_handle_id, scopes_missing, BrokerDenial, BrokerDenialReason,
236 ClassifiedFailure, ConnectionConsent, ConnectionHealth, ConnectionProvider,
237 ConnectionReauthRequired, ConnectionRecord, ConnectionRefresh, ConnectionRevocation,
238 ConnectionStatus, CredentialBroker, CredentialHandle, CredentialMediator,
239 CredentialRequirement, CredentialTool, CredentialUse, HandleClaims, HandleIssuance,
240 IssueRequest, MediatedTool, OAuthFailure, OAuthProvider, ResolvedCredential,
241 ScriptedOAuthProvider, SealedCredential, StoredConnection, TokenGrant, TokenMaterial,
242 CONNECTION_ID_PREFIX, HANDLE_ID_PREFIX, HANDLE_TOKEN_PREFIX, SEALED_FORMAT_VERSION,
243 };
244 pub use crate::capsule::{
245 any_grant_of_kind, derive_capsule_id, network_grant_covers, CapabilityGrant,
246 CapabilityKind, CapsuleDenial, CapsuleId, CapsuleIdentity, CapsuleInterface,
247 CapsuleManifest, CapsuleResolution, CapsuleUse, FilesystemMode, ResourceBudget,
248 SUPPORTED_WORLDS, WORLD_V1,
249 };
250 pub use crate::checkpoint::{
251 Checkpoint, Checkpointer, InMemoryCheckpointer, JsonFileCheckpointer,
252 };
253 #[cfg(feature = "postgres")]
254 pub use crate::checkpoint_postgres::PostgresCheckpointer;
255 pub use crate::durable::{
256 backoff_delay_ms, backoff_delay_ms_with, classify_retry, classify_retry_with_policy,
257 resolve_retry_parameters, resolve_timeout_bound_ms, retry_decision_event,
258 retry_legal_actions, retry_selected_action, timeout_decision_event, timeout_legal_actions,
259 timeout_selected_action, ArtifactContract, ErrorClass, LatencyPercentiles,
260 ResolvedRetryParameters, RetryDecision, TaskBudget, TaskEnvelope, BASE_RETRY_DELAY_MS,
261 MAX_RETRY_DELAY_MS, TASK_ENVELOPE_FORMAT_VERSION,
262 };
263 pub use crate::effects::{
264 admit_compensatable, admit_irreversible, admit_retry, admit_speculation, derive_effect_id,
265 ApprovalToken, CompensatableEffect, CompensationHandler, CompensationRegistry, EffectId,
266 EffectViolation, IdempotentEffect, IrreversibleEffect, PureEffect, ReadOnlyEffect,
267 TypedEffect, EFFECT_ID_DOMAIN,
268 };
269 pub use crate::error::{Result, RustyError};
270 pub use crate::executor::{ExecutionOutcome, Executor, GraphEvent, RunConfig};
271 pub use crate::graph::{ConditionalRouter, Edge, Graph, GraphBuilder, Route, Send};
272 pub use crate::journal::{
273 Clock, EventDraft, Journal, JournalSnapshot, RngSource, PARENT_EVENT_KEY,
274 };
275 pub use crate::learn::{
276 admit_promotion, canary_admits, candidate_effect_key, derive_candidate_id,
277 detect_policy_drift, distill_retry_parameters, distill_timeout_parameters,
278 evaluation_effect_key, promotion_effect_id, promotion_effect_key, rollback_effect_key,
279 surface_for_kind, AutoPromotion, CanaryBinding, Candidate, CandidateContent,
280 CandidateEvaluation, CandidateEvaluator, CandidateId, CandidateKind, CandidateOverlay,
281 CandidateRecord, CandidateStatus, DriftBaseline, DriftThresholds, EnvelopeRule,
282 EnvironmentTag, EvaluationRequest, EvaluationThresholds, EvaluationVerdict, EvidenceSpan,
283 GrantDirection, LearnError, MiddlewareLayerConfig, PolicyDriftReport, PromotionAuthority,
284 PromotionDecision, PromotionEnvelope, PromotionReceipt, PromotionRefusal, ReplayDivergence,
285 ReplaySummary, RetryLearningConfig, RollbackReceipt, SurfaceKey, TimeoutLearningConfig,
286 TwinCandidateEvaluator, VersionPointer, CANARY_DRAW_DOMAIN, PROMOTION_EFFECT_KIND,
287 SURFACE_TAG_SEPARATOR,
288 };
289 pub use crate::llm::{
290 ChatMessage, ChatModel, ChatResponse, OpenAiCompatibleClient, Role, ToolCall, Usage,
291 };
292 pub use crate::memory::{
293 apply_query, assemble, derive_memory_id, estimated_tokens, memory_effect_key,
294 memory_read_request, BudgetOverflow, ContextBudget, InMemoryMemoryStore, JournaledMemory,
295 MemoryAssembly, MemoryEvidence, MemoryKind, MemoryProvenance, MemoryQuery, MemoryRecord,
296 MemoryReplaySource, MemoryScope, MemorySource, MemoryStore, ProvenanceAuthor, ScopeAddress,
297 TokenAccounting, ValidityWindow, DEFAULT_TOKEN_MARGIN_PERCENT, MEMORY_SCHEMA_VERSION,
298 TOKEN_BYTES_PER_ESTIMATE,
299 };
300 pub use crate::middleware::{
301 instantiate_composition, Decision, InterceptPoint, Middleware, MiddlewareChain,
302 MiddlewareChatModel, ModelCall, NodeCall, Rejection, RequestLogger, ToolCallBlocklist,
303 ToolInvocation,
304 };
305 pub use crate::node::{Command, Node, NodeConfig, NodeContext, NodeOutput};
306 pub use crate::react::{
307 create_react_agent, create_react_agent_replaying, create_react_agent_streaming,
308 create_react_agent_with_recording,
309 };
310 pub use crate::receipt::{
311 derive_key_id, manifest_digest, mint_receipt, verify_receipt, PublicKey, ReceiptRejection,
312 RunReceipt, SigningKey, SigningKeyRotation, VerifiedRun, RECEIPT_FORMAT_VERSION,
313 };
314 pub use crate::record::{
315 derive_policy_version, ArtifactRef, BackoffParameters, CapsuleVersion, CheckpointHeader,
316 ConcurrencyPolicyParameters, DecisionAction, DecisionEvent, DecisionFamily,
317 DecisionOutcome, DecisionRole, Effect, EffectReceipt, EventStatus, ExecutorPolicy,
318 JournalRef, PayloadRef, PolicyVersion, RetryPolicyParameters, RunEvent, RunEventKind,
319 RunManifest, TimeoutPolicyParameters, CURRENT_FORMAT_VERSION, POLICY_MAX_ATTEMPTS_ENVELOPE,
320 POLICY_MAX_DELAY_ENVELOPE_MS,
321 };
322 pub use crate::registry::{
323 diff_candidates, pointer_admission, resolution_pin, ArtifactCommit, ArtifactRecord,
324 ConfigResolution, LeafChange, LeafModification, PointerBinding, RegistryDiff,
325 RegistryError, TextDiffLine, MAX_ARTIFACT_NAME_LEN,
326 };
327 pub use crate::replay::{
328 BranchDiff, BranchTotals, ChannelDiff, ExactReplay, FixtureMetadata, LogicalClockParams,
329 RecordingChatModel, RecordingTool, ReplayFixture, ReplayOutcome, ReplayParams,
330 ReplaySource, ReplayingChatModel, ReplayingTool, ServedEffect, StepDiff,
331 FIXTURE_FORMAT_VERSION,
332 };
333 pub use crate::state::{Reducer, State, StateSpec};
334 pub use crate::team_trace::{TeamTrace, TeamTraceNode};
335 pub use crate::tool::{Tool, ToolExecutor, ToolRegistry};
336 pub use crate::twin::{
337 CounterfactualBranch, CounterfactualFork, DecisionContext, FaultAnchor, FaultInjection,
338 FaultSchedule, InjectedFault, Interleaving, ParameterizedPolicy, RecordedAnswer,
339 StaticFloor, Twin, TwinMetrics, TwinOutcome, TwinPolicy, TwinReport, TwinRunConfig,
340 TwinWorkItem, TwinWorld, UnevaluableCase, DEFAULT_CONCURRENCY_LADDER,
341 DEFAULT_TIMEOUT_LADDER, MIN_TIMEOUT_RUNG_MS, TWIN_FORK_POLICY_VERSION, TWIN_REPORT_BOUND,
342 };
343}