adk_core/action_ledger.rs
1//! Durable record of tool calls whose side effects must not repeat.
2//!
3//! An [`ActionLedger`] records a [`ToolEffect::NonIdempotent`] call before it
4//! executes and its outcome after. A call replayed under the same
5//! [idempotency key](crate::ToolContext::idempotency_key) — after a crash, a
6//! timeout, or a cancelled run — is answered from the ledger instead of
7//! executing a second time:
8//!
9//! | Ledger state for the key | Agent behaviour |
10//! |--------------------------|-----------------|
11//! | No record | `begin`, execute, `complete` |
12//! | Completed | The recorded outcome is returned; the tool does not run |
13//! | Begun, not completed | An [`outcome_unknown_response`] is returned; the tool does not run |
14//! | Ledger read or `begin` fails | An error is returned; the tool does not run |
15//!
16//! The governance kill switch is checked again between `begin` and execution. A call it
17//! refuses there is completed as [`ActionOutcome::Failed`] with its [`not_run_text`], so the
18//! record never reads as begun without an outcome and a replay is answered with that text.
19
20use crate::{
21 AdkError, ErrorCategory, ErrorComponent, ReadonlyContext, Result, RunConfig, ToolEffect,
22 ToolResultStatus,
23};
24use async_trait::async_trait;
25use chrono::{DateTime, Utc};
26use serde::{Deserialize, Serialize};
27use serde_json::Value;
28use std::collections::HashMap;
29use std::sync::Arc;
30
31/// The `status` value of a function response whose side effects may or may not
32/// have happened.
33pub const OUTCOME_UNKNOWN_STATUS: &str = "outcome_unknown";
34
35/// Builds the function response for a call whose outcome is unknown.
36///
37/// The runtime returns this when a non-idempotent call timed out, panicked, was
38/// cancelled mid-flight, or has a ledger record that was begun but never
39/// completed. It tells the model and the operator that the side effect may have
40/// happened, so the call must not simply be repeated.
41///
42/// # Example
43///
44/// ```rust
45/// use adk_core::{OUTCOME_UNKNOWN_STATUS, outcome_unknown_response};
46///
47/// let response = outcome_unknown_response("the run was cancelled mid-call");
48/// assert_eq!(response["status"], OUTCOME_UNKNOWN_STATUS);
49/// assert_eq!(response["detail"], "the run was cancelled mid-call");
50/// ```
51pub fn outcome_unknown_response(detail: impl Into<String>) -> Value {
52 serde_json::json!({ "status": OUTCOME_UNKNOWN_STATUS, "detail": detail.into() })
53}
54
55/// The prefix of the text a call the governance kill switch refused is answered with.
56pub const NOT_RUN_PREFIX: &str = "not run: ";
57
58/// The text a call the governance kill switch refused with `refusal` is answered with:
59/// `not run: <refusal message>`. A call refused after [`ActionLedger::begin`] is completed
60/// as [`ActionOutcome::Failed`] with this text, so a replay answers it the same way.
61///
62/// # Example
63///
64/// ```rust
65/// use adk_core::{AdkError, is_not_run, not_run_text};
66///
67/// let text = not_run_text(&AdkError::agent("execution is frozen"));
68/// assert_eq!(text, "not run: execution is frozen");
69/// assert!(is_not_run(&text));
70/// ```
71pub fn not_run_text(refusal: &AdkError) -> String {
72 format!("{NOT_RUN_PREFIX}{}", refusal.message)
73}
74
75/// Returns `true` when `text` is a [`not_run_text`]: the call was refused and never ran.
76///
77/// # Example
78///
79/// ```rust
80/// assert!(adk_core::is_not_run("not run: execution is frozen"));
81/// assert!(!adk_core::is_not_run("card declined"));
82/// ```
83pub fn is_not_run(text: &str) -> bool {
84 text.starts_with(NOT_RUN_PREFIX)
85}
86
87/// Returns `true` when `response` is an [`outcome_unknown_response`].
88///
89/// # Example
90///
91/// ```rust
92/// use adk_core::{is_outcome_unknown, outcome_unknown_response};
93///
94/// assert!(is_outcome_unknown(&outcome_unknown_response("timed out")));
95/// assert!(!is_outcome_unknown(&serde_json::json!({ "status": "ok" })));
96/// ```
97pub fn is_outcome_unknown(response: &Value) -> bool {
98 response.get("status").and_then(Value::as_str) == Some(OUTCOME_UNKNOWN_STATUS)
99}
100
101/// Returns a stable digest of `value` in canonical JSON form, as `fnv1a128:<hex>`.
102///
103/// Object keys are sorted at every level, so structurally equal values produce
104/// the same digest, in every process and release. The ledger stores digests
105/// rather than arguments or results, so it never holds payment details or other
106/// tool payloads. The digest identifies a payload; it is not a cryptographic
107/// hash and does not prove that a payload was not altered.
108///
109/// # Example
110///
111/// ```rust
112/// use adk_core::json_digest;
113/// use serde_json::json;
114///
115/// let a = json_digest(&json!({ "amount": 50, "currency": "USD" }));
116/// let b = json_digest(&json!({ "currency": "USD", "amount": 50 }));
117/// assert_eq!(a, b);
118/// assert!(a.starts_with("fnv1a128:"));
119/// ```
120pub fn json_digest(value: &Value) -> String {
121 const OFFSET_BASIS: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
122 const PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013b;
123
124 let mut canonical = String::new();
125 crate::context::write_canonical(value, &mut canonical);
126 let hash = canonical
127 .bytes()
128 .fold(OFFSET_BASIS, |hash, byte| (hash ^ u128::from(byte)).wrapping_mul(PRIME));
129 format!("fnv1a128:{hash:032x}")
130}
131
132/// The result of a ledgered call, recorded by [`ActionLedger::complete`].
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(tag = "status", rename_all = "camelCase")]
135#[non_exhaustive]
136pub enum ActionOutcome {
137 /// The tool returned a value.
138 #[serde(rename_all = "camelCase")]
139 Succeeded {
140 /// [`json_digest`] of the value the tool returned.
141 result_digest: String,
142 },
143 /// The tool returned an error, or the governance kill switch refused the call between
144 /// [`ActionLedger::begin`] and execution, in which case `error` is its [`not_run_text`]
145 /// and the tool never ran ([`is_not_run`]).
146 #[serde(rename_all = "camelCase")]
147 Failed {
148 /// The error message the tool returned, or the [`not_run_text`] of a refused call.
149 error: String,
150 },
151}
152
153/// One ledgered tool call.
154///
155/// # Example
156///
157/// ```rust
158/// use adk_core::{ActionRecord, ToolEffect};
159/// use serde_json::json;
160///
161/// let record = ActionRecord::new(
162/// "app/user/session/inv-1/call-1",
163/// "payments_checkout_complete",
164/// &json!({ "transactionId": "tx-1" }),
165/// ToolEffect::NonIdempotent,
166/// );
167/// assert!(!record.is_completed());
168/// ```
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170#[serde(rename_all = "camelCase")]
171pub struct ActionRecord {
172 /// The call's [idempotency key](crate::ToolContext::idempotency_key).
173 pub key: String,
174 /// The name of the tool that was called.
175 pub tool_name: String,
176 /// [`json_digest`] of the call arguments.
177 pub args_digest: String,
178 /// The effect the tool declared when the call began.
179 pub effect: ToolEffect,
180 /// When the call began.
181 pub started_at: DateTime<Utc>,
182 /// The recorded outcome, or `None` while the call is in flight or after it
183 /// ended without one (crash, timeout, cancellation).
184 #[serde(default, skip_serializing_if = "Option::is_none")]
185 pub outcome: Option<ActionOutcome>,
186 /// When the outcome was recorded.
187 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub completed_at: Option<DateTime<Utc>>,
189}
190
191impl ActionRecord {
192 /// Creates a record for a call that begins now.
193 pub fn new(
194 key: impl Into<String>,
195 tool_name: impl Into<String>,
196 args: &Value,
197 effect: ToolEffect,
198 ) -> Self {
199 Self {
200 key: key.into(),
201 tool_name: tool_name.into(),
202 args_digest: json_digest(args),
203 effect,
204 started_at: Utc::now(),
205 outcome: None,
206 completed_at: None,
207 }
208 }
209
210 /// Returns `true` once an outcome has been recorded.
211 pub fn is_completed(&self) -> bool {
212 self.outcome.is_some()
213 }
214}
215
216/// Durable store of non-idempotent tool calls, keyed by idempotency key.
217///
218/// Set one on [`RunConfig::action_ledger`](crate::RunConfig::action_ledger).
219/// `LlmAgent` and `CodeActAgent` call [`begin`](Self::begin) before executing a
220/// [`ToolEffect::NonIdempotent`] tool and [`complete`](Self::complete) after,
221/// and consults [`get`](Self::get) first so a replayed call never executes
222/// twice. An error from `get` or `begin` fails the call closed: the tool is not
223/// executed.
224///
225/// # Example
226///
227/// ```rust
228/// use adk_core::{ActionLedger, ActionOutcome, ActionRecord, InMemoryActionLedger, ToolEffect};
229/// use serde_json::json;
230///
231/// #[tokio::main(flavor = "current_thread")]
232/// async fn main() -> adk_core::Result<()> {
233/// let ledger = InMemoryActionLedger::new();
234/// let record = ActionRecord::new("k1", "pay", &json!({}), ToolEffect::NonIdempotent);
235/// ledger.begin(&record).await?;
236/// assert!(ledger.begin(&record).await.is_err(), "a key begins once");
237///
238/// let outcome = ActionOutcome::Succeeded { result_digest: "fnv1a128:00".into() };
239/// ledger.complete("k1", outcome.clone()).await?;
240/// assert_eq!(ledger.get("k1").await?.and_then(|record| record.outcome), Some(outcome));
241/// Ok(())
242/// }
243/// ```
244#[async_trait]
245pub trait ActionLedger: std::fmt::Debug + Send + Sync {
246 /// Records that a call is about to execute.
247 ///
248 /// # Errors
249 ///
250 /// Returns an error when a record already exists under `record.key`, or when
251 /// the record cannot be stored. Either way the call must not execute.
252 async fn begin(&self, record: &ActionRecord) -> Result<()>;
253
254 /// Records the outcome of a call that [`begin`](Self::begin) recorded.
255 ///
256 /// # Errors
257 ///
258 /// Returns an error when no record exists under `key`, when one already has
259 /// an outcome, or when the outcome cannot be stored.
260 async fn complete(&self, key: &str, outcome: ActionOutcome) -> Result<()>;
261
262 /// Returns the record stored under `key`, if any.
263 ///
264 /// # Errors
265 ///
266 /// Returns an error when the ledger cannot be read.
267 async fn get(&self, key: &str) -> Result<Option<ActionRecord>>;
268}
269
270/// Builds the error a ledger returns when `begin` finds an existing record.
271///
272/// # Example
273///
274/// ```rust
275/// let error = adk_core::action_ledger::duplicate_key_error("k1");
276/// assert_eq!(error.code, "tool.action_ledger.duplicate_key");
277/// ```
278pub fn duplicate_key_error(key: &str) -> AdkError {
279 AdkError::new(
280 ErrorComponent::Tool,
281 ErrorCategory::InvalidInput,
282 "tool.action_ledger.duplicate_key",
283 format!(
284 "action ledger already holds a record for key '{key}'; the call was not executed again"
285 ),
286 )
287}
288
289/// Builds the error a ledger returns when `complete` cannot find the record.
290///
291/// # Example
292///
293/// ```rust
294/// let error = adk_core::action_ledger::missing_key_error("k1");
295/// assert!(error.is_not_found());
296/// ```
297pub fn missing_key_error(key: &str) -> AdkError {
298 AdkError::new(
299 ErrorComponent::Tool,
300 ErrorCategory::NotFound,
301 "tool.action_ledger.not_found",
302 format!("action ledger has no record for key '{key}'; call begin before complete"),
303 )
304}
305
306/// Builds the error a ledger returns when `complete` finds an outcome already recorded.
307///
308/// # Example
309///
310/// ```rust
311/// let error = adk_core::action_ledger::already_completed_error("k1");
312/// assert_eq!(error.code, "tool.action_ledger.already_completed");
313/// ```
314pub fn already_completed_error(key: &str) -> AdkError {
315 AdkError::new(
316 ErrorComponent::Tool,
317 ErrorCategory::InvalidInput,
318 "tool.action_ledger.already_completed",
319 format!("action ledger record '{key}' already has an outcome; outcomes are write-once"),
320 )
321}
322
323/// Process-local [`ActionLedger`].
324///
325/// Records survive a cancelled or timed-out run within one process but not a
326/// process restart. Use a durable implementation, such as
327/// `adk_session::SqliteActionLedger`, when calls must not repeat across restarts.
328///
329/// # Example
330///
331/// ```rust
332/// use adk_core::{InMemoryActionLedger, RunConfig};
333/// use std::sync::Arc;
334///
335/// let config = RunConfig::builder()
336/// .action_ledger(Arc::new(InMemoryActionLedger::new()))
337/// .build();
338/// assert!(config.action_ledger.is_some());
339/// ```
340#[derive(Debug, Default)]
341pub struct InMemoryActionLedger {
342 records: tokio::sync::RwLock<HashMap<String, ActionRecord>>,
343}
344
345impl InMemoryActionLedger {
346 /// Creates an empty ledger.
347 pub fn new() -> Self {
348 Self::default()
349 }
350}
351
352#[async_trait]
353impl ActionLedger for InMemoryActionLedger {
354 async fn begin(&self, record: &ActionRecord) -> Result<()> {
355 let mut records = self.records.write().await;
356 if records.contains_key(&record.key) {
357 return Err(duplicate_key_error(&record.key));
358 }
359 records.insert(record.key.clone(), record.clone());
360 Ok(())
361 }
362
363 async fn complete(&self, key: &str, outcome: ActionOutcome) -> Result<()> {
364 let mut records = self.records.write().await;
365 let record = records.get_mut(key).ok_or_else(|| missing_key_error(key))?;
366 if record.outcome.is_some() {
367 return Err(already_completed_error(key));
368 }
369 record.outcome = Some(outcome);
370 record.completed_at = Some(Utc::now());
371 Ok(())
372 }
373
374 async fn get(&self, key: &str) -> Result<Option<ActionRecord>> {
375 Ok(self.records.read().await.get(key).cloned())
376 }
377}
378
379/// The action-ledger key of a held tool call that a later run resumes.
380///
381/// A call's ledger key is normally its
382/// [`ToolContext::idempotency_key`](crate::ToolContext::idempotency_key), which names
383/// the invocation that runs it. A held call resumes in a later run, under that run's
384/// invocation, so a resumed call is keyed by its original identity instead: the
385/// session, the call ID the call was issued under, and a digest of the
386/// [`ToolConfirmationRequest::fingerprint`](crate::ToolConfirmationRequest::fingerprint)
387/// it was held with. Every resumption of the same held call shares one record, so a call
388/// that ran in a run whose result was never saved is answered from its record instead of
389/// running again (spec 3.1 §7.12, §9.2 I37).
390///
391/// # Example
392///
393/// ```rust
394/// use adk_core::{ToolConfirmationRequest, held_call_ledger_key};
395/// use serde_json::json;
396///
397/// let request = ToolConfirmationRequest::new("transfer", json!({ "amount": 40 }))
398/// .with_function_call_id("call-1");
399/// let key = held_call_ledger_key("app", "alice", "s1", "call-1", &request.fingerprint());
400/// assert!(key.starts_with("app/alice/s1/held/call-1/"));
401/// assert_eq!(key, held_call_ledger_key("app", "alice", "s1", "call-1", &request.fingerprint()));
402/// ```
403pub fn held_call_ledger_key(
404 app_name: &str,
405 user_id: &str,
406 session_id: &str,
407 function_call_id: &str,
408 fingerprint: &str,
409) -> String {
410 let digest = json_digest(&Value::String(fingerprint.to_string()));
411 format!("{app_name}/{user_id}/{session_id}/held/{function_call_id}/{digest}")
412}
413
414/// A call begun in the action ledger by [`begin_ledgered_call`], completed once the tool
415/// finishes.
416#[derive(Debug)]
417pub struct LedgeredCall {
418 ledger: Arc<dyn ActionLedger>,
419 key: String,
420}
421
422/// The ledger's answer to a call that must not execute, from [`begin_ledgered_call`].
423#[derive(Debug)]
424#[non_exhaustive]
425pub struct LedgerAnswer {
426 /// The function response that answers the call.
427 pub response: Value,
428 /// What the answer reports: the recorded outcome, or `NotRun` when the ledger failed.
429 pub status: ToolResultStatus,
430 /// The ledger's error, when it could not be read or written.
431 pub cause: Option<AdkError>,
432}
433
434/// Consults the run's action ledger ([`RunConfig::action_ledger`]) before a call executes.
435///
436/// Every runtime that dispatches tools — `LlmAgent`, `CodeActAgent` and the realtime
437/// agents — brackets a [`ToolEffect::NonIdempotent`] call with this step after the
438/// governed path authorizes it and before it executes.
439///
440/// Returns `Ok(Ok(None))` when the call is not ledgered (no ledger configured, or an
441/// effect other than [`ToolEffect::NonIdempotent`]), and `Ok(Ok(Some(_)))` once the
442/// call has been begun under `key`. Returns `Ok(Err(answer))` when the call must
443/// not execute: the ledger already holds a record for `key`, or cannot be read or
444/// written.
445///
446/// # Example
447///
448/// ```rust
449/// use std::sync::Arc;
450///
451/// use adk_core::{
452/// InMemoryActionLedger, ReadonlyContext, RunConfig, ToolEffect, begin_ledgered_call,
453/// };
454/// use serde_json::json;
455///
456/// struct Call;
457/// impl ReadonlyContext for Call {
458/// fn invocation_id(&self) -> &str { "inv-1" }
459/// fn agent_name(&self) -> &str { "voice" }
460/// fn user_id(&self) -> &str { "alice" }
461/// fn app_name(&self) -> &str { "app" }
462/// fn session_id(&self) -> &str { "s1" }
463/// fn branch(&self) -> &str { "" }
464/// fn user_content(&self) -> &adk_core::Content {
465/// static EMPTY: std::sync::OnceLock<adk_core::Content> = std::sync::OnceLock::new();
466/// EMPTY.get_or_init(|| adk_core::Content::new("user"))
467/// }
468/// }
469///
470/// # futures::executor::block_on(async {
471/// let config = RunConfig::builder().action_ledger(Arc::new(InMemoryActionLedger::new())).build();
472/// let args = json!({ "to": "tel:+14155550100" });
473/// let begun = begin_ledgered_call(&config, &Call, ToolEffect::NonIdempotent, "k1".into(), "transfer_call", &args)
474/// .await?
475/// .expect("no record yet")
476/// .expect("ledgered");
477/// begun.complete("transfer_call", Some(&json!({ "transferred": true })), "").await;
478///
479/// // A replay under the same key is answered from the record and does not execute.
480/// let replay = begin_ledgered_call(&config, &Call, ToolEffect::NonIdempotent, "k1".into(), "transfer_call", &args)
481/// .await?;
482/// assert_eq!(replay.unwrap_err().response["status"], "already_succeeded");
483/// # Ok::<(), adk_core::AdkError>(())
484/// # }).unwrap();
485/// ```
486///
487/// # Errors
488///
489/// Returns `audit.record_failed`, which ends the run, when an outcome-unknown answer
490/// cannot be audited under [`AuditFailureMode::Block`](crate::audit_log::AuditFailureMode::Block).
491pub async fn begin_ledgered_call(
492 config: &RunConfig,
493 ctx: &dyn ReadonlyContext,
494 effect: ToolEffect,
495 key: String,
496 name: &str,
497 args: &Value,
498) -> Result<std::result::Result<Option<LedgeredCall>, LedgerAnswer>> {
499 let ledger = match &config.action_ledger {
500 Some(ledger) if effect == ToolEffect::NonIdempotent => ledger.clone(),
501 _ => return Ok(Ok(None)),
502 };
503 let mut status = ToolResultStatus::NotRun;
504 let mut cause = None;
505 let response = match ledger.get(&key).await {
506 Ok(Some(record)) => {
507 status = ToolResultStatus::of_record(record.outcome.as_ref());
508 match record.outcome {
509 Some(ActionOutcome::Succeeded { result_digest }) => serde_json::json!({
510 "status": "already_succeeded",
511 "result_digest": result_digest,
512 "detail": format!("this call to '{name}' already completed; it was not executed again"),
513 }),
514 Some(ActionOutcome::Failed { error }) => serde_json::json!({
515 "status": "already_failed",
516 "error": error,
517 "detail": format!("this call to '{name}' already failed; it was not executed again"),
518 }),
519 _ => {
520 record_outcome_unknown(config, ctx, name, args, "began_without_outcome")
521 .await?;
522 outcome_unknown_response(format!(
523 "an earlier attempt of this call to '{name}' began but recorded no outcome, so it may have taken effect; it was not executed again"
524 ))
525 }
526 }
527 }
528 // A store error can name its connection, so the model is given its code only.
529 Ok(None) => match ledger.begin(&ActionRecord::new(key.clone(), name, args, effect)).await {
530 Ok(()) => return Ok(Ok(Some(LedgeredCall { ledger, key }))),
531 Err(error) => {
532 tracing::error!(tool.name = %name, error = %error, "action ledger could not record the call");
533 let response = serde_json::json!({
534 "error": format!("tool '{name}' was not executed: the action ledger could not record the call: {}", error.redacted())
535 });
536 cause = Some(error);
537 response
538 }
539 },
540 Err(error) => {
541 tracing::error!(tool.name = %name, error = %error, "action ledger could not be read");
542 let response = serde_json::json!({
543 "error": format!("tool '{name}' was not executed: the action ledger could not be read: {}", error.redacted())
544 });
545 cause = Some(error);
546 response
547 }
548 };
549 tracing::warn!(
550 tool.name = %name,
551 tool.idempotency_key = %key,
552 response = %response,
553 "non-idempotent call answered by the action ledger without executing"
554 );
555 Ok(Err(LedgerAnswer { response, status, cause }))
556}
557
558/// Records, through the run's [`RunConfig::audit`], a call answered with an unknown
559/// outcome. `cause` is `interrupted` for a call that ended mid-flight and
560/// `began_without_outcome` for a replay of one.
561///
562/// # Errors
563///
564/// Returns `audit.record_failed` when the record cannot be written under
565/// [`AuditFailureMode::Block`](crate::audit_log::AuditFailureMode::Block).
566pub async fn record_outcome_unknown(
567 config: &RunConfig,
568 ctx: &dyn ReadonlyContext,
569 name: &str,
570 args: &Value,
571 cause: &str,
572) -> Result<()> {
573 use crate::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
574
575 let Some(trail) = &config.audit else {
576 return Ok(());
577 };
578 let draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, name)
579 .actor(AuditActor::for_context(ctx))
580 .args_digest(trail.digest(args))
581 .outcome(AuditRecordOutcome::OutcomeUnknown)
582 .ext("cause", Value::String(cause.to_string()))
583 .ext("sessionId", Value::String(ctx.session_id().to_string()));
584 trail.record(draft).await
585}
586
587impl LedgeredCall {
588 /// Records the outcome of a call that ran to an end: `result` when the tool
589 /// returned a value, otherwise `error`, the text the model was given for the
590 /// failure, since a replay of the call is answered with it. A call the kill switch
591 /// refused between `begin` and execution is completed here too, as `Failed` with its
592 /// [`not_run_text`]: it never ran.
593 ///
594 /// A call that ended mid-flight (timeout, panic) must not be completed, so
595 /// its begun record answers a replay with an unknown outcome.
596 pub async fn complete(self, name: &str, result: Option<&Value>, error: &str) {
597 let outcome = match result {
598 Some(value) => ActionOutcome::Succeeded { result_digest: json_digest(value) },
599 None => ActionOutcome::Failed { error: error.to_string() },
600 };
601 if let Err(error) = self.ledger.complete(&self.key, outcome).await {
602 tracing::error!(
603 tool.name = %name,
604 tool.idempotency_key = %self.key,
605 error = %error,
606 "action ledger could not record the outcome; a replay will report it as unknown"
607 );
608 }
609 }
610}
611
612/// The function response for a non-idempotent call that ended mid-flight with
613/// `error`.
614///
615/// # Example
616///
617/// ```rust
618/// use adk_core::{interrupted_call_response, is_outcome_unknown};
619///
620/// assert!(is_outcome_unknown(&interrupted_call_response("Tool 'pay' timed out after 30s")));
621/// ```
622pub fn interrupted_call_response(error: &str) -> Value {
623 outcome_unknown_response(format!(
624 "{error}. The call may have taken effect; check its result before calling it again."
625 ))
626}
627
628#[cfg(test)]
629mod tests {
630 use super::*;
631 use serde_json::json;
632
633 #[tokio::test]
634 async fn in_memory_ledger_round_trips_a_completed_record() {
635 let ledger = InMemoryActionLedger::new();
636 let record = ActionRecord::new("k", "pay", &json!({"a": 1}), ToolEffect::NonIdempotent);
637 ledger.begin(&record).await.unwrap();
638 assert_eq!(ledger.get("k").await.unwrap(), Some(record.clone()));
639
640 let outcome = ActionOutcome::Failed { error: "declined".into() };
641 ledger.complete("k", outcome.clone()).await.unwrap();
642 let stored = ledger.get("k").await.unwrap().unwrap();
643 assert_eq!(stored.outcome, Some(outcome.clone()));
644 assert!(stored.completed_at.is_some());
645
646 let error = ledger.complete("k", outcome).await.unwrap_err();
647 assert_eq!(error.code, "tool.action_ledger.already_completed");
648 }
649
650 #[tokio::test]
651 async fn in_memory_ledger_rejects_duplicates_and_unknown_keys() {
652 let ledger = InMemoryActionLedger::new();
653 let record = ActionRecord::new("k", "pay", &json!({}), ToolEffect::NonIdempotent);
654 ledger.begin(&record).await.unwrap();
655 assert_eq!(
656 ledger.begin(&record).await.unwrap_err().code,
657 "tool.action_ledger.duplicate_key"
658 );
659 let missing = ledger
660 .complete("other", ActionOutcome::Succeeded { result_digest: String::new() })
661 .await
662 .unwrap_err();
663 assert!(missing.is_not_found());
664 assert_eq!(ledger.get("other").await.unwrap(), None);
665 }
666
667 #[test]
668 fn action_record_serializes_camel_case() {
669 let mut record = ActionRecord::new("k", "pay", &json!({}), ToolEffect::NonIdempotent);
670 record.outcome = Some(ActionOutcome::Succeeded { result_digest: "fnv1a128:ab".into() });
671 let value = serde_json::to_value(&record).unwrap();
672 assert_eq!(value["toolName"], "pay");
673 assert_eq!(value["effect"], "non_idempotent");
674 assert_eq!(value["outcome"], json!({"status": "succeeded", "resultDigest": "fnv1a128:ab"}));
675 let back: ActionRecord = serde_json::from_value(value).unwrap();
676 assert_eq!(back, record);
677 }
678
679 #[test]
680 fn json_digest_ignores_key_order_and_distinguishes_values() {
681 assert_eq!(json_digest(&json!({"a": 1, "b": 2})), json_digest(&json!({"b": 2, "a": 1})));
682 assert_ne!(json_digest(&json!({"a": 1})), json_digest(&json!({"a": 2})));
683 assert_eq!(json_digest(&json!(null)).len(), "fnv1a128:".len() + 32);
684 // The algorithm is fixed, so a digest stored by one release matches the next.
685 assert_eq!(json_digest(&json!({"a": 1})), "fnv1a128:a930e708924ff78dd36054201cd38dc9");
686 }
687}