adk-plugin 3.0.0

Plugin system for ADK-Rust agents: run, agent, model, and tool lifecycle callbacks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Type-safe shared state container for plugins.
//!
//! [`PluginContext`] uses the TypeMap pattern where each type serves as its own key,
//! providing a type-safe, concurrent key-value store for plugin shared state.
//!
//! # Overview
//!
//! Plugins often need to share state across hook invocations within a single agent run.
//! For example, a rate-limiting plugin tracks request counts, a caching plugin stores
//! cached responses, and a metrics plugin accumulates statistics.
//!
//! `PluginContext` enables this by allowing plugins to insert and retrieve values
//! keyed by their Rust type. Each unique type can have exactly one value stored.
//!
//! [`EnhancedPluginManager`](crate::EnhancedPluginManager) hands each invocation its own
//! context, so state one user's run writes is never read by another's. State meant for every
//! invocation of the agent goes in [`PluginContext::shared`].
//!
//! # Examples
//!
//! ```rust
//! use adk_plugin::PluginContext;
//!
//! #[derive(Clone, Debug, PartialEq)]
//! struct RequestCount(u32);
//!
//! #[derive(Clone, Debug, PartialEq)]
//! struct CacheHits(u64);
//!
//! # #[tokio::main]
//! # async fn main() {
//! let ctx = PluginContext::new();
//!
//! // Insert typed state
//! ctx.insert(RequestCount(0)).await;
//! ctx.insert(CacheHits(42)).await;
//!
//! // Retrieve typed state
//! let count = ctx.get::<RequestCount>().await;
//! assert_eq!(count, Some(RequestCount(0)));
//!
//! // Update state (last write wins)
//! ctx.insert(RequestCount(5)).await;
//! let count = ctx.get::<RequestCount>().await;
//! assert_eq!(count, Some(RequestCount(5)));
//!
//! // Remove state
//! let removed = ctx.remove::<CacheHits>().await;
//! assert_eq!(removed, Some(CacheHits(42)));
//! assert_eq!(ctx.get::<CacheHits>().await, None);
//! # }
//! ```

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;

use tokio::sync::RwLock;

/// A type-safe, concurrent key-value store for plugin shared state.
///
/// Uses the TypeMap pattern where each type serves as its own key.
/// Thread-safe via [`tokio::sync::RwLock`] for concurrent async access.
///
/// # Concurrency
///
/// - Multiple readers can access state concurrently via [`get`](Self::get) and
///   [`contains`](Self::contains).
/// - Writers acquire exclusive access via [`insert`](Self::insert) and
///   [`remove`](Self::remove).
/// - No locks are held across await points — each method acquires and releases
///   the lock within a single operation.
///
/// # Examples
///
/// ```rust
/// use adk_plugin::PluginContext;
///
/// #[derive(Clone, Debug)]
/// struct RateLimitState {
///     requests_this_minute: u32,
/// }
///
/// # #[tokio::main]
/// # async fn main() {
/// let ctx = PluginContext::new();
///
/// // A rate-limiting plugin writes state
/// ctx.insert(RateLimitState { requests_this_minute: 1 }).await;
///
/// // A metrics plugin reads it
/// if let Some(state) = ctx.get::<RateLimitState>().await {
///     println!("Requests: {}", state.requests_this_minute);
/// }
/// # }
/// ```
pub struct PluginContext {
    state: RwLock<HashMap<TypeId, Box<dyn Any + Send + Sync>>>,
    /// The per-agent context this invocation's context reaches through `shared()`.
    shared: Option<Arc<PluginContext>>,
}

impl PluginContext {
    /// Creates a new empty `PluginContext`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use adk_plugin::PluginContext;
    ///
    /// let ctx = PluginContext::new();
    /// ```
    pub fn new() -> Self {
        Self { state: RwLock::new(HashMap::new()), shared: None }
    }

