adk-managed 1.0.0

Managed agent runtime for ADK-Rust — durable, resumable, provider-neutral agent execution
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Testing utilities for the managed agent runtime.
//!
//! This module provides deterministic test doubles for the managed agent runtime
//! pipeline. These are **not mocks** — they implement the real traits and exercise
//! the full runtime pipeline (parking, checkpoints, replay, event mapping). Only
//! the LLM provider API call is replaced with pre-scripted deterministic responses.
//!
//! # Architecture
//!
//! ```text
//! ScriptedLlm (deterministic responses)
//!//!//! Full runtime pipeline (SessionLoop, CheckpointManager, ToolParkingLot, etc.)
//!//!//! SessionEvent stream (byte-identical assertions possible)
//! ```
//!
//! # Usage
//!
//! ```rust,ignore
//! use adk_managed::testing::{ScriptedLlm, ScriptedTurn, ScriptedToolCall};
//! use serde_json::json;
//!
//! let turns = vec![
//!     ScriptedTurn {
//!         text: Some("Hello! How can I help you?".to_string()),
//!         tool_calls: vec![],
//!     },
//!     ScriptedTurn {
//!         text: None,
//!         tool_calls: vec![ScriptedToolCall {
//!             name: "web_search".to_string(),
//!             input: json!({"query": "rust async"}),
//!             id: Some("tc_001".to_string()),
//!         }],
//!     },
//! ];
//!
//! let llm = ScriptedLlm::new("scripted-model", turns);
//! // Use llm in place of any Arc<dyn Llm> in the runtime pipeline
//! ```

use adk_core::{
    Llm, LlmRequest, LlmResponse, LlmResponseStream, Result as AdkResult, types::Content,
};
use async_stream::stream;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicUsize, Ordering};

/// A pre-scripted turn that the [`ScriptedLlm`] will return.
///
/// Each turn represents one complete LLM response. It can contain text content,
/// tool calls, or both — mirroring real LLM behavior where a response may
/// include reasoning text followed by tool invocations.
///
/// # Wire Format
///
/// Serializes to/from JSON for use in fixture files:
///
/// ```json
/// {
///   "text": "Let me search for that.",
///   "tool_calls": [
///     { "name": "web_search", "input": {"query": "rust"}, "id": "tc_001" }
///   ]
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScriptedTurn {
    /// Text response content (if any).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Tool calls to make (if any).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ScriptedToolCall>,
}

/// A scripted tool call within a [`ScriptedTurn`].
///
/// Represents a function call that the LLM "decides" to make.
/// The `id` field maps to the tool_use_id / function call ID used
/// for round-trip correlation with tool results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScriptedToolCall {
    /// Name of the tool to call.
    pub name: String,
    /// Input arguments as JSON.
    pub input: serde_json::Value,
    /// Optional tool call ID. If not provided, a deterministic ID is generated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
}

/// A deterministic LLM double with pre-scripted responses.
///
/// `ScriptedLlm` implements the real [`Llm`] trait and exercises the full
/// runtime pipeline. Only the provider API call is replaced — everything else
/// (session loop, checkpoints, parking, event mapping) runs exactly as it would
/// with a real provider.
///
/// This is explicitly **NOT a mock**. It:
/// - Implements the full `Llm` trait contract
/// - Returns complete `LlmResponse` objects with proper `Content` and `Part` types
/// - Supports tool calls (function calls) in responses
/// - Advances through turns deterministically (FIFO order)
/// - Is thread-safe (`Send + Sync` via `AtomicUsize`)
///
/// # Panics
///
/// If more turns are requested than were scripted, the LLM returns an empty
/// response with `turn_complete = true` rather than panicking.
pub struct ScriptedLlm {
    /// Model name identifier.
    name: String,
    /// Pre-scripted turns in FIFO order.
    turns: Vec<ScriptedTurn>,
    /// Current turn index (atomic for thread safety).
    current_turn: AtomicUsize,
}

impl ScriptedLlm {
    /// Create a new `ScriptedLlm` with the given name and pre-scripted turns.
    ///
    /// Turns are consumed in FIFO order — each call to `generate_content`
    /// advances to the next turn.
    pub fn new(name: impl Into<String>, turns: Vec<ScriptedTurn>) -> Self {
        Self { name: name.into(), turns, current_turn: AtomicUsize::new(0) }
    }

    /// Returns the number of turns that have been consumed so far.
    pub fn turns_consumed(&self) -> usize {
        self.current_turn.load(Ordering::Relaxed)
    }

    /// Returns the total number of scripted turns.
    pub fn total_turns(&self) -> usize {
        self.turns.len()
    }

