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