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//!
6//! ## Overview
7//!
8//! This crate provides the foundational abstractions for the Agent Development Kit:
9//!
10//! - [`Agent`] - The fundamental trait for all agents
11//! - [`Tool`] / [`Toolset`] - For extending agents with custom capabilities
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//!
18//! ## What's New in 0.6.0
19//!
20//! - **`SharedState`**: Concurrent key-value store with `set_shared`, `get_shared`, and
21//!   `wait_for_key` (timeout-based blocking) for cross-agent coordination in `ParallelAgent`.
22//! - **`shared_state()` on `CallbackContext`**: Default method returning `None` — tools and
23//!   callbacks can access `SharedState` when running inside a `ParallelAgent` with shared state enabled.
24//! - **`ToolConfirmationPolicy`**: Built-in HITL mechanism — `Never`, `Always`, or `PerTool`
25//!   policies that pause execution and emit `ToolConfirmationRequest` events for user approval.
26//!
27//! ## Quick Start
28//!
29//! ```rust,no_run
30//! use adk_core::{Agent, Tool, Event, Result};
31//! use std::sync::Arc;
32//!
33//! // All agents implement the Agent trait
34//! // All tools implement the Tool trait
35//! // Events are streamed as the agent executes
36//! ```
37//!
38//! ## Core Traits
39//!
40//! ### Agent
41//!
42//! The [`Agent`] trait defines the interface for all agents:
43//!
44//! ```rust,ignore
45//! #[async_trait]
46//! pub trait Agent: Send + Sync {
47//!     fn name(&self) -> &str;
48//!     fn description(&self) -> Option<&str>;
49//!     async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream>;
50//! }
51//! ```
52//!
53//! ### Tool
54//!
55//! The [`Tool`] trait defines custom capabilities:
56//!
57//! ```rust,ignore
58//! #[async_trait]
59//! pub trait Tool: Send + Sync {
60//!     fn name(&self) -> &str;
61//!     fn description(&self) -> &str;
62//!     async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value>;
63//! }
64//! ```
65//!
66//! ## State Management
67//!
68//! State uses typed prefixes for organization:
69//!
70//! - `user:` - User preferences (persists across sessions)
71//! - `app:` - Application state (application-wide)
72//! - `temp:` - Temporary data (cleared each turn)
73
74pub mod agent;
75pub mod agent_loader;
76pub mod callbacks;
77pub mod context;
78pub mod error;
79pub mod event;
80pub mod identity;
81pub mod instruction_template;
82pub mod intra_compaction;
83pub mod model;
84pub mod request_context;
85pub mod shared_state;
86pub mod tool;
87pub mod types;
88
89pub use agent::{Agent, EventStream, ResolvedContext};
90pub use agent_loader::{AgentLoader, MultiAgentLoader, SingleAgentLoader};
91pub use callbacks::{
92    AfterAgentCallback, AfterModelCallback, AfterToolCallback, AfterToolCallbackFull,
93    BaseEventsSummarizer, BeforeAgentCallback, BeforeModelCallback, BeforeModelResult,
94    BeforeToolCallback, EventsCompactionConfig, GlobalInstructionProvider, InstructionProvider,
95    OnToolErrorCallback,
96};
97pub use context::{
98    Artifacts, CallbackContext, IncludeContents, InvocationContext, MAX_STATE_KEY_LEN, Memory,
99    MemoryEntry, ReadonlyContext, ReadonlyState, RunConfig, SecretService, Session, State,
100    StreamingMode, ToolCallbackContext, ToolConfirmationDecision, ToolConfirmationPolicy,
101    ToolConfirmationRequest, ToolOutcome, validate_state_key,
102};
103pub use error::{AdkError, ErrorCategory, ErrorComponent, ErrorDetails, Result, RetryHint};
104pub use event::{
105    Event, EventActions, EventCompaction, KEY_PREFIX_APP, KEY_PREFIX_TEMP, KEY_PREFIX_USER,
106};
107pub use identity::{
108    AdkIdentity, AppName, ExecutionIdentity, IdentityError, InvocationId, SessionId, UserId,
109};
110pub use instruction_template::inject_session_state;
111pub use intra_compaction::IntraCompactionConfig;
112pub use model::{
113    CacheCapable, CitationMetadata, CitationSource, ContextCacheConfig, FinishReason,
114    GenerateContentConfig, Llm, LlmRequest, LlmResponse, LlmResponseStream, UsageMetadata,
115};
116pub use request_context::RequestContext;
117pub use shared_state::{SharedState, SharedStateError};
118pub use tool::{
119    RetryBudget, Tool, ToolContext, ToolExecutionStrategy, ToolPredicate, ToolRegistry, Toolset,
120    ValidationMode,
121};
122pub use types::{
123    Content, FileDataPart, FunctionResponseData, InlineDataPart, MAX_INLINE_DATA_SIZE, Part,
124};
125
126// Re-export async_trait so the #[tool] macro's generated code can reference it
127// via adk_tool::async_trait (adk_tool re-exports from adk_core).
128pub use async_trait::async_trait;
129
130/// Enforces the explicit cryptographic provider process-wide.
131/// This bypasses any inert 'ring' code lingering in deep dependencies.
132///
133/// Because we lack a monolithic main() function, we use lazy evaluation
134/// to guarantee that aws-lc-rs is installed globally the millisecond
135/// an adk-rust consumer attempts to use the network.
136pub fn ensure_crypto_provider() {
137    #[cfg(feature = "rustls")]
138    {
139        static CRYPTO_INIT: std::sync::Once = std::sync::Once::new();
140        CRYPTO_INIT.call_once(|| {
141            // We ignore the Result. If the parent application has already
142            // deliberately installed a provider, we respect their sovereign choice.
143            let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
144        });
145    }
146}