    /// Build an `LlmResponse` from a `ScriptedTurn`.
    fn build_response(turn: &ScriptedTurn, turn_index: usize) -> LlmResponse {
        use adk_core::FinishReason;
        use adk_core::types::Part;

        let mut parts = Vec::new();

        // Add text part if present.
        if let Some(text) = &turn.text {
            parts.push(Part::Text { text: text.clone() });
        }

        // Add function call parts.
        for (i, tool_call) in turn.tool_calls.iter().enumerate() {
            let id =
                tool_call.id.clone().unwrap_or_else(|| format!("scripted_tc_{turn_index}_{i}"));
            parts.push(Part::FunctionCall {
                name: tool_call.name.clone(),
                args: tool_call.input.clone(),
                id: Some(id),
                thought_signature: None,
            });
        }

        let content = if parts.is_empty() {
            None
        } else {
            Some(Content { role: "model".to_string(), parts })
        };

        LlmResponse {
            content,
            usage_metadata: None,
            finish_reason: Some(FinishReason::Stop),
            citation_metadata: None,
            partial: false,
            turn_complete: true,
            interrupted: false,
            error_code: None,
            error_message: None,
            provider_metadata: None,
            interaction_id: None,
        }
    }
}

impl std::fmt::Debug for ScriptedLlm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScriptedLlm")
            .field("name", &self.name)
            .field("turns", &self.turns.len())
            .field("current_turn", &self.current_turn.load(Ordering::Relaxed))
            .finish()
    }
}

#[async_trait]
impl Llm for ScriptedLlm {
    fn name(&self) -> &str {
        &self.name
    }

