Skip to main content

adk_core/
lib.rs

1//! # adk-core
2//!
3//! Core traits and types for ADK agents, tools, sessions, and events.
4//!
5//! ## Overview
6//!
7//! This crate provides the foundational abstractions for the Agent Development Kit:
8//!
9//! - [`Agent`] - The fundamental trait for all agents
10//! - [`Tool`] / [`Toolset`] - For extending agents with custom capabilities
11//! - [`Llm`] - The interface every model provider implements
12//! - [`Session`] / [`State`] - For managing conversation context
13//! - [`Event`] - For streaming agent responses
14//! - [`AdkError`] / [`Result`] - Unified error handling
15//! - [`SharedState`] / [`SharedStateError`] - Thread-safe key-value store for parallel agent coordination
16//! - [`ToolConfirmationPolicy`] / [`ToolConfirmationRequest`] - Human-in-the-loop tool authorization
17//! - [`ToolPolicy`] / [`DeclarativePolicy`] / [`authorize_tool_call`] - The governed tool execution path
18//! - [`GovernanceControl`] - Organisation-wide kill switch
19//! - [`RunBudget`] / [`SpendLedger`] / [`ActionLedger`] - Run limits, spend caps, and at-most-once tool calls
20//! - [`AgentId`] / [`AgentPrincipal`] / [`ActingContext`] / [`ActingConfig`] - Agent identity
21//! - [`LeaseStore`] / [`DurableRunStore`] / [`ScheduleStore`] / [`GovernanceStateStore`] -
22//!   Durable runtime contracts: fenced leases, the run queue, schedules, and freeze state
23//! - [`subject::SubjectRights`] / [`subject::ConsentStore`] / [`subject::SubjectRegistry`] -
24//!   Visitor ids, consent, and a subject's export, erasure, and links across stores
25//!
26//! ## Feature Flags
27//!
28//! | Feature | Enables |
29//! |---------|---------|
30//! | `rustls` | [`ensure_crypto_provider`] installs the `aws-lc-rs` rustls provider |
31//! | `conformance` | The `conformance` module: suites for durable store backends |
32//! | `cron` | Cron schedules in IANA time zones |
33//! | `webhooks` | The `webhook` module: Standard Webhooks signing and verification |
34//! | `egress-dns` | `egress::SystemResolver`: the operating system resolver for egress checks |
35//! | `egress-client` | `egress::GuardedClient`: an HTTP client that enforces an `EgressPolicy` |
36//! | `webhook-delivery` | The `webhook_delivery` module: signed outbound delivery |
37//! | `auth-bridge` | The `request_context` module: `RequestContextExtractor`, the trait an HTTP server authenticates requests through |
38//!
39//! ## Quick Start
40//!
41//! ```rust
42//! use std::sync::Arc;
43//!
44//! use adk_core::{Result, Tool, ToolContext, ToolEffect};
45//! use async_trait::async_trait;
46//! use serde_json::{Value, json};
47//!
48//! struct Echo;
49//!
50//! #[async_trait]
51//! impl Tool for Echo {
52//!     fn name(&self) -> &str {
53//!         "echo"
54//!     }
55//!
56//!     fn description(&self) -> &str {
57//!         "Returns its arguments"
58//!     }
59//!
60//!     fn effect(&self) -> ToolEffect {
61//!         ToolEffect::ReadOnly
62//!     }
63//!
64//!     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
65//!         Ok(json!({ "echo": args }))
66//!     }
67//! }
68//!
69//! assert_eq!(Echo.effect(), ToolEffect::ReadOnly);
70//! ```
71//!
72//! ## Core Traits
73//!
74//! ### Agent
75//!
76//! The [`Agent`] trait defines the interface for all agents. `name`, `description`, `sub_agents`,
77//! and `run` are required; `description` returns `&str`, and a leaf agent returns `&[]` from
78//! `sub_agents`.
79//!
80//! ```rust
81//! use std::sync::Arc;
82//!
83//! use adk_core::{Agent, EventStream, InvocationContext, Result};
84//! use async_trait::async_trait;
85//!
86//! struct Silent;
87//!
88//! #[async_trait]
89//! impl Agent for Silent {
90//!     fn name(&self) -> &str {
91//!         "silent"
92//!     }
93//!
94//!     fn description(&self) -> &str {
95//!         "Produces no events"
96//!     }
97//!
98//!     fn sub_agents(&self) -> &[Arc<dyn Agent>] {
99//!         &[]
100//!     }
101//!
102//!     async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
103//!         Ok(Box::pin(futures::stream::empty()))
104//!     }
105//! }
106//! ```
107//!
108//! ### Tool
109//!
110//! The [`Tool`] trait defines custom capabilities. [`Tool::effect`] declares whether a call is
111//! read-only, idempotent, or non-idempotent, which governs retries and the action ledger.
112//!
113//! ## State Management
114//!
115//! State uses typed prefixes for organization:
116//!
117//! - `user:` - User preferences (persists across sessions)
118//! - `app:` - Application state (application-wide)
119//! - `temp:` - Visible for the rest of the invocation; session services do not persist it
120#![allow(clippy::result_large_err)]
121#![deny(missing_docs)]
122
123/// How a run's agents act: the identity model, the run-level acting configuration,
124/// delegation, and subject delegation policies.
125pub mod acting;
126/// Durable record of non-idempotent tool calls.
127pub mod action_ledger;
128/// Core agent trait and event stream type.
129pub mod agent;
130/// Starting an agent turn without owning the runner's construction.
131pub mod agent_invoker;
132/// Dynamic agent loading by name.
133pub mod agent_loader;
134/// Approval service: an inbox of approval requests with quorum, delegation, escalation,
135/// and expiry over an approval store.
136pub mod approval;
137/// Append-only audit log records and the store that holds them.
138pub mod audit_log;
139/// Run budgets: limits on model calls, tokens, cost, wall time, and tool calls.
140pub mod budget;
141/// Callback type aliases for agent, model, and tool lifecycle hooks.
142pub mod callbacks;
143/// Time sources for stores whose behaviour depends on the current time.
144pub mod clock;
145/// Provider-neutral computer actuation: actions, screenshots, and the actuator trait.
146pub mod computer;
147/// Conformance suites that every durable store backend runs against its implementation.
148#[cfg(feature = "conformance")]
149pub mod conformance;
150/// Invocation context traits: state, session, artifacts, memory, and run configuration.
151pub mod context;
152/// Agent credentials, identity sources, and resource-scoped token brokers.
153pub mod credential;
154/// Typed decisions: a model picks one of a fixed set of options, with a rationale and a
155/// confidence.
156pub mod decision;
157pub mod egress;
158/// Unified structured error type and result alias.
159pub mod error;
160/// Event types representing agent interactions in a conversation.
161pub mod event;
162mod event_stream;
163/// The LLM summarizer that session and in-run compaction share.
164pub mod event_summarizer;
165/// Evidence an approver sees with a held call: images by digest and artifact.
166pub mod evidence;
167/// Governed tool execution: kill switch, durable approvals, and the authorization path.
168pub mod governance;
169/// Durable freeze state for the kill switch, shared by every replica.
170pub mod governance_state;
171/// Sources a run retrieved, and the citations an answer makes to them.
172pub mod grounding;
173/// Building model history from session events: other agents' turns as context, tool
174/// branches, and balanced history cuts.
175pub mod history;
176/// Typed identity primitives for app, user, session, and invocation.
177pub mod identity;
178/// Template-based instruction injection with session state interpolation.
179pub mod instruction_template;
180/// Auto-compaction during a run: its threshold, the token estimate, and the agents' hook.
181pub mod intra_compaction;
182/// Leases with fencing epochs: one owner of a named resource at a time.
183pub mod lease;
184/// Metering for every model call made on behalf of a run.
185pub mod metering;
186/// LLM trait, request/response types, and caching configuration.
187pub mod model;
188/// The process's one ONNX Runtime environment, shared by every crate that runs ONNX models.
189#[cfg(feature = "ort")]
190pub mod onnx;
191/// Tool execution policy: allow, deny, or require approval per call.
192pub mod policy;
193/// Agent identity: agent identifiers, principals, and acting contexts.
194pub mod principal;
195pub mod queue_source;
196/// HTTP request context extracted by auth middleware.
197pub mod request_context;
198/// Model-evaluated tool approval: a reviewer that decides held calls before a person.
199pub mod review;
200/// Durable runs: a queue of runs that workers claim under fenced leases.
201pub mod run_store;
202/// Schedules that enqueue durable runs, and the firing rule.
203pub mod schedule;
204/// Provider-aware JSON Schema normalization for tool declarations.
205pub mod schema_adapter;
206/// Thread-safe schema cache for tool parameter schemas.
207pub mod schema_cache;
208/// JSON Schema utility functions.
209pub mod schema_utils;
210/// Thread-safe shared state for parallel agent coordination.
211pub mod shared_state;
212/// One spend ledger for model calls and payments: reservations, limits, and committed spend.
213pub mod spend;
214/// User messages that reach a run while it runs: the run's inbox, the receipt and the
215/// event marker.
216pub mod steering;
217/// Background sub-agents: the host contract, their status, the budget slice and tool
218/// ceiling they run under, and the notice a parent receives.
219pub mod subagent;
220pub mod subject;
221/// Tool trait, toolset, execution strategy, and registry.
222pub mod tool;
223/// Semaphore-based tool concurrency management.
224pub mod tool_concurrency;
225/// Function responses for tool calls that fail, are withheld, or carry undecodable arguments.
226pub mod tool_response;
227/// Content, Part, and multimodal data types.
228pub mod types;
229/// Vendor-neutral usage units and per-unit prices.
230pub mod usage;
231#[cfg(feature = "webhooks")]
232pub mod webhook;
233#[cfg(feature = "webhook-delivery")]
234pub mod webhook_delivery;
235
236pub use acting::{
237    ActingConfig, PRINCIPAL_NOT_ALLOWED_CODE, SUBJECT_MISMATCH_CODE, StaticSubjectDelegation,
238    SubjectDelegationPolicy, SubjectDelegationRequest, subject_mismatch_error,
239};
240pub use action_ledger::{
241    ActionLedger, ActionOutcome, ActionRecord, InMemoryActionLedger, LedgerAnswer, LedgeredCall,
242    NOT_RUN_PREFIX, OUTCOME_UNKNOWN_STATUS, begin_ledgered_call, held_call_ledger_key,
243    interrupted_call_response, is_not_run, is_outcome_unknown, json_digest, not_run_text,
244    outcome_unknown_response, record_outcome_unknown,
245};
246pub use agent::{
247    Agent, AgentCapabilities, AgentInteractionMode, AgentKind, AgentProfile, AgentRelationshipKind,
248    AgentTopology, AgentTopologyMember, AgentTopologyRelationship, AgentTransferDecision,
249    AgentTransferRequest, EventStream, ResolvedContext, ToolProfile, screen_user_input_with,
250};
251pub use agent_invoker::AgentInvoker;
252pub use agent_loader::{AgentLoader, MultiAgentLoader, SingleAgentLoader};
253pub use approval::{
254    APPROVAL_REAPPLY_GRACE, ApprovalAction, ApprovalCall, ApprovalCursor, ApprovalDecision,
255    ApprovalDelegation, ApprovalEventKind, ApprovalNotification, ApprovalNotifier, ApprovalPolicy,
256    ApprovalRequest, ApprovalRequestQuery, ApprovalResolution, ApprovalRisk, ApprovalRoute,
257    ApprovalRouter, ApprovalService, ApprovalState, ApprovalTick, ApproverDirectory,
258    ApproverSelector, DEFAULT_APPROVAL_PAGE, DelegationScope, DelegationWindow, EscalationStep,
259    ExpiryAction, InboxPage, InboxQuery, StoreApprovalService,
260};
261pub use budget::{
262    BUDGET_LIMIT_KEY, BUDGET_RECORDED_KEY, BudgetExceeded, BudgetLimit, BudgetTracker, BudgetUsage,
263    ModelCallMeter, RunBudget, budget_exceeded_event, generate_with_budget, meter_stream,
264};
265pub use callbacks::{
266    AfterAgentCallback, AfterModelCallback, AfterToolCallback, AfterToolCallbackFull,
267    BaseEventsSummarizer, BeforeAgentCallback, BeforeModelCallback, BeforeModelResult,
268    BeforeToolCallback, CALLBACK_PANICKED_CODE, EventsCompactionConfig, GlobalInstructionProvider,
269    HistoryProcessor, InstructionProvider, InvocationHooks, OnToolErrorCallback, guard_callback,
270};
271pub use clock::{Clock, ManualClock, SystemClock};
272pub use computer::{
273    ActuationOutput, ComputerAction, ComputerActionKind, ComputerActuator, MouseButton,
274    ScreenPoint, Screenshot, ScrollDirection,
275};
276pub use context::{
277    Artifacts, BUILTIN_TOOL_ORIGIN, BackpressurePolicy, BatchCall, CallbackContext,
278    IncludeContents, InvocationContext, MAX_STATE_KEY_LEN, Memory, MemoryEntry, ReadonlyContext,
279    ReadonlyState, RunConfig, RunConfigBuilder, RuntimeToolset, STATIC_TOOL_ORIGIN, SecretRequest,
280    SecretService, Session, State, StreamingMode, ToolCallbackContext, ToolConcurrencyConfig,
281    ToolConfirmationDecision, ToolConfirmationHandler, ToolConfirmationPolicy,
282    ToolConfirmationRequest, ToolOrigin, ToolOutcome, tool_call_fingerprint, validate_state_key,
283};
284pub use credential::{
285    AgentCredential, CredentialBroker, CredentialKind, CredentialSecret, IdentitySource,
286    RevocationScope, ScopedToken, StaticIdentitySource, resource_indicator,
287};
288pub use decision::{Choice, ChoiceOption, Decider, Decision, decide};
289pub use error::{
290    AdkError, ErrorCategory, ErrorComponent, ErrorDetails, ErrorDiagnostics, Result, RetryHint,
291    UPSTREAM_EXCERPT_BYTES, json_error_summary, upstream_excerpt,
292};
293pub use event::{
294    Event, EventActions, EventCompaction, KEY_PREFIX_APP, KEY_PREFIX_TEMP, KEY_PREFIX_USER,
295    TOOL_PROGRESS_CALL_ID_KEY, TOOL_PROGRESS_STREAM_KEY, ToolCallView, ToolResultView,
296    WorkflowPosition, event_belongs_to_branch,
297};
298pub use event_stream::EventTextDeltas;
299pub use event_summarizer::LlmEventSummarizer;
300pub use evidence::{ArtifactLocator, Evidence, ImageEvidence};
301pub use governance::{
302    ApprovalScope, ApprovalStore, BUILTIN_TOOLS_WITHHELD_KEY, BuiltinToolGovernor,
303    BuiltinToolWithholding, CONFIRMATION_PENDING_STATUS, DEFAULT_TOOL_CONFIRMATION_TIMEOUT,
304    DRAW_TOOL_NAMES, GOVERNANCE_FROZEN_CODE, GOVERNANCE_STALE_CODE, GovernanceControl,
305    GovernanceMirrorConfig, GovernanceWatch, GovernedCall, HeldToolCall, InMemoryApprovalStore,
306    PendingApproval, REQUESTED_CALL_ID_PREFIX, REQUESTED_CALL_METADATA_KEY, RequestedCall,
307    RequestedCallSeal, RequestedVia, RequestedViaKind, SealedCall, ToolApproval, ToolAuthorization,
308    ToolCallScreen, ToolGate, WithheldBuiltinTool, authorize_tool_call, builtin_tool_configuration,
309    confirm_tool_call, confirmation_decision_available, confirmation_pending_response,
310    held_call_compaction_limit, held_tool_calls, is_confirmation_pending,
311    supersede_pending_responses, untrusted_block, withdraw_held_call, workflow_resume_positions,
312};
313pub use governance_state::{
314    GovernanceScope, GovernanceState, GovernanceStateStore, InMemoryGovernanceStateStore,
315};
316pub use grounding::{GroundingSource, bind_markdown_citations, record_grounding_sources};
317pub use identity::{
318    AdkIdentity, AppName, ExecutionIdentity, IdentityError, InvocationId, SessionId, UserId,
319};
320pub use instruction_template::inject_session_state;
321pub use intra_compaction::{
322    CompactedHistory, CompactionTrigger, HistoryCompactionRequest, HistoryCompactor,
323    IntraCompactionConfig, NativeCompactionRequest,
324};
325pub use lease::{InMemoryLeaseStore, Lease, LeaseStore};
326pub use metering::{
327    LlmSpendEstimate, MeteredLlm, MeteredUsage, ModelCallScope, ModelSpendHold,
328    UNBOUNDED_HOLD_MICRO_USD, UsageCall, UsageHold, generate_metered, meter_usage,
329    vendor_for_model,
330};
331pub use model::{
332    BuiltinToolUse, CacheCapable, CitationMetadata, CitationSource, ContextCacheConfig, Effort,
333    FinishReason, GenerateContentConfig, Llm, LlmRequest, LlmResponse, LlmResponseStream,
334    ToolDeclarations, ToolDeclarationsIter, ToolDeclarationsKeys, ToolDeclarationsValues,
335    UsageMetadata, nullable_count,
336};
337pub use model::{
338    DataDestination, DataLocality, NativeCompaction, NativeWebSearch, NativeWebSearchTool,
339};
340pub use policy::{
341    ArgPredicate, DeclarativePolicy, DeclarativePolicyBuilder, PolicyCall, PolicyDecision,
342    PolicyRule, StrictestPolicy, ToolPolicy, ToolPolicyRequest,
343};
344pub use principal::{
345    ActingContext, AgentId, AgentPrincipal, PrincipalError, SubjectKind, SubjectRef,
346};
347pub use queue_source::{
348    InMemoryQueueSource, IngressReport, QueueIngress, QueueMessage, QueueSource,
349};
350pub use request_context::RequestContext;
351pub use review::{
352    DEFAULT_REVIEW_TIMEOUT, MODEL_REVIEWER_PREFIX, ModelApprover, REVIEW_SOURCE, ReviewScope,
353    ReviewVerdict, ToolReview, ToolReviewer,
354};
355pub use run_store::{
356    ClaimedRun, DurableRunStore, Enqueued, InMemoryRunStore, NewRun, OnConflict, RetryBackoff,
357    RunCheckpointRef, RunFilter, RunOutcome, RunRecord, RunState,
358};
359pub use schedule::{
360    FirePlan, InMemoryScheduleStore, Jitter, MissedFirePolicy, Schedule, ScheduleSpec,
361    ScheduleStore, firing_idempotency_key, manual_idempotency_key, plan_fires,
362};
363pub use schema_adapter::{GenericSchemaAdapter, SchemaAdapter};
364pub use schema_cache::SchemaCache;
365pub use shared_state::{SharedState, SharedStateError};
366pub use spend::{
367    DEFAULT_RESERVATION_TTL, InMemorySpendLedger, ReservationId, SPEND_LIMIT_EXCEEDED_CODE,
368    SpendError, SpendKey, SpendLedger, SpendLimit, SpendLimits, SpendPeriod, usd_to_micro_usd,
369};
370pub use steering::{
371    STEER_INVALID_MESSAGE_CODE, STEER_NO_ACTIVE_RUN_CODE, SteerOutcome, SteerReceipt,
372    SteeringInbox, SteeringMarker, SteeringMessage, validate_steering_message,
373};
374pub use subagent::{
375    FollowUp, RunLimits, SubagentHost, SubagentLaunch, SubagentMode, SubagentParent,
376    SubagentRecord, SubagentRequest, SubagentScope, SubagentStart, SubagentStatus, SubagentTarget,
377    ToolCeiling,
378};
379pub use tool::{
380    BatchGroup, DUPLICATE_TOOL_NAME_CODE, RetryBudget, Tool, ToolContext, ToolEffect,
381    ToolExecutionStrategy, ToolPredicate, ToolRegistry, Toolset, ValidationMode,
382    ensure_unique_tool_names,
383};
384pub use tool_concurrency::{ConcurrencyPermit, ToolConcurrencyManager};
385pub use tool_response::{
386    INVALID_TOOL_ARGUMENTS_KEY, RESULT_WITHHELD_STATUS, TOOL_ERROR_MESSAGE_LIMIT,
387    TOOL_INVALID_ARGUMENTS_CODE, TOOL_PERMISSION_DENIED_CODE, TOOL_RESULT_ERROR_CATEGORY_KEY,
388    TOOL_RESULT_ERROR_CODE_KEY, TOOL_RESULT_STATUS_KEY, ToolResultScreen, ToolResultStatus,
389    invalid_tool_arguments, invalid_tool_arguments_reason, result_blocked_response,
390    result_withheld_response, screen_tool_result, tool_error_response,
391};
392pub use types::{
393    BlobResourceContents, Content, EmbeddedResource, FileDataPart, FunctionResponseData,
394    GENERATED_CALL_ID_PREFIX, InlineDataPart, MAX_INLINE_DATA_SIZE, Part, TextResourceContents,
395};
396pub use url::Url;
397pub use usage::{UnitRate, UsageUnit, UsageVector};
398
399// Re-export async_trait so the #[tool] macro's generated code can reference it
400// via adk_tool::async_trait (adk_tool re-exports from adk_core).
401pub use async_trait::async_trait;
402
403/// Enforces the explicit cryptographic provider process-wide.
404/// This bypasses any inert 'ring' code lingering in deep dependencies.
405///
406/// Because we lack a monolithic main() function, we use lazy evaluation
407/// to guarantee that aws-lc-rs is installed globally the millisecond
408/// an adk-rust consumer attempts to use the network.
409pub fn ensure_crypto_provider() {
410    #[cfg(feature = "rustls")]
411    {
412        static CRYPTO_INIT: std::sync::Once = std::sync::Once::new();
413        CRYPTO_INIT.call_once(|| {
414            // We ignore the Result. If the parent application has already
415            // deliberately installed a provider, we respect their sovereign choice.
416            let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
417        });
418    }
419}