    /// Creates an empty context for one invocation whose [`shared`](Self::shared) context is
    /// `shared`.
    ///
    /// [`EnhancedPluginManager`](crate::EnhancedPluginManager) creates one per invocation
    /// over its per-agent context; build one directly to test a plugin outside a manager.
    /// Implements spec 3.1 §12 phase 0 (`PluginContext` per invocation).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use adk_plugin::PluginContext;
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Calls(u32);
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let agent_wide = Arc::new(PluginContext::new());
    /// let invocation = PluginContext::with_shared(Arc::clone(&agent_wide));
    ///
    /// invocation.insert(Calls(1)).await;
    /// invocation.shared().insert(Calls(7)).await;
    /// assert_eq!(invocation.get::<Calls>().await, Some(Calls(1)));
    /// assert_eq!(agent_wide.get::<Calls>().await, Some(Calls(7)));
    /// # }
    /// ```
    pub fn with_shared(shared: Arc<PluginContext>) -> Self {
        Self { state: RwLock::new(HashMap::new()), shared: Some(shared) }
    }

    /// Returns the context every invocation of the agent shares.
    ///
    /// Hooks receive their invocation's context; state that must outlive the invocation or
    /// be seen by other users' invocations, such as an agent-wide rate limit, goes here. A
    /// context created with [`new`](Self::new) has no separate shared context and returns
    /// itself. Implements spec 3.1 §12 phase 0 (`PluginContext` per invocation).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use adk_plugin::PluginContext;
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Limit(u32);
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let ctx = PluginContext::new();
    /// ctx.shared().insert(Limit(10)).await;
    /// assert_eq!(ctx.get::<Limit>().await, Some(Limit(10)));
    /// # }
    /// ```
    pub fn shared(&self) -> &PluginContext {
        self.shared.as_deref().unwrap_or(self)
    }

    /// Inserts a value into the context. The type itself is the key.
    ///
    /// If a value of the same type already exists, it is replaced.
    /// The previous value is discarded.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use adk_plugin::PluginContext;
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Counter(u32);
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let ctx = PluginContext::new();
    /// ctx.insert(Counter(1)).await;
    /// ctx.insert(Counter(2)).await; // Replaces the previous value
    ///
    /// assert_eq!(ctx.get::<Counter>().await, Some(Counter(2)));
    /// # }
    /// ```
    pub async fn insert<T: Send + Sync + 'static>(&self, value: T) {
        self.state.write().await.insert(TypeId::of::<T>(), Box::new(value));
    }

    /// Gets a clone of the stored value for type `T`.
    ///
    /// Returns `None` if no value of type `T` has been inserted.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use adk_plugin::PluginContext;
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Name(String);
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let ctx = PluginContext::new();
    ///
    /// assert_eq!(ctx.get::<Name>().await, None);
    ///
    /// ctx.insert(Name("alice".to_string())).await;
    /// assert_eq!(ctx.get::<Name>().await, Some(Name("alice".to_string())));
    /// # }
    /// ```
    pub async fn get<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
        self.state.read().await.get(&TypeId::of::<T>()).and_then(|v| v.downcast_ref::<T>()).cloned()
    }

    /// Checks if a value of type `T` exists in the context.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use adk_plugin::PluginContext;
    ///
    /// #[derive(Clone, Debug)]
    /// struct Marker;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let ctx = PluginContext::new();
    ///
    /// assert!(!ctx.contains::<Marker>().await);
    /// ctx.insert(Marker).await;
    /// assert!(ctx.contains::<Marker>().await);
    /// # }
    /// ```
    pub async fn contains<T: Send + Sync + 'static>(&self) -> bool {
        self.state.read().await.contains_key(&TypeId::of::<T>())
    }

    /// Removes a value of type `T`, returning it if present.
    ///
    /// After removal, [`get`](Self::get) and [`contains`](Self::contains) for
    /// type `T` will return `None` and `false` respectively.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use adk_plugin::PluginContext;
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Token(String);
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let ctx = PluginContext::new();
    /// ctx.insert(Token("abc".to_string())).await;
    ///
    /// let removed = ctx.remove::<Token>().await;
    /// assert_eq!(removed, Some(Token("abc".to_string())));
    /// assert_eq!(ctx.get::<Token>().await, None);
    /// # }
    /// ```
    pub async fn remove<T: Send + Sync + 'static>(&self) -> Option<T> {
        self.state
            .write()
            .await
            .remove(&TypeId::of::<T>())
            .and_then(|v| v.downcast::<T>().ok())
            .map(|b| *b)
    }
}