    async fn generate_content(
        &self,
        _request: LlmRequest,
        _stream: bool,
    ) -> AdkResult<LlmResponseStream> {
        let turn_index = self.current_turn.fetch_add(1, Ordering::Relaxed);

        let response = if turn_index < self.turns.len() {
            Self::build_response(&self.turns[turn_index], turn_index)
        } else {
            // Beyond scripted turns — return empty complete response.
            LlmResponse {
                content: Some(Content {
                    role: "model".to_string(),
                    parts: vec![adk_core::types::Part::Text {
                        text: "[ScriptedLlm: no more scripted turns]".to_string(),
                    }],
                }),
                usage_metadata: None,
                finish_reason: Some(adk_core::FinishReason::Stop),
                citation_metadata: None,
                partial: false,
                turn_complete: true,
                interrupted: false,
                error_code: None,
                error_message: None,
                provider_metadata: None,
                interaction_id: None,
            }
        };

        let response_stream = stream! {
            yield Ok(response);
        };

        Ok(Box::pin(response_stream))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::StreamExt;
    use serde_json::json;

    #[tokio::test]
    async fn test_scripted_llm_returns_text() {
        let turns =
            vec![ScriptedTurn { text: Some("Hello, world!".to_string()), tool_calls: vec![] }];
        let llm = ScriptedLlm::new("test-model", turns);

        assert_eq!(llm.name(), "test-model");

        let request = LlmRequest::new("test-model", vec![]);
        let mut stream = llm.generate_content(request, false).await.unwrap();

        let response = stream.next().await.unwrap().unwrap();
        assert!(response.turn_complete);
        assert!(!response.partial);

        let content = response.content.unwrap();
        assert_eq!(content.role, "model");
        assert_eq!(content.parts.len(), 1);
        match &content.parts[0] {
            adk_core::types::Part::Text { text } => {
                assert_eq!(text, "Hello, world!");
            }
            other => panic!("expected Text part, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_scripted_llm_returns_tool_calls() {
        let turns = vec![ScriptedTurn {
            text: None,
            tool_calls: vec![ScriptedToolCall {
                name: "web_search".to_string(),
                input: json!({"query": "rust async"}),
                id: Some("tc_001".to_string()),
            }],
        }];
        let llm = ScriptedLlm::new("tool-model", turns);

        let request = LlmRequest::new("tool-model", vec![]);
        let mut stream = llm.generate_content(request, false).await.unwrap();

        let response = stream.next().await.unwrap().unwrap();
        let content = response.content.unwrap();
        assert_eq!(content.parts.len(), 1);
        match &content.parts[0] {
            adk_core::types::Part::FunctionCall { name, args, id, .. } => {
                assert_eq!(name, "web_search");
                assert_eq!(args, &json!({"query": "rust async"}));
                assert_eq!(id, &Some("tc_001".to_string()));
            }
            other => panic!("expected FunctionCall part, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_scripted_llm_advances_through_turns() {
        let turns = vec![
            ScriptedTurn { text: Some("First".to_string()), tool_calls: vec![] },
            ScriptedTurn { text: Some("Second".to_string()), tool_calls: vec![] },
            ScriptedTurn { text: Some("Third".to_string()), tool_calls: vec![] },
        ];
        let llm = ScriptedLlm::new("multi-turn", turns);

        for (i, expected) in ["First", "Second", "Third"].iter().enumerate() {
            let request = LlmRequest::new("multi-turn", vec![]);
            let mut stream = llm.generate_content(request, false).await.unwrap();
            let response = stream.next().await.unwrap().unwrap();
            let content = response.content.unwrap();
            match &content.parts[0] {
                adk_core::types::Part::Text { text } => {
                    assert_eq!(text, *expected);
                }
                other => panic!("turn {i}: expected Text, got: {other:?}"),
            }
        }

        assert_eq!(llm.turns_consumed(), 3);
    }

    #[tokio::test]
    async fn test_scripted_llm_handles_exhaustion() {
        let turns = vec![ScriptedTurn { text: Some("Only one".to_string()), tool_calls: vec![] }];
        let llm = ScriptedLlm::new("exhausted", turns);

        // Consume the only turn.
        let request = LlmRequest::new("exhausted", vec![]);
        let mut stream = llm.generate_content(request, false).await.unwrap();
        let _ = stream.next().await.unwrap().unwrap();

        // Next call should return a fallback.
        let request = LlmRequest::new("exhausted", vec![]);
        let mut stream = llm.generate_content(request, false).await.unwrap();
        let response = stream.next().await.unwrap().unwrap();
        assert!(response.turn_complete);
        let content = response.content.unwrap();
        match &content.parts[0] {
            adk_core::types::Part::Text { text } => {
                assert!(text.contains("no more scripted turns"));
            }
            other => panic!("expected fallback Text, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_scripted_llm_mixed_text_and_tool_calls() {
        let turns = vec![ScriptedTurn {
            text: Some("Let me search for that.".to_string()),
            tool_calls: vec![ScriptedToolCall {
                name: "web_search".to_string(),
                input: json!({"query": "ADK Rust"}),
                id: Some("tc_mixed".to_string()),
            }],
        }];
        let llm = ScriptedLlm::new("mixed", turns);

        let request = LlmRequest::new("mixed", vec![]);
        let mut stream = llm.generate_content(request, false).await.unwrap();
        let response = stream.next().await.unwrap().unwrap();
        let content = response.content.unwrap();

        assert_eq!(content.parts.len(), 2);
        assert!(matches!(&content.parts[0], adk_core::types::Part::Text { .. }));
        assert!(matches!(&content.parts[1], adk_core::types::Part::FunctionCall { .. }));
    }

    #[tokio::test]
    async fn test_scripted_turn_serialization_roundtrip() {
        let turn = ScriptedTurn {
            text: Some("Hello".to_string()),
            tool_calls: vec![ScriptedToolCall {
                name: "search".to_string(),
                input: json!({"q": "test"}),
                id: Some("id_1".to_string()),
            }],
        };

        let json = serde_json::to_string(&turn).unwrap();
        let deserialized: ScriptedTurn = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.text, turn.text);
        assert_eq!(deserialized.tool_calls.len(), 1);
        assert_eq!(deserialized.tool_calls[0].name, "search");
        assert_eq!(deserialized.tool_calls[0].id, Some("id_1".to_string()));
    }

    #[tokio::test]
    async fn test_auto_generated_tool_call_ids() {
        let turns = vec![ScriptedTurn {
            text: None,
            tool_calls: vec![
                ScriptedToolCall {
                    name: "tool_a".to_string(),
                    input: json!({}),
                    id: None, // auto-generate
                },
                ScriptedToolCall {
                    name: "tool_b".to_string(),
                    input: json!({}),
                    id: None, // auto-generate
                },
            ],
        }];
        let llm = ScriptedLlm::new("auto-id", turns);

        let request = LlmRequest::new("auto-id", vec![]);
        let mut stream = llm.generate_content(request, false).await.unwrap();
        let response = stream.next().await.unwrap().unwrap();
        let content = response.content.unwrap();

        // Both should have deterministic IDs based on turn and index.
        match &content.parts[0] {
            adk_core::types::Part::FunctionCall { id, .. } => {
                assert_eq!(id, &Some("scripted_tc_0_0".to_string()));
            }
            other => panic!("expected FunctionCall, got: {other:?}"),
        }
        match &content.parts[1] {
            adk_core::types::Part::FunctionCall { id, .. } => {
                assert_eq!(id, &Some("scripted_tc_0_1".to_string()));
            }
            other => panic!("expected FunctionCall, got: {other:?}"),
        }
    }
}