adk_core/lib.rs
1//! # adk-core
2//!
3//! Core traits and types for ADK agents, tools, sessions, and events.
4#![allow(clippy::result_large_err)]
5#![deny(missing_docs)]
6//!
7//! ## Overview
8//!
9//! This crate provides the foundational abstractions for the Agent Development Kit:
10//!
11//! - [`Agent`] - The fundamental trait for all agents
12//! - [`Tool`] / [`Toolset`] - For extending agents with custom capabilities
13//! - [`Session`] / [`State`] - For managing conversation context
14//! - [`Event`] - For streaming agent responses
15//! - [`AdkError`] / [`Result`] - Unified error handling
16//! - [`SharedState`] / [`SharedStateError`] - Thread-safe key-value store for parallel agent coordination
17//! - [`ToolConfirmationPolicy`] / [`ToolConfirmationRequest`] - Human-in-the-loop tool authorization
18//!
19//! ## What's New in 0.6.0
20//!
21//! - **`SharedState`**: Concurrent key-value store with `set_shared`, `get_shared`, and
22//! `wait_for_key` (timeout-based blocking) for cross-agent coordination in `ParallelAgent`.
23//! - **`shared_state()` on `CallbackContext`**: Default method returning `None` — tools and
24//! callbacks can access `SharedState` when running inside a `ParallelAgent` with shared state enabled.
25//! - **`ToolConfirmationPolicy`**: Built-in HITL mechanism — `Never`, `Always`, or `PerTool`
26//! policies that pause execution and emit `ToolConfirmationRequest` events for user approval.
27//!
28//! ## Quick Start
29//!
30//! ```rust,no_run
31//! use adk_core::{Agent, Tool, Event, Result};
32//! use std::sync::Arc;
33//!
34//! // All agents implement the Agent trait
35//! // All tools implement the Tool trait
36//! // Events are streamed as the agent executes
37//! ```
38//!
39//! ## Core Traits
40//!
41//! ### Agent
42//!
43//! The [`Agent`] trait defines the interface for all agents:
44//!
45//! ```rust,ignore
46//! #[async_trait]
47//! pub trait Agent: Send + Sync {
48//! fn name(&self) -> &str;
49//! fn description(&self) -> Option<&str>;
50//! async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream>;
51//! }
52//! ```
53//!
54//! ### Tool
55//!
56//! The [`Tool`] trait defines custom capabilities:
57//!
58//! ```rust,ignore
59//! #[async_trait]
60//! pub trait Tool: Send + Sync {
61//! fn name(&self) -> &str;
62//! fn description(&self) -> &str;
63//! async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value>;
64//! }
65//! ```
66//!
67//! ## State Management
68//!
69//! State uses typed prefixes for organization:
70//!
71//! - `user:` - User preferences (persists across sessions)
72//! - `app:` - Application state (application-wide)
73//! - `temp:` - Temporary data (cleared each turn)
74
75/// Core agent trait and event stream type.
76pub mod agent;
77/// Starting an agent turn without owning the runner's construction.
78pub mod agent_invoker;
79/// Dynamic agent loading by name.
80pub mod agent_loader;
81/// Callback type aliases for agent, model, and tool lifecycle hooks.
82pub mod callbacks;
83/// Invocation context traits: state, session, artifacts, memory, and run configuration.
84pub mod context;
85/// Unified structured error type and result alias.
86pub mod error;
87/// Event types representing agent interactions in a conversation.
88pub mod event;
89/// Typed identity primitives for app, user, session, and invocation.
90pub mod identity;
91/// Template-based instruction injection with session state interpolation.
92pub mod instruction_template;
93/// Intra-turn context compaction configuration.
94pub mod intra_compaction;
95/// LLM trait, request/response types, and caching configuration.
96pub mod model;
97/// HTTP request context extracted by auth middleware.
98pub mod request_context;
99/// Provider-aware JSON Schema normalization for tool declarations.
100pub mod schema_adapter;
101/// Thread-safe schema cache for tool parameter schemas.
102pub mod schema_cache;
103/// JSON Schema utility functions.
104pub mod schema_utils;
105/// Thread-safe shared state for parallel agent coordination.
106pub mod shared_state;
107/// Tool trait, toolset, execution strategy, and registry.
108pub mod tool;
109/// Semaphore-based tool concurrency management.
110pub mod tool_concurrency;
111/// Content, Part, and multimodal data types.
112pub mod types;
113
114pub use agent::{
115 Agent, AgentCapabilities, AgentInteractionMode, AgentRelationshipKind, AgentTopology,
116 AgentTopologyMember, AgentTopologyRelationship, AgentTransferDecision, AgentTransferRequest,
117 EventStream, ResolvedContext,
118};
119pub use agent_invoker::AgentInvoker;
120pub use agent_loader::{AgentLoader, MultiAgentLoader, SingleAgentLoader};
121pub use callbacks::{
122 AfterAgentCallback, AfterModelCallback, AfterToolCallback, AfterToolCallbackFull,
123 BaseEventsSummarizer, BeforeAgentCallback, BeforeModelCallback, BeforeModelResult,
124 BeforeToolCallback, EventsCompactionConfig, GlobalInstructionProvider, InstructionProvider,
125 OnToolErrorCallback,
126};
127pub use context::{
128 Artifacts, BackpressurePolicy, CallbackContext, IncludeContents, InvocationContext,
129 MAX_STATE_KEY_LEN, Memory, MemoryEntry, ReadonlyContext, ReadonlyState, RunConfig,
130 RunConfigBuilder, RuntimeToolset, SecretRequest, SecretService, Session, State, StreamingMode,
131 ToolCallbackContext, ToolConcurrencyConfig, ToolConfirmationDecision, ToolConfirmationHandler,
132 ToolConfirmationPolicy, ToolConfirmationRequest, ToolOutcome, tool_call_fingerprint,
133 validate_state_key,
134};
135pub use error::{AdkError, ErrorCategory, ErrorComponent, ErrorDetails, Result, RetryHint};
136pub use event::{
137 Event, EventActions, EventCompaction, KEY_PREFIX_APP, KEY_PREFIX_TEMP, KEY_PREFIX_USER,
138 TOOL_PROGRESS_CALL_ID_KEY, TOOL_PROGRESS_STREAM_KEY, ToolCallView, ToolResultView,
139 event_belongs_to_branch,
140};
141pub use identity::{
142 AdkIdentity, AppName, ExecutionIdentity, IdentityError, InvocationId, SessionId, UserId,
143};
144pub use instruction_template::inject_session_state;
145pub use intra_compaction::IntraCompactionConfig;
146pub use model::{
147 CacheCapable, CitationMetadata, CitationSource, ContextCacheConfig, FinishReason,
148 GenerateContentConfig, Llm, LlmRequest, LlmResponse, LlmResponseStream, UsageMetadata,
149};
150pub use request_context::RequestContext;
151pub use schema_adapter::{GenericSchemaAdapter, SchemaAdapter};
152pub use schema_cache::SchemaCache;
153pub use shared_state::{SharedState, SharedStateError};
154pub use tool::{
155 RetryBudget, Tool, ToolContext, ToolExecutionStrategy, ToolPredicate, ToolRegistry, Toolset,
156 ValidationMode,
157};
158pub use tool_concurrency::{ConcurrencyPermit, ToolConcurrencyManager};
159pub use types::{
160 BlobResourceContents, Content, EmbeddedResource, FileDataPart, FunctionResponseData,
161 InlineDataPart, MAX_INLINE_DATA_SIZE, Part, TextResourceContents,
162};
163
164// Re-export async_trait so the #[tool] macro's generated code can reference it
165// via adk_tool::async_trait (adk_tool re-exports from adk_core).
166pub use async_trait::async_trait;
167
168/// Enforces the explicit cryptographic provider process-wide.
169/// This bypasses any inert 'ring' code lingering in deep dependencies.
170///
171/// Because we lack a monolithic main() function, we use lazy evaluation
172/// to guarantee that aws-lc-rs is installed globally the millisecond
173/// an adk-rust consumer attempts to use the network.
174pub fn ensure_crypto_provider() {
175 #[cfg(feature = "rustls")]
176 {
177 static CRYPTO_INIT: std::sync::Once = std::sync::Once::new();
178 CRYPTO_INIT.call_once(|| {
179 // We ignore the Result. If the parent application has already
180 // deliberately installed a provider, we respect their sovereign choice.
181 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
182 });
183 }
184}