1use std::{fmt, sync::Arc};
2
3use runifold_core::{
4 CapabilityId, Checkpoint, CheckpointError, CheckpointErrorKind, CheckpointId, CheckpointStore,
5 RunContext, Usage,
6};
7use runifold_model::{Message, ModelRef, ModelResponse};
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11use crate::conversation::{ConversationId, ConversationVersion, MemoryNamespace};
12use crate::{
13 AgentError, AgentOutcome, TerminalRequirementFailure, TerminalReviewPolicy,
14 TerminalReviewerDescriptor, TurnReviewPolicy,
15};
16
17const CHECKPOINT_KIND: &str = "runifold.agent";
18const CHECKPOINT_SCHEMA_VERSION: u32 = 1;
19
20#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
22#[non_exhaustive]
23pub enum ResumePolicy {
24 #[default]
26 RejectAmbiguous,
27 RetryInterruptedTurn,
31}
32
33#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
35#[serde(tag = "state", rename_all = "snake_case")]
36#[non_exhaustive]
37pub enum AgentCheckpointPhase {
38 ReadyForTurn,
40 TurnInFlight {
42 turn: u32,
44 },
45 Completed {
47 response: Box<ModelResponse>,
49 },
50 TerminalRequirementFailed {
53 failure: TerminalRequirementFailure,
55 attempts: u32,
57 },
58 TurnReviewReady {
61 response: Box<ModelResponse>,
63 turn: u32,
65 },
66 TurnReviewInFlight {
69 response: Box<ModelResponse>,
71 turn: u32,
73 },
74 TurnReviewApproved {
77 response: Box<ModelResponse>,
79 turn: u32,
81 },
82 TurnReviewRejected {
84 response: Box<ModelResponse>,
86 turn: u32,
88 reason: String,
90 attempts: u32,
92 },
93 TurnReviewExhausted {
95 response: Box<ModelResponse>,
97 turn: u32,
99 feedback: Value,
101 attempts: u32,
103 },
104 TerminalReviewReady {
106 response: Box<ModelResponse>,
108 attempt: u32,
110 },
111 TerminalReviewInFlight {
113 response: Box<ModelResponse>,
115 attempt: u32,
117 },
118 TerminalReviewRejected {
120 response: Box<ModelResponse>,
122 reason: String,
124 attempts: u32,
126 },
127 TerminalReviewExhausted {
129 response: Box<ModelResponse>,
131 feedback: Value,
133 attempts: u32,
135 },
136}
137
138#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
140pub struct DurableConversationCheckpoint {
141 pub conversation_id: ConversationId,
143 pub namespace: MemoryNamespace,
145 pub expected_version: ConversationVersion,
147 pub persisted_prefix_len: u64,
149}
150
151#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
153pub struct AgentCheckpointState {
154 pub execution_id: String,
156 pub agent: String,
158 pub model: ModelRef,
160 pub transcript: Vec<Message>,
162 pub turns: u32,
164 pub tool_calls: u32,
166 pub delegations: u32,
168 pub usage: Usage,
170 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub turn_reviewer: Option<TerminalReviewerDescriptor>,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub turn_review_policy: Option<TurnReviewPolicy>,
176 #[serde(default, skip_serializing_if = "Vec::is_empty")]
178 pub turn_reviewer_capabilities: Vec<CapabilityId>,
179 #[serde(default, skip_serializing_if = "Option::is_none")]
181 pub terminal_reviewer: Option<TerminalReviewerDescriptor>,
182 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub terminal_review_policy: Option<TerminalReviewPolicy>,
185 #[serde(default, skip_serializing_if = "Vec::is_empty")]
187 pub terminal_reviewer_capabilities: Vec<CapabilityId>,
188 pub phase: AgentCheckpointPhase,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub durable_conversation: Option<DurableConversationCheckpoint>,
193}
194
195impl AgentCheckpointState {
196 pub(crate) fn outcome(&self) -> Option<AgentOutcome> {
197 match &self.phase {
198 AgentCheckpointPhase::Completed { response } => Some(AgentOutcome {
199 response: response.as_ref().clone(),
200 transcript: self.transcript.clone(),
201 turns: self.turns,
202 tool_calls: self.tool_calls,
203 delegations: self.delegations,
204 usage: self.usage,
205 }),
206 _ => None,
207 }
208 }
209
210 pub(crate) fn terminal_failure(&self) -> Option<AgentError> {
211 match &self.phase {
212 AgentCheckpointPhase::TerminalRequirementFailed {
213 failure, attempts, ..
214 } => Some(super::agent::completion::failure_error(failure, *attempts)),
215 AgentCheckpointPhase::TerminalReviewRejected { reason, .. } => {
216 Some(AgentError::TerminalReviewRejected {
217 reason: reason.clone(),
218 })
219 }
220 AgentCheckpointPhase::TerminalReviewExhausted { attempts, .. } => {
221 Some(AgentError::TerminalReviewExhausted {
222 attempts: *attempts,
223 })
224 }
225 AgentCheckpointPhase::TurnReviewRejected { reason, .. } => {
226 Some(AgentError::TurnReviewRejected {
227 reason: reason.clone(),
228 })
229 }
230 AgentCheckpointPhase::TurnReviewExhausted { attempts, .. } => {
231 Some(AgentError::TurnReviewExhausted {
232 attempts: *attempts,
233 })
234 }
235 _ => None,
236 }
237 }
238}
239
240#[derive(Clone)]
242pub struct AgentCheckpoint {
243 id: CheckpointId,
244 store: Arc<dyn CheckpointStore>,
245}
246
247impl AgentCheckpoint {
248 pub fn new(store: Arc<dyn CheckpointStore>) -> Self {
250 Self {
251 id: CheckpointId::new(),
252 store,
253 }
254 }
255
256 pub fn existing(id: CheckpointId, store: Arc<dyn CheckpointStore>) -> Self {
258 Self { id, store }
259 }
260
261 pub const fn id(&self) -> CheckpointId {
263 self.id
264 }
265
266 pub fn load(&self) -> Result<(Checkpoint, AgentCheckpointState), CheckpointError> {
272 let checkpoint = self.store.load(self.id)?;
273 if checkpoint.kind != CHECKPOINT_KIND
274 || checkpoint.schema_version != CHECKPOINT_SCHEMA_VERSION
275 {
276 return Err(CheckpointError::new(
277 CheckpointErrorKind::InvalidPayload,
278 "checkpoint kind or schema version is not supported",
279 ));
280 }
281 let state = serde_json::from_value(checkpoint.payload.clone()).map_err(|error| {
282 CheckpointError::new(CheckpointErrorKind::InvalidPayload, error.to_string())
283 })?;
284 Ok((checkpoint, state))
285 }
286}
287
288impl fmt::Debug for AgentCheckpoint {
289 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
290 formatter
291 .debug_struct("AgentCheckpoint")
292 .field("id", &self.id)
293 .finish_non_exhaustive()
294 }
295}
296
297pub(crate) struct CheckpointCursor {
298 handle: AgentCheckpoint,
299 envelope: Checkpoint,
300}
301
302impl CheckpointCursor {
303 pub(crate) fn create(
304 handle: &AgentCheckpoint,
305 run: &RunContext,
306 state: &AgentCheckpointState,
307 ) -> Result<Self, AgentError> {
308 let payload = serialize(state)?;
309 let envelope = Checkpoint::initial(
310 handle.id,
311 run.run_id(),
312 CHECKPOINT_KIND,
313 CHECKPOINT_SCHEMA_VERSION,
314 payload,
315 );
316 handle.store.compare_and_swap(&envelope, None)?;
317 Ok(Self {
318 handle: handle.clone(),
319 envelope,
320 })
321 }
322
323 pub(crate) fn loaded(handle: &AgentCheckpoint, envelope: Checkpoint) -> Self {
324 Self {
325 handle: handle.clone(),
326 envelope,
327 }
328 }
329
330 pub(crate) fn save(&mut self, state: &AgentCheckpointState) -> Result<(), AgentError> {
331 let next = self.envelope.next(serialize(state)?)?;
332 self.handle
333 .store
334 .compare_and_swap(&next, Some(self.envelope.revision))?;
335 self.envelope = next;
336 Ok(())
337 }
338
339 pub(crate) fn next(&self, state: &AgentCheckpointState) -> Result<Checkpoint, AgentError> {
340 self.envelope.next(serialize(state)?).map_err(Into::into)
341 }
342
343 pub(crate) const fn revision(&self) -> u64 {
344 self.envelope.revision
345 }
346
347 pub(crate) const fn id(&self) -> CheckpointId {
348 self.envelope.id
349 }
350}
351
352fn serialize(state: &AgentCheckpointState) -> Result<serde_json::Value, AgentError> {
353 serde_json::to_value(state).map_err(|error| {
354 CheckpointError::new(CheckpointErrorKind::InvalidPayload, error.to_string()).into()
355 })
356}