aidaemon_core/state.rs
1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6use crate::approval::{EffectKey, InterruptKind, SharedDeclines};
7use crate::limits::LimitGrants;
8use crate::message::{Message, ToolCall};
9use crate::provider::Usage;
10use crate::receipt::Receipt;
11use crate::stuck::StuckState;
12use crate::tool::Finish;
13
14/// Version of the [`RunState`] serialization format this kernel writes and
15/// can resume. State saved before the field existed reads as version 1.
16/// Bump it when a change would make older saved state resume wrongly, and
17/// teach `resume` to migrate or refuse the old version.
18///
19/// Version 2 added [`Pending::child`]. A version 1 snapshot has no child and
20/// means the same thing under version 2, so it loads as is. A kernel that
21/// knows only version 1 must refuse version 2: it would drop the child and
22/// take the child's interruption for the parent's own.
23pub const RUN_STATE_SCHEMA: u32 = 2;
24
25fn first_schema() -> u32 {
26 1
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(transparent)]
31pub struct RunId(Uuid);
32
33impl RunId {
34 pub fn new() -> Self {
35 Self(Uuid::new_v4())
36 }
37}
38
39impl Default for RunId {
40 fn default() -> Self {
41 Self::new()
42 }
43}
44
45impl fmt::Display for RunId {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 self.0.fmt(f)
48 }
49}
50
51/// Why the run paused.
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53pub struct Interruption {
54 /// The call waiting for a decision. It has not run. In a parent paused
55 /// for a child ([`Pending::child`]) this is the child's call, at whatever
56 /// depth it is waiting, so the approver is shown what would really run.
57 pub call: ToolCall,
58 pub reason: String,
59 /// Who the interruption waits for. State saved before kinds existed
60 /// reads as [`InterruptKind::Untrusted`].
61 #[serde(default)]
62 pub kind: InterruptKind,
63 /// A keyed digest binding an answer to exactly this question: the
64 /// run, the call (id, tool, canonical arguments), the hook that asked
65 /// and a nonce. `Resolution::Approve` is honored only for the call it
66 /// was given for, and only once; see [`crate::Agent::resume`]. `None`
67 /// in state saved before digests existed (an approval of it is judged
68 /// again from the first hook).
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub digest: Option<String>,
71}
72
73/// The unfinished tool batch of an interrupted turn.
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
75pub struct Pending {
76 #[doc(hidden)]
77 pub calls: Vec<ToolCall>,
78 /// Index of the interrupted call; earlier calls already have results.
79 #[doc(hidden)]
80 pub next: usize,
81 pub interruption: Interruption,
82 /// Index of the hook that interrupted. An approval settles that hook
83 /// only: hooks registered after it still judge the call on resume.
84 #[serde(default)]
85 #[doc(hidden)]
86 pub hook_index: Option<usize>,
87 /// The hooks that were installed when the run paused. `hook_index` means
88 /// nothing under a different chain, so an approval is judged again from
89 /// the first hook when this does not match.
90 #[serde(default)]
91 #[doc(hidden)]
92 pub hook_chain: Vec<String>,
93 /// The paused run of a child this call started, when the interrupted
94 /// call is a tool that delegates ([`crate::Tool::suspends`]). The call at
95 /// `next` is already inside that tool, so an answer goes to the child (at
96 /// any depth) and the call's result is what the child ends with.
97 /// [`Pending::interruption`] is then a copy of the deepest run's.
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub child: Option<Box<RunState>>,
100 /// Hooks the owner already answered for this same call (unchanged
101 /// since), bound by [`Interruption::digest`]: an approval waives them
102 /// with the one that asked last.
103 #[serde(default, skip_serializing_if = "Vec::is_empty")]
104 #[doc(hidden)]
105 pub waived: Vec<usize>,
106}
107
108/// A tool batch that was executing when the state was last saved. Present
109/// only in checkpoints taken mid-turn; used for crash recovery.
110#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
111pub struct InFlight {
112 pub calls: Vec<ToolCall>,
113 /// Calls that were handed to their tool.
114 #[serde(default)]
115 pub started: Vec<String>,
116 /// Calls whose result is already in the transcript.
117 #[serde(default)]
118 pub done: Vec<String>,
119}
120
121/// A finish a dispatched call returned in the current batch, kept until the
122/// batch ends (across an interruption or a restart) and then applied.
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124pub struct PendingFinish {
125 pub finish: Finish,
126 /// The name of the tool whose call returned it.
127 pub tool: String,
128}
129
130/// Everything needed to continue a run, as plain serializable data.
131///
132/// Persist it anywhere (a database row, a file, a queue message) and hand it
133/// to [`crate::Agent::resume`] later. Agents are matched by their stable
134/// `agent_id`, never by position or display name.
135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
136pub struct RunState {
137 /// See [`RUN_STATE_SCHEMA`]; read it with [`RunState::schema`].
138 #[serde(default = "first_schema")]
139 pub(crate) schema: u32,
140 pub run_id: RunId,
141 pub agent_id: String,
142 pub session_id: String,
143 /// Transcript without the agent's instructions (those are re-sent on
144 /// every request).
145 pub messages: Vec<Message>,
146 /// Receipts of every run in this session. Each carries its `run_id`;
147 /// use [`RunState::run_receipts`] for the current run only.
148 pub receipts: Vec<Receipt>,
149 /// Token usage of every run in this session.
150 pub usage: Usage,
151 /// Token usage of the current run only. Budgets in [`crate::Limits`]
152 /// are checked against this, like `turn` and `tool_calls`.
153 #[serde(default)]
154 pub run_usage: Usage,
155 pub turn: u32,
156 pub tool_calls: u32,
157 /// Wall-clock time already spent, summed across resumes.
158 pub elapsed_ms: u64,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub pending: Option<Pending>,
161 /// Kernel bookkeeping for crash recovery (see `aidaemon-store-sqlite`'s
162 /// `in_flight_runs`), not part of the stable API.
163 #[doc(hidden)]
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub in_flight: Option<InFlight>,
166 #[doc(hidden)]
167 #[serde(default)]
168 pub nudges: u32,
169 /// The run has seen untrusted content (a dispatched call whose result
170 /// was authored by someone else, whatever its status), or was seeded
171 /// that way. Never cleared within a run.
172 #[serde(default)]
173 pub untrusted_seen: bool,
174 #[serde(default)]
175 pub(crate) stuck: StuckState,
176 /// Effects the owner declined in this run (deduplicated). The kernel
177 /// records a denied [`InterruptKind::OwnerApproval`] request's effects
178 /// here; hooks read them through [`crate::HookContext::declined`]. A new
179 /// run ([`RunState::with_user_message`]) starts with none.
180 #[serde(default)]
181 pub declined: Vec<EffectKey>,
182 /// Declines shared with related runs (a parent and its children), set
183 /// with [`RunState::share_declines`]. A runtime handle, never
184 /// serialized: `declined` is the run's record, and a resumed run shares
185 /// again once the application reattaches a set.
186 #[serde(skip)]
187 pub(crate) shared_declines: Option<SharedDeclines>,
188 /// Requirements stop hooks reported as unmet when the run stopped
189 /// ([`crate::StopDecision::AcceptUnmet`]), deduplicated, in hook order.
190 /// Set only when the run ends `Completed`; a new run
191 /// ([`RunState::with_user_message`]) starts with none.
192 #[serde(default, skip_serializing_if = "Vec::is_empty")]
193 pub unmet: Vec<String>,
194 /// The first finish a call returned in the unfinished batch; the run
195 /// ends with it once the batch ends (see [`crate::ToolOutput::finish`]).
196 #[doc(hidden)]
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub finishing: Option<PendingFinish>,
199 /// How far `on_limit` hooks raised this run's limits. A new run
200 /// ([`RunState::with_user_message`]) starts with none.
201 #[doc(hidden)]
202 #[serde(default)]
203 pub limit_grants: LimitGrants,
204 /// The run whose tool call started this one, if any.
205 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub parent_run: Option<RunId>,
207 /// `on_stop` continuations since the last new successful call.
208 #[serde(default)]
209 pub(crate) idle_continuations: u32,
210 /// Successful calls of this run when `idle_continuations` last changed.
211 #[serde(default)]
212 pub(crate) continued_at_successes: usize,
213 /// The deferred tools already loaded when this run first built a
214 /// request; `None` before that. Kept with the state so a run resumed
215 /// after an interruption sends the same tool block (the front of the
216 /// provider's prompt cache) instead of treating its own loads as old.
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub(crate) loaded_at_start: Option<std::collections::BTreeSet<String>>,
219 /// The deferred tools this run loaded, each after the batch that did.
220 #[serde(default, skip_serializing_if = "Vec::is_empty")]
221 pub(crate) tool_loads: Vec<crate::provider::ToolLoad>,
222}
223
224impl RunState {
225 /// A fresh state for a new run, so callers know the run id before it
226 /// starts. Run it with [`crate::Agent::run_from`].
227 /// `input` is text or a user [`Message`] (for example one with images).
228 pub fn new(agent_id: &str, session_id: &str, input: impl Into<Message>) -> Self {
229 Self {
230 schema: RUN_STATE_SCHEMA,
231 run_id: RunId::new(),
232 agent_id: agent_id.to_string(),
233 session_id: session_id.to_string(),
234 messages: vec![input.into()],
235 receipts: Vec::new(),
236 usage: Usage::default(),
237 run_usage: Usage::default(),
238 turn: 0,
239 tool_calls: 0,
240 elapsed_ms: 0,
241 pending: None,
242 in_flight: None,
243 nudges: 0,
244 untrusted_seen: false,
245 stuck: StuckState::default(),
246 declined: Vec::new(),
247 shared_declines: None,
248 unmet: Vec::new(),
249 finishing: None,
250 limit_grants: LimitGrants::default(),
251 parent_run: None,
252 idle_continuations: 0,
253 continued_at_successes: 0,
254 loaded_at_start: None,
255 tool_loads: Vec::new(),
256 }
257 }
258
259 /// Record the run whose tool call started this one.
260 pub fn with_parent(mut self, parent: RunId) -> Self {
261 self.parent_run = Some(parent);
262 self
263 }
264
265 /// Start the run as if it had already read untrusted content (the
266 /// caller knows the input itself is someone else's).
267 pub fn with_untrusted_context(mut self) -> Self {
268 self.untrusted_seen = true;
269 self
270 }
271
272 /// Continue an earlier, finished run with a new user message (same
273 /// session, new run). Session receipts and `usage` keep accumulating;
274 /// per-run counters and budgets (`turn`, `tool_calls`, `run_usage`,
275 /// elapsed time) start again from zero, and the run's
276 /// [`RunState::declined`] effects and [`RunState::unmet`] requirements
277 /// are forgotten, as is any [`SharedDeclines`] set: the new run shares
278 /// only a set attached to it.
279 pub fn with_user_message(mut self, input: impl Into<Message>) -> Self {
280 self.messages.push(input.into());
281 self.run_id = RunId::new();
282 self.run_usage = Usage::default();
283 self.turn = 0;
284 self.tool_calls = 0;
285 self.elapsed_ms = 0;
286 self.nudges = 0;
287 self.in_flight = None;
288 self.stuck.reset();
289 self.declined.clear();
290 self.shared_declines = None;
291 self.unmet.clear();
292 self.finishing = None;
293 self.limit_grants = LimitGrants::default();
294 self.idle_continuations = 0;
295 self.continued_at_successes = 0;
296 self.loaded_at_start = None;
297 self.tool_loads.clear();
298 self
299 }
300
301 /// Share this run's declines with the other runs holding `declines`
302 /// (see [`SharedDeclines`]): each is refused the others' declined
303 /// effects from its next call on. The run's own declines are published
304 /// at once and the set's are taken in. Attach it again after resuming
305 /// saved state: the handle is not serialized.
306 pub fn share_declines(mut self, declines: SharedDeclines) -> Self {
307 declines.exchange(&mut self.declined);
308 self.shared_declines = Some(declines);
309 self
310 }
311
312 /// The decline set this run shares, if any.
313 pub fn shared_declines(&self) -> Option<&SharedDeclines> {
314 self.shared_declines.as_ref()
315 }
316
317 /// Take in what the runs sharing this run's set declined and publish
318 /// this run's own. Returns whether this run's declines grew.
319 pub(crate) fn sync_declines(&mut self) -> bool {
320 match self.shared_declines.as_ref() {
321 Some(shared) => shared.exchange(&mut self.declined),
322 None => false,
323 }
324 }
325
326 /// The run actually waiting for an answer: this one, or the child it is
327 /// paused for, at any depth. `None` when this run is not interrupted.
328 pub fn waiting_run(&self) -> Option<&RunState> {
329 let mut run = self;
330 run.pending.as_ref()?;
331 while let Some(child) = run.pending.as_ref().and_then(|p| p.child.as_deref()) {
332 run = child;
333 }
334 Some(run)
335 }
336
337 /// The serialization format version this state was written with.
338 pub fn schema(&self) -> u32 {
339 self.schema
340 }
341
342 /// Receipts produced by the current run (not earlier runs in the session).
343 pub fn run_receipts(&self) -> impl Iterator<Item = &Receipt> {
344 let run_id = self.run_id;
345 self.receipts.iter().filter(move |r| r.run_id == run_id)
346 }
347}