adk_agent/codeact/checkpoint.rs
1//! The suspend/resume payload, persisted in **session state**.
2//!
3//! There is no side store. When the agent suspends (a confirmation-gated or
4//! long-running tool call), it serializes the live interpreter continuation
5//! (Monty snapshot) plus the loop transcript into a [`CodeActCheckpoint`] and
6//! writes it to session state under [`PENDING_STATE_KEY`] via an event's
7//! `state_delta`. On the next invocation `CodeActAgent::run` reads it back and
8//! resumes — the same "save to session, rebuild, continue" model as
9//! [`LlmAgent`](crate::LlmAgent), with the snapshot standing in for the part of
10//! the continuation that can't be reconstructed from message history.
11
12use adk_core::Content;
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15
16/// Session-state key under which the pending checkpoint is stored.
17pub const PENDING_STATE_KEY: &str = "codeact_pending";
18
19/// The tool call a suspended run is waiting on.
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub struct PendingToolCall {
22 /// The interpreter call id (for correlating the eventual response).
23 pub call_id: u64,
24 /// The tool the script invoked.
25 pub tool: String,
26 /// The arguments the tool was called with.
27 pub args: Value,
28}
29
30/// The result to feed back into a resumed continuation.
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub enum ResolutionRecord {
33 /// Return this value from the tool call.
34 Value(Value),
35 /// Raise an error at the tool call site, with this message.
36 Raise(String),
37}
38
39/// Why a checkpoint was written, and how to resume from it.
40///
41/// The first two bracket every inline tool call (a write-ahead log); the last
42/// two are external pauses.
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44#[serde(tag = "kind", rename_all = "snake_case")]
45pub enum Disposition {
46 /// Written **before** an inline tool runs. On recovery the call is re-run to
47 /// produce the result; a non-idempotent call recorded in the action ledger is
48 /// answered from its record instead of executing again.
49 PendingResult,
50 /// Written **after** an inline tool returns. On recovery the continuation is
51 /// resumed with the stored result — the tool is **not** re-run.
52 Resolved(ResolutionRecord),
53 /// A confirmation-gated tool is awaiting a human decision (delivered via
54 /// `RunConfig::tool_confirmation_decisions` on the next invocation).
55 AwaitingConfirmation,
56 /// A long-running tool was started; its result arrives out-of-band as a
57 /// `FunctionResponse` in the next invocation's message.
58 AwaitingCompletion {
59 /// The pending handle the tool's `execute()` returned (e.g. a task id).
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pending_handle: Option<Value>,
62 },
63}
64
65/// A serializable snapshot of a suspended CodeAct run, stored in session state.
66///
67/// Does not derive `PartialEq` because [`Content`] does not; compare via the
68/// serialized form when equality is needed.
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct CodeActCheckpoint {
71 /// The model turn this run was on.
72 pub iteration: u32,
73 /// The model <-> observation transcript accumulated so far.
74 pub transcript: Vec<Content>,
75 /// The serialized interpreter continuation, paused at [`call`](Self::call).
76 pub snapshot: Vec<u8>,
77 /// The tool call being awaited.
78 pub call: PendingToolCall,
79 /// Why it suspended / how to resume.
80 pub disposition: Disposition,
81 /// The tool roster at suspend time, to detect a mismatched resume (the
82 /// external-function set is baked into the snapshot).
83 pub tool_roster: Vec<String>,
84 /// The agent run that wrote this checkpoint.
85 ///
86 /// Tool-call idempotency keys are scoped to it, so a call replayed from this
87 /// checkpoint in a later invocation keeps its key and the action ledger
88 /// answers it instead of executing it again. `None` in checkpoints written
89 /// before the field existed; resuming one starts a new scope.
90 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub run_id: Option<String>,
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97 use serde_json::json;
98
99 #[test]
100 fn checkpoint_round_trips_through_json() {
101 let cp = CodeActCheckpoint {
102 iteration: 2,
103 transcript: vec![Content::new("user").with_text("hi")],
104 snapshot: vec![1, 2, 3],
105 call: PendingToolCall { call_id: 7, tool: "slow".into(), args: json!({"x": 1}) },
106 disposition: Disposition::AwaitingCompletion {
107 pending_handle: Some(json!({"task": "t1"})),
108 },
109 tool_roster: vec!["slow".into()],
110 run_id: Some("run-1".into()),
111 };
112 let value = serde_json::to_value(&cp).unwrap();
113 let back: CodeActCheckpoint = serde_json::from_value(value.clone()).unwrap();
114 assert_eq!(value, serde_json::to_value(&back).unwrap());
115 }
116
117 #[test]
118 fn dispositions_round_trip() {
119 for case in [
120 Disposition::PendingResult,
121 Disposition::Resolved(ResolutionRecord::Value(json!(1))),
122 Disposition::Resolved(ResolutionRecord::Raise("boom".into())),
123 Disposition::AwaitingConfirmation,
124 Disposition::AwaitingCompletion { pending_handle: Some(json!("h")) },
125 Disposition::AwaitingCompletion { pending_handle: None },
126 ] {
127 let v = serde_json::to_value(&case).unwrap();
128 assert_eq!(case, serde_json::from_value(v).unwrap());
129 }
130 }
131}