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#![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/// Dynamic agent loading by name.
78pub mod agent_loader;
79/// Callback type aliases for agent, model, and tool lifecycle hooks.
80pub mod callbacks;
81/// Invocation context traits: state, session, artifacts, memory, and run configuration.
82pub mod context;
83/// Unified structured error type and result alias.
84pub mod error;
85/// Event types representing agent interactions in a conversation.
86pub mod event;
87/// Typed identity primitives for app, user, session, and invocation.
88pub mod identity;
89/// Template-based instruction injection with session state interpolation.
90pub mod instruction_template;
91/// Intra-turn context compaction configuration.
92pub mod intra_compaction;
93/// LLM trait, request/response types, and caching configuration.
94pub mod model;
95/// HTTP request context extracted by auth middleware.
96pub mod request_context;
97/// Provider-aware JSON Schema normalization for tool declarations.
98pub mod schema_adapter;
99/// Thread-safe schema cache for tool parameter schemas.
100pub mod schema_cache;
101/// JSON Schema utility functions.
102pub mod schema_utils;
103/// Thread-safe shared state for parallel agent coordination.
104pub mod shared_state;
105/// Tool trait, toolset, execution strategy, and registry.
106pub mod tool;
107/// Semaphore-based tool concurrency management.
108pub mod tool_concurrency;
109/// Content, Part, and multimodal data types.
110pub mod types;
111
112pub use agent::{Agent, EventStream, ResolvedContext};
113pub use agent_loader::{AgentLoader, MultiAgentLoader, SingleAgentLoader};
114pub use callbacks::{
115    AfterAgentCallback, AfterModelCallback, AfterToolCallback, AfterToolCallbackFull,
116    BaseEventsSummarizer, BeforeAgentCallback, BeforeModelCallback, BeforeModelResult,
117    BeforeToolCallback, EventsCompactionConfig, GlobalInstructionProvider, InstructionProvider,
118    OnToolErrorCallback,
119};
120pub use context::{
121    Artifacts, BackpressurePolicy, CallbackContext, IncludeContents, InvocationContext,
122    MAX_STATE_KEY_LEN, Memory, MemoryEntry, ReadonlyContext, ReadonlyState, RunConfig,
123    RunConfigBuilder, SecretService, Session, State, StreamingMode, ToolCallbackContext,
124    ToolConcurrencyConfig, ToolConfirmationDecision, ToolConfirmationPolicy,
125    ToolConfirmationRequest, ToolOutcome, validate_state_key,
126};
127pub use error::{AdkError, ErrorCategory, ErrorComponent, ErrorDetails, Result, RetryHint};
128pub use event::{
129    Event, EventActions, EventCompaction, KEY_PREFIX_APP, KEY_PREFIX_TEMP, KEY_PREFIX_USER,
130};
131pub use identity::{
132    AdkIdentity, AppName, ExecutionIdentity, IdentityError, InvocationId, SessionId, UserId,
133};
134pub use instruction_template::inject_session_state;
135pub use intra_compaction::IntraCompactionConfig;
136pub use model::{
137    CacheCapable, CitationMetadata, CitationSource, ContextCacheConfig, FinishReason,
138    GenerateContentConfig, Llm, LlmRequest, LlmResponse, LlmResponseStream, UsageMetadata,
139};
140pub use request_context::RequestContext;
141pub use schema_adapter::{GenericSchemaAdapter, SchemaAdapter};
142pub use schema_cache::SchemaCache;
143pub use shared_state::{SharedState, SharedStateError};
144pub use tool::{
145    RetryBudget, Tool, ToolContext, ToolExecutionStrategy, ToolPredicate, ToolRegistry, Toolset,
146    ValidationMode,
147};
148pub use tool_concurrency::{ConcurrencyPermit, ToolConcurrencyManager};
149pub use types::{
150    Content, FileDataPart, FunctionResponseData, InlineDataPart, MAX_INLINE_DATA_SIZE, Part,
151};
152
153// Re-export async_trait so the #[tool] macro's generated code can reference it
154// via adk_tool::async_trait (adk_tool re-exports from adk_core).
155pub use async_trait::async_trait;
156
157/// Enforces the explicit cryptographic provider process-wide.
158/// This bypasses any inert 'ring' code lingering in deep dependencies.
159///
160/// Because we lack a monolithic main() function, we use lazy evaluation
161/// to guarantee that aws-lc-rs is installed globally the millisecond
162/// an adk-rust consumer attempts to use the network.
163pub fn ensure_crypto_provider() {
164    #[cfg(feature = "rustls")]
165    {
166        static CRYPTO_INIT: std::sync::Once = std::sync::Once::new();
167        CRYPTO_INIT.call_once(|| {
168            // We ignore the Result. If the parent application has already
169            // deliberately installed a provider, we respect their sovereign choice.
170            let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
171        });
172    }
173}