impl Default for PluginContext {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Clone, Debug, PartialEq)]
    struct Counter(u32);

    #[derive(Clone, Debug, PartialEq)]
    struct Name(String);

    #[tokio::test]
    async fn test_new_context_is_empty() {
        let ctx = PluginContext::new();
        assert!(!ctx.contains::<Counter>().await);
        assert_eq!(ctx.get::<Counter>().await, None);
    }

    #[tokio::test]
    async fn test_insert_and_get() {
        let ctx = PluginContext::new();
        ctx.insert(Counter(42)).await;

        let value = ctx.get::<Counter>().await;
        assert_eq!(value, Some(Counter(42)));
    }

    #[tokio::test]
    async fn test_insert_overwrites_previous() {
        let ctx = PluginContext::new();
        ctx.insert(Counter(1)).await;
        ctx.insert(Counter(99)).await;

        assert_eq!(ctx.get::<Counter>().await, Some(Counter(99)));
    }

    #[tokio::test]
    async fn test_multiple_types() {
        let ctx = PluginContext::new();
        ctx.insert(Counter(10)).await;
        ctx.insert(Name("hello".to_string())).await;

        assert_eq!(ctx.get::<Counter>().await, Some(Counter(10)));
        assert_eq!(ctx.get::<Name>().await, Some(Name("hello".to_string())));
    }

    #[tokio::test]
    async fn test_contains() {
        let ctx = PluginContext::new();
        assert!(!ctx.contains::<Counter>().await);

        ctx.insert(Counter(0)).await;
        assert!(ctx.contains::<Counter>().await);
    }

    #[tokio::test]
    async fn test_remove_returns_value() {
        let ctx = PluginContext::new();
        ctx.insert(Counter(7)).await;

        let removed = ctx.remove::<Counter>().await;
        assert_eq!(removed, Some(Counter(7)));
    }

    #[tokio::test]
    async fn test_remove_makes_get_return_none() {
        let ctx = PluginContext::new();
        ctx.insert(Counter(7)).await;
        ctx.remove::<Counter>().await;

        assert_eq!(ctx.get::<Counter>().await, None);
        assert!(!ctx.contains::<Counter>().await);
    }

    #[tokio::test]
    async fn test_remove_nonexistent_returns_none() {
        let ctx = PluginContext::new();
        let removed = ctx.remove::<Counter>().await;
        assert_eq!(removed, None);
    }

    #[tokio::test]
    async fn test_default_creates_empty_context() {
        let ctx = PluginContext::default();
        assert!(!ctx.contains::<Counter>().await);
    }

    #[tokio::test]
    async fn an_invocation_context_keeps_its_state_apart_from_the_shared_one() {
        let shared = Arc::new(PluginContext::new());
        let first = PluginContext::with_shared(Arc::clone(&shared));
        let second = PluginContext::with_shared(Arc::clone(&shared));

        first.insert(Counter(1)).await;
        assert_eq!(second.get::<Counter>().await, None);

        first.shared().insert(Name("agent-wide".to_string())).await;
        assert_eq!(second.shared().get::<Name>().await, Some(Name("agent-wide".to_string())));
        assert_eq!(second.get::<Name>().await, None);
    }

    #[tokio::test]
    async fn test_concurrent_access() {
        use std::sync::Arc;

        let ctx = Arc::new(PluginContext::new());
        ctx.insert(Counter(0)).await;

        let ctx_clone = Arc::clone(&ctx);
        let writer = tokio::spawn(async move {
            for i in 1..=100 {
                ctx_clone.insert(Counter(i)).await;
            }
        });

        let ctx_clone2 = Arc::clone(&ctx);
        let reader = tokio::spawn(async move {
            for _ in 0..100 {
                // Should never panic — reads are always valid
                let _ = ctx_clone2.get::<Counter>().await;
            }
        });

        writer.await.unwrap();
        reader.await.unwrap();

        // Final value should be 100 (last write)
        assert_eq!(ctx.get::<Counter>().await, Some(Counter(100)));
    }
}