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 artifact;
189pub mod broker;
190pub mod capsule;
191#[cfg(feature = "wasm")]
192pub mod capsule_host;
193pub mod checkpoint;
194#[cfg(feature = "postgres")]
195pub mod checkpoint_postgres;
196pub mod deploy;
197pub mod durable;
198pub mod effects;
199pub mod error;
200pub mod executor;
201pub mod graph;
202pub mod journal;
203pub mod learn;
204pub mod llm;
205pub mod mcp;
206pub mod memory;
207pub mod middleware;
208pub mod node;
209pub mod react;
210pub mod receipt;
211pub mod record;
212pub mod registry;
213pub mod remote;
214pub mod replay;
215pub mod state;
216pub mod team_trace;
217pub mod tool;
218pub mod twin;
219#[cfg(feature = "wasm")]
220pub mod wasm_node;
221
222/// Convenience re-exports of the main public API.
223pub mod prelude {
224 pub use crate::a2a::{A2aNode, A2A_PROTOCOL_VERSION};
225 pub use crate::agents::{
226 agent_id_from_recipient, AgentBudget, AgentId, CapabilityManifest, ContextGrant,
227 CoordinationContract, CoordinationKind, CoordinationMessage, CoordinationOutcome,
228 CoordinationStatus, CoordinationViolation, DelegateContract, Delegation, EscalationNotice,
229 FanOutContract, MemberDisposition, MemberFailurePolicy, MemberSettlement, QuorumContract,
230 QuorumOutcome, QuorumResolver, QuorumResolverRecord, QuorumTally, RaceContract,
231 RestartPolicy, StateScope, SupervisionAttempt, SupervisionPolicy, SupervisionTrigger,
232 AGENT_RECIPIENT_PREFIX, COORDINATION_RESULT_KIND, ESCALATION_MESSAGE_KIND,
233 };
234 pub use crate::artifact::{
235 commit_artifact, ArtifactCommitment, ArtifactError, ArtifactLineage, ArtifactVersion,
236 CommitDeclaration, MediaKind, RetentionPolicy, RunArtifact,
237 };
238 #[cfg(feature = "wasm")]
239 pub use crate::broker::BrokeredCapsuleHost;
240 pub use crate::broker::{
241 new_connection_id, new_handle_id, scopes_missing, BrokerDenial, BrokerDenialReason,
242 ClassifiedFailure, ConnectionConsent, ConnectionHealth, ConnectionProvider,
243 ConnectionReauthRequired, ConnectionRecord, ConnectionRefresh, ConnectionRevocation,
244 ConnectionStatus, CredentialBroker, CredentialHandle, CredentialMediator,
245 CredentialRequirement, CredentialTool, CredentialUse, HandleClaims, HandleIssuance,
246 IssueRequest, MediatedTool, OAuthFailure, OAuthProvider, ResolvedCredential,
247 ScriptedOAuthProvider, SealedCredential, StoredConnection, TokenGrant, TokenMaterial,
248 CONNECTION_ID_PREFIX, HANDLE_ID_PREFIX, HANDLE_TOKEN_PREFIX, SEALED_FORMAT_VERSION,
249 };
250 pub use crate::capsule::{
251 any_grant_of_kind, derive_capsule_id, network_grant_covers, CapabilityGrant,
252 CapabilityKind, CapsuleDenial, CapsuleId, CapsuleIdentity, CapsuleInterface,
253 CapsuleManifest, CapsuleResolution, CapsuleUse, FilesystemMode, ResourceBudget,
254 SUPPORTED_WORLDS, WORLD_V1,
255 };
256 pub use crate::checkpoint::{
257 Checkpoint, Checkpointer, InMemoryCheckpointer, JsonFileCheckpointer,
258 };
259 #[cfg(feature = "postgres")]
260 pub use crate::checkpoint_postgres::PostgresCheckpointer;
261 pub use crate::deploy::{
262 deployment_admission, deployment_surface, derive_revision_id, pin_set_digest,
263 revision_promotion_effect_id, scoped_secret_name, validate_secret_name, CanaryClearance,
264 CanaryDeclaration, CanaryDeployment, DeployError, DeploymentPointer, DeploymentResolved,
265 DeploymentRevision, EnvSecretAct, EnvSecretDenial, EnvSecretRecord, EnvSecretRevocation,
266 Environment, EnvironmentDeclaration, GateCheckRecord, GateDecisionRecord, GateDeclaration,
267 GateEvaluation, GateVerdict, RegistryPin, RevisionContent, RevisionGateEvaluator,
268 RevisionId, RevisionPromotion, RevisionRegistration, RevisionRollback, ShadowRunOutcome,
269 ShadowRunStarted, ShadowVerdict, StoredEnvSecret, MAX_SECRET_NAME_LEN,
270 REVISION_PROMOTION_EFFECT_KIND,
271 };
272 pub use crate::durable::{
273 backoff_delay_ms, backoff_delay_ms_with, classify_retry, classify_retry_with_policy,
274 resolve_retry_parameters, resolve_timeout_bound_ms, retry_decision_event,
275 retry_legal_actions, retry_selected_action, timeout_decision_event, timeout_legal_actions,
276 timeout_selected_action, ArtifactContract, ErrorClass, LatencyPercentiles,
277 ResolvedRetryParameters, RetryDecision, TaskBudget, TaskEnvelope, BASE_RETRY_DELAY_MS,
278 MAX_RETRY_DELAY_MS, TASK_ENVELOPE_FORMAT_VERSION,
279 };
280 pub use crate::effects::{
281 admit_compensatable, admit_irreversible, admit_retry, admit_speculation, derive_effect_id,
282 ApprovalToken, CompensatableEffect, CompensationHandler, CompensationRegistry, EffectId,
283 EffectViolation, IdempotentEffect, IrreversibleEffect, PureEffect, ReadOnlyEffect,
284 ShadowOutcomeSource, ShadowRefusal, ShadowRefusalSink, TypedEffect, EFFECT_ID_DOMAIN,
285 };
286 pub use crate::error::{Result, RustyError};
287 pub use crate::executor::{ExecutionOutcome, Executor, GraphEvent, RunConfig};
288 pub use crate::graph::{ConditionalRouter, Edge, Graph, GraphBuilder, Route, Send};
289 pub use crate::journal::{
290 Clock, EventDraft, Journal, JournalSnapshot, RngSource, PARENT_EVENT_KEY,
291 };
292 pub use crate::learn::{
293 admit_promotion, canary_admits, candidate_effect_key, derive_candidate_id,
294 detect_policy_drift, distill_retry_parameters, distill_timeout_parameters,
295 evaluation_effect_key, promotion_effect_id, promotion_effect_key, rollback_effect_key,
296 surface_for_kind, AutoPromotion, CanaryBinding, Candidate, CandidateContent,
297 CandidateEvaluation, CandidateEvaluator, CandidateId, CandidateKind, CandidateOverlay,
298 CandidateRecord, CandidateStatus, DriftBaseline, DriftThresholds, EnvelopeRule,
299 EnvironmentTag, EvaluationRequest, EvaluationThresholds, EvaluationVerdict, EvidenceSpan,
300 GrantDirection, LearnError, MiddlewareLayerConfig, PolicyDriftReport, PromotionAuthority,
301 PromotionDecision, PromotionEnvelope, PromotionReceipt, PromotionRefusal, ReplayDivergence,
302 ReplaySummary, RetryLearningConfig, RollbackReceipt, SurfaceKey, TimeoutLearningConfig,
303 TwinCandidateEvaluator, VersionPointer, CANARY_DRAW_DOMAIN, PROMOTION_EFFECT_KIND,
304 SURFACE_TAG_SEPARATOR,
305 };
306 pub use crate::llm::{
307 ChatMessage, ChatModel, ChatResponse, OpenAiCompatibleClient, Role, ToolCall, Usage,
308 };
309 pub use crate::memory::{
310 apply_query, assemble, derive_memory_id, estimated_tokens, memory_effect_key,
311 memory_read_request, BudgetOverflow, ContextBudget, InMemoryMemoryStore, JournaledMemory,
312 MemoryAssembly, MemoryEvidence, MemoryKind, MemoryProvenance, MemoryQuery, MemoryRecord,
313 MemoryReplaySource, MemoryScope, MemorySource, MemoryStore, ProvenanceAuthor, ScopeAddress,
314 TokenAccounting, ValidityWindow, DEFAULT_TOKEN_MARGIN_PERCENT, MEMORY_SCHEMA_VERSION,
315 TOKEN_BYTES_PER_ESTIMATE,
316 };
317 pub use crate::middleware::{
318 instantiate_composition, Decision, InterceptPoint, Middleware, MiddlewareChain,
319 MiddlewareChatModel, ModelCall, NodeCall, Rejection, RequestLogger, ToolCallBlocklist,
320 ToolInvocation,
321 };
322 pub use crate::node::{Command, Node, NodeConfig, NodeContext, NodeOutput};
323 pub use crate::react::{
324 create_react_agent, create_react_agent_replaying, create_react_agent_streaming,
325 create_react_agent_with_recording,
326 };
327 pub use crate::receipt::{
328 derive_key_id, manifest_digest, mint_receipt, verify_receipt, PublicKey, ReceiptRejection,
329 RunReceipt, SigningKey, SigningKeyRotation, VerifiedRun, RECEIPT_FORMAT_VERSION,
330 };
331 pub use crate::record::{
332 derive_policy_version, ArtifactRef, BackoffParameters, CapsuleVersion, CheckpointHeader,
333 ConcurrencyPolicyParameters, DecisionAction, DecisionEvent, DecisionFamily,
334 DecisionOutcome, DecisionRole, Effect, EffectReceipt, EventStatus, ExecutorPolicy,
335 JournalRef, PayloadRef, PolicyVersion, RetryPolicyParameters, RunEvent, RunEventKind,
336 RunManifest, TimeoutPolicyParameters, CURRENT_FORMAT_VERSION, POLICY_MAX_ATTEMPTS_ENVELOPE,
337 POLICY_MAX_DELAY_ENVELOPE_MS,
338 };
339 pub use crate::registry::{
340 diff_candidates, pointer_admission, resolution_pin, ArtifactCommit, ArtifactRecord,
341 ConfigResolution, LeafChange, LeafModification, PointerBinding, RegistryDiff,
342 RegistryError, TextDiffLine, MAX_ARTIFACT_NAME_LEN,
343 };
344 pub use crate::replay::{
345 BranchDiff, BranchTotals, ChannelDiff, ExactReplay, FixtureMetadata, JournalShadowSource,
346 LogicalClockParams, RecordingChatModel, RecordingTool, ReplayFixture, ReplayOutcome,
347 ReplayParams, ReplaySource, ReplayingChatModel, ReplayingTool, ServedEffect, StepDiff,
348 FIXTURE_FORMAT_VERSION,
349 };
350 pub use crate::state::{Reducer, State, StateSpec};
351 pub use crate::team_trace::{TeamTrace, TeamTraceNode};
352 pub use crate::tool::{Tool, ToolExecutor, ToolRegistry};
353 pub use crate::twin::{
354 CounterfactualBranch, CounterfactualFork, DecisionContext, FaultAnchor, FaultInjection,
355 FaultSchedule, InjectedFault, Interleaving, ParameterizedPolicy, RecordedAnswer,
356 StaticFloor, Twin, TwinMetrics, TwinOutcome, TwinPolicy, TwinReport, TwinRunConfig,
357 TwinWorkItem, TwinWorld, UnevaluableCase, DEFAULT_CONCURRENCY_LADDER,
358 DEFAULT_TIMEOUT_LADDER, MIN_TIMEOUT_RUNG_MS, TWIN_FORK_POLICY_VERSION, TWIN_REPORT_BOUND,
359 };
360}