Skip to main content

adk_server/background/
worker.rs

1//! The durable worker: claims runs from a [`DurableRunStore`] under fenced leases and
2//! executes them.
3//!
4//! # Lifecycle of one claimed run
5//!
6//! 1. [`claim`](DurableRunStore::claim) returns the run with a fencing epoch.
7//! 2. The worker heartbeats every `lease_ttl / 3`. A heartbeat that reports a
8//!    cancellation request stops the run cooperatively; one that fails with
9//!    `run_store.stale_epoch` (another worker recovered the run) drops the execution at
10//!    once, and the worker writes nothing more.
11//! 3. The target runs: an agent through its [`Runner`], or a workflow through the
12//!    [`WorkflowExecutor`]. The worker records where the run is checkpointed with
13//!    [`set_checkpoint`](DurableRunStore::set_checkpoint) before any progress is made.
14//! 4. [`finish`](DurableRunStore::finish) ends the attempt, fenced by the epoch. An agent
15//!    run that ends holding a tool call for approval is parked instead: the worker records
16//!    [`RunCheckpointRef::AwaitingApproval`] and calls
17//!    [`wait`](DurableRunStore::wait); a [`wake`](DurableRunStore::wake) after the
18//!    decision makes it claimable, and the claim resumes the same session so the held call
19//!    executes with its decision.
20//!
21//! # Calls a person asked for
22//!
23//! An agent run's input `{"text": ..., "requestedCall": RequestedCall}` carries a call a
24//! person asked for through something the agent drew (spec 3.3 §7.4 rule 5). On a run an
25//! authenticated caller enqueued, the start of the run sets [`RunConfig::requested_call`],
26//! and the agent holds the call for the person's decision, so the run parks as above; on any
27//! other run the call is ignored. A woken run continues as any parked run does.
28//!
29//! [`RunConfig::requested_call`]: adk_core::RunConfig::requested_call
30//!
31//! # Run limits
32//!
33//! An agent run's input can narrow what the runner allows under `runLimits`
34//! ([`RunLimits`](adk_core::RunLimits)); it can never widen it, so any caller that may enqueue
35//! a run may set them:
36//!
37//! | `runLimits` field | Effect |
38//! |-------------------|--------|
39//! | `budget` ([`RunBudget`](adk_core::RunBudget) in camelCase, wall time in `maxWallTimeMs`) | The run's budget is the stricter of the runner's and this one ([`RunBudget::narrowed`](adk_core::RunBudget::narrowed)) |
40//! | `allowedTools` (tool names) | [`ToolCeiling`](adk_core::ToolCeiling) layered under the run's or the runner's tool policy with [`StrictestPolicy`](adk_core::StrictestPolicy): a call to any other tool is denied |
41//!
42//! A background sub-agent's run ([`DurableSubagents`](super::DurableSubagents)) also carries
43//! `subagent`: its budget tracker resumes from what the sub-agent's session shows it spent
44//! ([`spent_in_session`](adk_core::subagent::spent_in_session)), so the slice covers all its
45//! runs and every recovered attempt. An input whose `runLimits` cannot be read fails the run
46//! without retry.
47//!
48//! # Fencing a stalled worker
49//!
50//! A worker that stalls (a long pause, a partition) can wake after its lease expired and
51//! another worker recovered the run. Every run-store write carries the epoch and is
52//! refused. For agent runs the worker also installs a lease fence as invocation hooks:
53//! before each model call and tool call, and after each model response and tool result,
54//! the fence checks that the lease is still provably held — the last successful heartbeat
55//! was sent less than `lease_ttl` ago. When it is not, the fence never returns, the
56//! execution is dropped, and no further session event, tool call, or store write happens.
57//!
58//! # Kill switch
59//!
60//! A worker with a governance control ([`DurableWorker::with_governance`]) claims nothing
61//! while the control refuses work. A claim already in flight when the control starts
62//! refusing can still return a run, so the worker checks the control again before it runs
63//! the target:
64//!
65//! | Refused | Worker |
66//! |---------|--------|
67//! | Once the claim returns | Hands the run back unstarted |
68//! | By the runner before the agent produced an event (its start check, or the check before the first model call) | Hands the run back unstarted, when the worker's own control also refuses |
69//! | After the run made a model or tool call, under [`GovernanceRefusal::Park`] (the default) | Parks the run at its next model-call boundary, as [Freeze parks](self#freeze-parks) describes |
70//! | After the run made a model or tool call, under [`GovernanceRefusal::Fail`], or by the runner's control on a worker with none | Ends the attempt with the control's error |
71//!
72//! A run handed back is parked with [`wait`](DurableRunStore::wait) until the time it was
73//! claimed: it is `Waiting`, claimable at once, and the claim that resumes it counts no
74//! further attempt.
75//!
76//! # Freeze parks
77//!
78//! Under [`DurableWorkerConfig::on_governance_refusal`] = [`GovernanceRefusal::Park`], a
79//! run the control refuses after it made a model or tool call stops at its next model-call
80//! boundary (spec 3.2 §10 S3): the tool calls of the model's last turn are answered —
81//! those the kill switch refused as `not run` — the worker records
82//! `RunCheckpointRef::Session`, parks the run with [`wait`](DurableRunStore::wait) until
83//! woken, and reports [`ParkReason::Frozen`]. A freeze-parked run never expires. The worker
84//! keeps the ids of the runs it parked this way and wakes exactly those once its control
85//! allows work again, so an unfreeze resumes them and never a run suspended by
86//! [`suspend`](DurableWorker::suspend); [`wake_frozen`](DurableWorker::wake_frozen) does the
87//! same on demand. A resumed run continues its session as [Crash resume](self#crash-resume)
88//! describes, and the action ledger keeps a completed call from running twice.
89//! [`request_cancel`](DurableRunStore::request_cancel) still finishes a parked run
90//! `Cancelled`.
91//!
92//! The park appends the system notice [`FREEZE_PAUSED_NOTICE`] to the session
93//! ([`system_notice_event`](adk_core::history::system_notice_event), authored `system`). The
94//! claim that resumes the run, on any worker, finds it as the parked invocation's latest
95//! notice, writes a [`FREEZE_RESUMED_ACTION`] audit record, and appends
96//! [`FREEZE_RESUMED_NOTICE`], so the model's next request says that the freeze is over and that
97//! the calls it refused did not run, instead of ending the task at a `not run` answer. A run
98//! no freeze parked — suspended, woken by an approval, or recovered after a crash — resumes
99//! without one. A notice authorizes nothing: a refused call made again goes through the
100//! governed path.
101//!
102//! Only a worker with a governance control parks this way, since its own control is what
103//! tells it the freeze is over. The list of parked runs lives in the worker's memory: a
104//! worker restarted while frozen does not wake the runs parked before the restart, so a
105//! supervisor that must survive restarts records each [`ParkReason::Frozen`] it receives
106//! through [`WorkerHooks::on_park`] and wakes those runs itself.
107//!
108//! # Idle waits
109//!
110//! The claim loop waits `poll_interval` when nothing is claimable, or until the earliest
111//! `not_before` of a queued or parked run on its queue when that comes first, so a delayed
112//! run or a timed wait resumes at its time rather than at the next poll (spec 3.2 §7.9,
113//! §13 Q2).
114//!
115//! # Identity
116//!
117//! An agent run acts as the runner's own principal for its root agent (its identity
118//! source, or the derived `urn:adk:agent:{app}/{agent}`), on behalf of the run's user.
119//! A principal stored on the run ([`RunRecord::principal`]) is a claim made by whoever
120//! enqueued it, so the worker honours it only within these rules, and otherwise fails the
121//! run without retry and records the refusal on the audit trail:
122//!
123//! | Stored principal | Worker |
124//! |------------------|--------|
125//! | None | Acts as its own principal, for the run's user as a human |
126//! | Agent id is the worker's own or the derived id of the target | Acts as its own principal |
127//! | Agent id is in [`DurableWorkerConfig::allowed_principals`] | Acts as the stored principal |
128//! | Any other agent id | Refused with `identity.principal_not_allowed` |
129//! | Subject is the run's user | Acts for the user as the stored subject's kind (a scheduled, webhook, or queue run is a service) |
130//! | Subject is anyone else | Passed to the runner, which refuses it with `identity.subject_mismatch` unless its `SubjectDelegationPolicy` allows it; a delegation chain headed by the run's user gives the user's subject kind |
131//!
132//! The allowlist is empty by default.
133//!
134//! A target served from a shared [`AgentTable`] is admitted by the same rules: its derived
135//! id is `urn:adk:agent:{app}/{target}`, so an agent hosted after the worker started acts
136//! as itself with no allowlist entry (spec 3.3 §10 S4).
137//!
138//! # Live targets
139//!
140//! A worker reads its targets on every claim (spec 3.3 §10 S4): first those registered with
141//! [`with_agent`](DurableWorker::with_agent), then a shared [`AgentTable`] set with
142//! [`with_agent_table`](DurableWorker::with_agent_table), then its workflows.
143//!
144//! | Claimed target | Worker |
145//! |----------------|--------|
146//! | Registered with `with_agent`, or hosted in the table | Runs it; a runner swapped in the table serves the next claim, and a claim already running finishes on the runner it started on |
147//! | Expected by the table, not built yet | Hands the run back unstarted, claimable again one `poll_interval` later; [`on_park`](WorkerHooks::on_park) with [`ParkReason::HandedBack`] |
148//! | A workflow the executor knows | Runs the workflow |
149//! | Anything else | Fails the run without retry |
150//!
151//! # Crash resume
152//!
153//! A run recovered after its lease expired resumes rather than restarting:
154//!
155//! | Target | Checkpoint | What the recovering worker does |
156//! |--------|------------|--------------------------------|
157//! | Agent | `Session { session_id, invocation_id }` | Answers calls the stopped worker left unanswered from the action ledger ([`Runner::recover_unanswered_calls`]); completes the run from the session when it already holds the final answer; otherwise continues the same session with an empty user turn, so the model sees the whole conversation, including the recovered call outcomes, and nothing is sent twice |
158//! | Workflow | `Graph { thread_id, checkpoint_id }` | Calls the workflow again with [`WorkflowRunContext::resumed`] set and the same `thread_id`; a graph workflow resumes from its checkpointer |
159//!
160//! No tool executes again during recovery. A non-idempotent call that began but recorded
161//! no outcome is answered `outcome_unknown`; one that completed is answered from its
162//! ledger record. A run whose original user turn never reached the session (the worker
163//! stopped before the checkpoint was recorded) starts again from its input.
164//!
165//! # Lifecycle hooks
166//!
167//! [`WorkerHooks`] registered with [`DurableWorker::with_hooks`] observe every state change
168//! the worker writes (spec 3.2 §10 S1). Each hook runs after the store write it reports, so
169//! the store already shows the state the hook receives:
170//!
171//! | Hook | Called | The run it receives |
172//! |------|--------|---------------------|
173//! | [`on_claim`](WorkerHooks::on_claim) | Once the worker starts the claimed run's target, before any model call or workflow step | `Running`, at the claim's epoch |
174//! | [`on_park`](WorkerHooks::on_park) | After [`wait`](DurableRunStore::wait) parked the run, with the [`ParkReason`] | `Waiting`, holding no lease |
175//! | [`on_finish`](WorkerHooks::on_finish) | After [`finish`](DurableRunStore::finish) wrote the attempt's outcome | `Completed`, `Failed`, or `Cancelled`; `Queued` when a retryable failure requeued it |
176//! | [`on_event`](WorkerHooks::on_event) | For each event an agent turn yields, partial chunks included, as the worker reads it | `Running`, as claimed |
177//!
178//! [`wake_input`](WorkerHooks::wake_input) is the one hook that returns something: the
179//! reason an agent run was woken, which the worker gives the turn it starts as user
180//! content, once per session.
181//!
182//! A run the worker hands back at once, because its governance control refused work when
183//! the claim returned, is reported to `on_park` only: its target never started. An attempt
184//! that lost its lease writes nothing and calls no hook; the worker that recovers the run
185//! reports it.
186//!
187//! # Suspending a run
188//!
189//! [`DurableWorker::suspend`] (or [`WorkerHandle::suspend`]) asks an agent run in flight on
190//! this worker to stop at its next model-call boundary and park, so it resumes later rather
191//! than ending (spec 3.2 §10 S1):
192//!
193//! 1. The tool calls the model already asked for finish and their responses reach the
194//!    session; no further model call is made.
195//! 2. The worker interrupts the turn, records `RunCheckpointRef::Session` on the
196//!    interrupted invocation, and parks the run with [`wait`](DurableRunStore::wait) until
197//!    woken: it is `Waiting`, holds no lease, and is claimable only after
198//!    [`wake`](DurableRunStore::wake).
199//! 3. The claim after the wake, by any worker, continues the session at the same attempt,
200//!    as [Crash resume](self#crash-resume) describes; a non-idempotent call that completed
201//!    before the suspension is never executed again.
202//!
203//! | Requested | Outcome |
204//! |-----------|---------|
205//! | `suspend` | Parked `Waiting` on its `Session` checkpoint; [`on_park`](WorkerHooks::on_park) with [`ParkReason::Suspended`] |
206//! | `suspend`, then the governance control refuses the run at that boundary | Parked the same way, with [`ParkReason::Suspended`], so an unfreeze does not wake it; refused before its first event, it is handed back as [Kill switch](self#kill-switch) describes |
207//! | [`request_cancel`](DurableRunStore::request_cancel), with or without `suspend` | Finished `Cancelled`, as before |
208//! | `suspend`, and the turn ends without another model call | Finished, or parked on its held tool calls, as without the request |
209//!
210//! Only agent runs are suspendable: a workflow run has no model-call boundary the worker
211//! can stop at, so `suspend` returns `false` for it and it runs on.
212
213use std::collections::{BTreeMap, BTreeSet, HashMap};
214use std::sync::Arc;
215use std::sync::atomic::{AtomicBool, Ordering};
216use std::time::Duration;
217
218use adk_core::audit_log::{
219    AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome, AuditTrail,
220};
221use adk_core::history::SYSTEM_NOTICE_PREFIX;
222use adk_core::{
223    ActingConfig, AdkError, AgentId, AgentPrincipal, BeforeModelResult, CallbackContext,
224    ClaimedRun, Clock, Content, DurableRunStore, ErrorCategory, ErrorComponent, Event,
225    GOVERNANCE_FROZEN_CODE, GOVERNANCE_STALE_CODE, GovernanceControl, InvocationHooks, LlmRequest,
226    LlmResponse, PRINCIPAL_NOT_ALLOWED_CODE, Part, RequestedCall, RunCheckpointRef, RunFilter,
227    RunOutcome, RunRecord, RunState, SessionId, SystemClock, UserId,
228    run_store::{RUN_NOT_FOUND_CODE, RUN_STALE_EPOCH_CODE, RetryBackoff},
229};
230use adk_runner::Runner;
231use async_trait::async_trait;
232use futures::StreamExt;
233use serde_json::Value;
234use tokio::sync::Notify;
235use tokio::time::Instant;
236use tokio_util::sync::CancellationToken;
237
238use super::table::AgentTable;
239use super::{WorkflowExecutor, WorkflowRunContext, WorkflowState};
240
241/// The shortest idle wait, so a deadline the wall clock has passed but the store has not
242/// released yet never spins the claim loop.
243const IDLE_FLOOR: Duration = Duration::from_millis(25);
244
245/// What a [`DurableWorker`] does with a run its governance control refuses after the run
246/// made a model or tool call (spec 3.2 §10 S3).
247///
248/// # Example
249///
250/// ```rust
251/// use adk_server::background::{DurableWorkerConfig, GovernanceRefusal};
252///
253/// let config = DurableWorkerConfig::default();
254/// assert_eq!(config.on_governance_refusal, GovernanceRefusal::Park);
255/// let config = config.with_governance_refusal(GovernanceRefusal::Fail);
256/// assert_eq!(config.on_governance_refusal, GovernanceRefusal::Fail);
257/// ```
258#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
259pub enum GovernanceRefusal {
260    /// Park the run `Waiting` on its `Session` checkpoint at its next model-call boundary,
261    /// reported as [`ParkReason::Frozen`], and wake it when the control allows work again.
262    /// See [Freeze parks](self#freeze-parks). The default.
263    #[default]
264    Park,
265    /// End the attempt with the control's error: `governance.frozen` fails the run,
266    /// `governance.stale` requeues it while attempts remain.
267    Fail,
268}
269
270/// How a [`DurableWorker`] claims and runs work.
271///
272/// # Example
273///
274/// ```rust
275/// use std::time::Duration;
276/// use adk_server::background::DurableWorkerConfig;
277///
278/// let config = DurableWorkerConfig::default()
279///     .with_queue("payments")
280///     .with_lease_ttl(Duration::from_secs(15))
281///     .with_max_concurrent_runs(8);
282/// assert_eq!(config.queue, "payments");
283/// ```
284#[derive(Debug, Clone)]
285#[non_exhaustive]
286pub struct DurableWorkerConfig {
287    /// The owner name written into every lease. Defaults to a random `worker-{uuid}`.
288    pub worker_id: String,
289    /// The queue claimed from. Defaults to `default`.
290    pub queue: String,
291    /// How long a claim or heartbeat holds the run. Defaults to 30 seconds.
292    pub lease_ttl: Duration,
293    /// How long the worker waits when nothing is claimable. Defaults to 500 ms.
294    pub poll_interval: Duration,
295    /// The most runs executed at once. Defaults to 4.
296    pub max_concurrent_runs: usize,
297    /// Fails an attempt that runs longer than this; `None` never times out.
298    pub run_timeout: Option<Duration>,
299    /// Finished runs older than this on the worker's clock
300    /// ([`DurableWorker::with_clock`]) are pruned by the worker loop; `None` keeps them.
301    /// Defaults to 24 hours.
302    pub retain_finished: Option<Duration>,
303    /// How long an agent run parked on a held tool call waits for a decision; `None`
304    /// waits until woken. A run resumed past this deadline with the call still held
305    /// fails with `approval expired`.
306    pub approval_timeout: Option<Duration>,
307    /// Agent ids a run's stored principal may name for the worker to act as it. Empty by
308    /// default: a stored principal other than the worker's own or the derived one is
309    /// refused. See [Identity](self#identity).
310    pub allowed_principals: BTreeSet<AgentId>,
311    /// What happens to a run the governance control refuses after it made a model or tool
312    /// call. Defaults to [`GovernanceRefusal::Park`]; see [Freeze parks](self#freeze-parks).
313    pub on_governance_refusal: GovernanceRefusal,
314    /// How long a retryable failure of a model call, or one whose error names a wait
315    /// (`Retry-After`), waits before the run's next attempt; other retryable failures, such
316    /// as a busy store or a workflow's, retry at once. Defaults to [`RetryBackoff::default`]:
317    /// about 5, 10 and 20 seconds, at least the error's own retry hint, at most 10 minutes.
318    pub retry_backoff: RetryBackoff,
319}
320
321impl Default for DurableWorkerConfig {
322    fn default() -> Self {
323        Self {
324            worker_id: format!("worker-{}", uuid::Uuid::new_v4()),
325            queue: "default".to_string(),
326            lease_ttl: Duration::from_secs(30),
327            poll_interval: Duration::from_millis(500),
328            max_concurrent_runs: 4,
329            run_timeout: None,
330            retain_finished: Some(Duration::from_secs(24 * 60 * 60)),
331            approval_timeout: None,
332            allowed_principals: BTreeSet::new(),
333            on_governance_refusal: GovernanceRefusal::Park,
334            retry_backoff: RetryBackoff::default(),
335        }
336    }
337}
338
339impl DurableWorkerConfig {
340    /// Sets how long a retryable failure of a model call, or one whose error names a wait,
341    /// waits before the run's next attempt; [`RetryBackoff::none`] retries at once.
342    ///
343    /// # Example
344    ///
345    /// ```rust
346    /// use std::time::Duration;
347    /// use adk_core::run_store::RetryBackoff;
348    /// use adk_server::background::DurableWorkerConfig;
349    ///
350    /// let config = DurableWorkerConfig::default()
351    ///     .with_retry_backoff(RetryBackoff::new(Duration::from_secs(1), Duration::from_secs(60)));
352    /// assert_eq!(config.retry_backoff.initial, Duration::from_secs(1));
353    /// ```
354    pub fn with_retry_backoff(mut self, backoff: RetryBackoff) -> Self {
355        self.retry_backoff = backoff;
356        self
357    }
358
359    /// Sets the owner name written into every lease.
360    pub fn with_worker_id(mut self, worker_id: impl Into<String>) -> Self {
361        self.worker_id = worker_id.into();
362        self
363    }
364
365    /// Sets the queue claimed from.
366    pub fn with_queue(mut self, queue: impl Into<String>) -> Self {
367        self.queue = queue.into();
368        self
369    }
370
371    /// Sets how long a claim or heartbeat holds the run.
372    pub fn with_lease_ttl(mut self, ttl: Duration) -> Self {
373        self.lease_ttl = ttl;
374        self
375    }
376
377    /// Sets how long the worker waits when nothing is claimable.
378    pub fn with_poll_interval(mut self, interval: Duration) -> Self {
379        self.poll_interval = interval;
380        self
381    }
382
383    /// Sets the most runs executed at once.
384    pub fn with_max_concurrent_runs(mut self, max: usize) -> Self {
385        self.max_concurrent_runs = max.max(1);
386        self
387    }
388
389    /// Fails an attempt that runs longer than `timeout`.
390    pub fn with_run_timeout(mut self, timeout: Duration) -> Self {
391        self.run_timeout = Some(timeout);
392        self
393    }
394
395    /// Sets how long a run parked on a held tool call waits for a decision.
396    pub fn with_approval_timeout(mut self, timeout: Option<Duration>) -> Self {
397        self.approval_timeout = timeout;
398        self
399    }
400
401    /// Lets a run's stored principal name `agent_id` for the worker to act as it.
402    pub fn with_allowed_principal(mut self, agent_id: AgentId) -> Self {
403        self.allowed_principals.insert(agent_id);
404        self
405    }
406
407    /// Sets how long finished runs are kept before the worker loop prunes them.
408    pub fn with_retain_finished(mut self, retain: Option<Duration>) -> Self {
409        self.retain_finished = retain;
410        self
411    }
412
413    /// Sets what happens to a run the governance control refuses after it made a model or
414    /// tool call (spec 3.2 §10 S3).
415    pub fn with_governance_refusal(mut self, action: GovernanceRefusal) -> Self {
416        self.on_governance_refusal = action;
417        self
418    }
419}
420
421/// Why a [`DurableWorker`] parked a run as `Waiting`, as [`WorkerHooks::on_park`] reports it
422/// (spec 3.2 §10 S1).
423///
424/// # Example
425///
426/// ```rust
427/// use adk_server::background::ParkReason;
428///
429/// let reason = ParkReason::Suspended;
430/// assert_ne!(reason, ParkReason::AwaitingApproval);
431/// ```
432#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
433#[non_exhaustive]
434pub enum ParkReason {
435    /// The run holds tool calls for approval, on a `RunCheckpointRef::AwaitingApproval`
436    /// checkpoint; a wake after the decision resumes it.
437    AwaitingApproval,
438    /// The run was asked to [`suspend`](DurableWorker::suspend) and stopped at a model-call
439    /// boundary, on a `RunCheckpointRef::Session` checkpoint; it waits until woken.
440    Suspended,
441    /// The governance control refused the run before it made a model or tool call; it is
442    /// claimable again at once.
443    HandedBack,
444    /// The governance control refused the run after it made a model or tool call and the
445    /// worker parked it at its next model-call boundary, on a `RunCheckpointRef::Session`
446    /// checkpoint, under [`GovernanceRefusal::Park`] (spec 3.2 §10 S3); the worker wakes
447    /// it when the control allows work again, and the resumed turn carries
448    /// [`FREEZE_RESUMED_NOTICE`].
449    Frozen,
450}
451
452/// The system notice a run parked by a freeze leaves in its session, after the answers to its
453/// last tool calls. See [Freeze parks](self#freeze-parks).
454pub const FREEZE_PAUSED_NOTICE: &str = "Execution paused by an operator freeze.";
455
456/// The system notice the claim that resumes a freeze-parked run adds to its session, so the
457/// model's next request says the freeze is over rather than ending at a `not run` answer. See
458/// [Freeze parks](self#freeze-parks).
459///
460/// # Example
461///
462/// ```rust
463/// use adk_core::history::system_notice;
464/// use adk_server::background::FREEZE_RESUMED_NOTICE;
465///
466/// let notice = system_notice(FREEZE_RESUMED_NOTICE);
467/// assert!(notice.parts[0].text().unwrap().starts_with("[System notice] Execution was paused"));
468/// ```
469pub const FREEZE_RESUMED_NOTICE: &str = "Execution was paused by an operator freeze and has now \
470    resumed. The tool calls refused during the freeze did not run. Continue the task, and call \
471    again any refused call you still need.";
472
473/// The action of the audit record a freeze-parked run writes when it resumes with
474/// [`FREEZE_RESUMED_NOTICE`].
475pub const FREEZE_RESUMED_ACTION: &str = "governance.run_resumed";
476
477/// Lifecycle hooks a [`DurableWorker`] calls as it moves a run between states (spec 3.2
478/// §10 S1).
479///
480/// Every method has an empty default, so an implementation overrides only the transitions
481/// it reports. A hook runs after the store write it reports and observes it: it cannot change
482/// what the worker does. The worker awaits each hook before it continues the attempt, so a
483/// hook hands slow work, such as delivery to a remote sink, off to another task. See
484/// [Lifecycle hooks](self#lifecycle-hooks) for when each is called.
485///
486/// # Example
487///
488/// ```rust
489/// use std::sync::Arc;
490/// use adk_core::{InMemoryRunStore, RunRecord};
491/// use adk_server::background::{DurableWorker, ParkReason, WorkerHooks};
492/// use async_trait::async_trait;
493///
494/// #[derive(Debug)]
495/// struct LogTransitions;
496///
497/// #[async_trait]
498/// impl WorkerHooks for LogTransitions {
499///     async fn on_park(&self, run: &RunRecord, reason: ParkReason) {
500///         tracing::info!(run.id = %run.run_id, park.reason = ?reason, "run parked");
501///     }
502/// }
503///
504/// let worker =
505///     DurableWorker::new(Arc::new(InMemoryRunStore::new())).with_hooks(Arc::new(LogTransitions));
506/// # let _ = worker;
507/// ```
508#[async_trait]
509pub trait WorkerHooks: Send + Sync {
510    /// Called once the worker starts the target of a run it claimed, before any model call
511    /// or workflow step. `run` is `Running` at the claim's epoch.
512    async fn on_claim(&self, _run: &RunRecord) {}
513
514    /// Called after the worker parked `run` as `Waiting`, with why. `run` holds no lease.
515    async fn on_park(&self, _run: &RunRecord, _reason: ParkReason) {}
516
517    /// Called after the worker wrote the attempt's outcome. `run` is `Completed`, `Failed`,
518    /// or `Cancelled`, or `Queued` when a retryable failure requeued it.
519    async fn on_finish(&self, _run: &RunRecord) {}
520
521    /// Called with each event of an agent turn, partial chunks included, in the order the
522    /// runner yields them. The events carry each model response's usage
523    /// (`llm_response.usage_metadata`, its `cost` included), so a host can count what the
524    /// turn spent whatever agent the runner hosts; a kernel attributes its spend this way.
525    async fn on_event(&self, _run: &RunRecord, _event: &Event) {}
526
527    /// Why `run` was woken, for the agent turn this claim starts; `None` by default. Called
528    /// after [`on_claim`](Self::on_claim), for agent runs only.
529    ///
530    /// The worker adds the text to the turn's user content: after the run's own input on a
531    /// turn that starts from it, and in place of the blank turn on one that continues a
532    /// parked run. It reaches the model as a user message, so the agent tree screens it as
533    /// one ([`Agent::screen_user_input`](adk_core::Agent::screen_user_input)), and it never
534    /// joins the agent's instructions.
535    ///
536    /// | Rule | Why |
537    /// |------|-----|
538    /// | The text's first line identifies the wake | A session that already holds a user message starting with that line is not given the text again, so a recovered attempt repeats nothing |
539    /// | A run parked on a held call (`RunCheckpointRef::AwaitingApproval`) is given none | Its turn stays blank so the held call resumes; the decision reaches it as that call's answer |
540    /// | The first hook that returns text wins | One wake starts one turn |
541    async fn wake_input(&self, _run: &RunRecord) -> Option<String> {
542        None
543    }
544}
545
546/// Claims runs from a [`DurableRunStore`] and executes them: agents through their
547/// [`Runner`], workflows through a [`WorkflowExecutor`].
548///
549/// Run one per replica with [`spawn`](Self::spawn); every replica claiming from the same
550/// store and queue shares the work, and a run whose worker stopped is recovered by
551/// another once its lease expires. See the [module documentation](self) for fencing and
552/// crash resume.
553///
554/// # Example
555///
556/// ```rust,ignore
557/// use std::sync::Arc;
558/// use adk_server::background::{DurableWorker, DurableWorkerConfig};
559///
560/// let worker = DurableWorker::new(run_store)
561///     .with_agent("support", Arc::new(runner))
562///     .with_workflows(Arc::new(registry))
563///     .with_governance(governance.clone())
564///     .with_config(DurableWorkerConfig::default().with_queue("default"));
565/// let handle = worker.spawn();
566/// // ...
567/// handle.shutdown().await;
568/// ```
569#[derive(Clone)]
570pub struct DurableWorker {
571    runs: Arc<dyn DurableRunStore>,
572    agents: BTreeMap<String, Arc<Runner>>,
573    /// The live targets shared with the host and other workers (spec 3.3 §10 S4), read
574    /// after `agents` on every claim.
575    table: Option<AgentTable>,
576    workflows: Option<Arc<dyn WorkflowExecutor>>,
577    governance: Option<GovernanceControl>,
578    audit: Option<AuditTrail>,
579    config: DurableWorkerConfig,
580    /// The time compared with the run store's timestamps, which the store stamps on its own
581    /// clock.
582    clock: Arc<dyn Clock>,
583    /// Makes every in-flight attempt heartbeat now, so a cancel requested in this
584    /// process is seen without waiting a heartbeat interval.
585    heartbeat_now: Arc<Notify>,
586    hooks: Vec<Arc<dyn WorkerHooks>>,
587    /// The agent attempts in flight, shared with clones and the handle, so a suspend
588    /// request reaches the attempt wherever it was asked.
589    suspensions: Arc<Suspensions>,
590    /// The runs this worker parked under a freeze, shared with clones and the handle, so
591    /// the unfreeze wakes them wherever it is observed.
592    frozen: Arc<FrozenRuns>,
593}
594
595impl std::fmt::Debug for DurableWorker {
596    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
597        f.debug_struct("DurableWorker")
598            .field("agents", &self.agents.keys().collect::<Vec<_>>())
599            .field("table", &self.table)
600            .field("workflows", &self.workflows.is_some())
601            .field("config", &self.config)
602            .field("hooks", &self.hooks.len())
603            .field("frozen", &self.frozen)
604            .finish_non_exhaustive()
605    }
606}
607
608/// Why an attempt ended without an outcome to write.
609enum Stop {
610    /// The lease is no longer held; another worker owns the run.
611    LeaseLost,
612}
613
614/// How an attempt that ran to its end left the run.
615enum Attempt {
616    /// The run finished with a result.
617    Done(Value),
618    /// The run holds tool calls for approval and waits, until this time when set.
619    Parked(Option<chrono::DateTime<chrono::Utc>>),
620    /// The governance control refused the run before it made a model or tool call.
621    Refused(AdkError),
622    /// The run was asked to suspend and stopped at a model-call boundary; its `Session`
623    /// checkpoint is recorded.
624    Suspended,
625    /// The governance control refused the run after it made a call and the worker stopped
626    /// it at a model-call boundary; its `Session` checkpoint is recorded.
627    Frozen,
628}
629
630/// A failed attempt.
631struct Failure {
632    error: String,
633    retryable: bool,
634    /// Whether the next attempt waits [`DurableWorkerConfig::retry_backoff`]: a model
635    /// provider's failure or one that names a wait.
636    backs_off: bool,
637    /// How long the error asked to wait before another attempt (`Retry-After`).
638    retry_after: Option<Duration>,
639}
640
641impl Failure {
642    /// A failure no later attempt can fix.
643    fn fatal(error: impl Into<String>) -> Self {
644        Self { error: error.into(), retryable: false, backs_off: false, retry_after: None }
645    }
646}
647
648impl From<AdkError> for Failure {
649    fn from(error: AdkError) -> Self {
650        let retryable = error.is_retryable();
651        let retry_after = retryable.then(|| error.retry.retry_after()).flatten();
652        // A provider under load needs time; a busy store or a stale kill-switch read clears
653        // in milliseconds and is retried at once, as is a workflow's opaque failure.
654        let backs_off =
655            retryable && (error.component == ErrorComponent::Model || retry_after.is_some());
656        Self { retryable, backs_off, retry_after, error: error.to_string() }
657    }
658}
659
660impl DurableWorker {
661    /// A worker over `runs` with no targets and the default configuration.
662    pub fn new(runs: Arc<dyn DurableRunStore>) -> Self {
663        Self {
664            runs,
665            agents: BTreeMap::new(),
666            table: None,
667            workflows: None,
668            governance: None,
669            audit: None,
670            config: DurableWorkerConfig::default(),
671            clock: Arc::new(SystemClock),
672            heartbeat_now: Arc::new(Notify::new()),
673            hooks: Vec::new(),
674            suspensions: Arc::default(),
675            frozen: Arc::default(),
676        }
677    }
678
679    /// Runs whose target is `target` execute through `runner`.
680    pub fn with_agent(mut self, target: impl Into<String>, runner: Arc<Runner>) -> Self {
681        self.agents.insert(target.into(), runner);
682        self
683    }
684
685    /// Reads agent targets from `table` on every claim, after those registered with
686    /// [`with_agent`](Self::with_agent) (spec 3.3 §10 S4): a target the host inserts while
687    /// the worker runs serves the next claim, one it removes is refused, and a claim of a
688    /// target the table [expects](AgentTable::expect) but has not built is handed back for
689    /// a later claim. See [Live targets](self#live-targets).
690    ///
691    /// # Example
692    ///
693    /// ```rust
694    /// use std::sync::Arc;
695    /// use adk_core::InMemoryRunStore;
696    /// use adk_server::background::{AgentTable, DurableWorker};
697    ///
698    /// let table = AgentTable::new();
699    /// let worker = DurableWorker::new(Arc::new(InMemoryRunStore::new())).with_agent_table(table.clone());
700    /// assert!(!worker.has_target("finance"));
701    /// table.expect("finance");
702    /// assert!(worker.has_target("finance"), "an expected target is served once built");
703    /// ```
704    pub fn with_agent_table(mut self, table: AgentTable) -> Self {
705        self.table = Some(table);
706        self
707    }
708
709    /// The runner of agent target `target`: one registered with `with_agent`, else the
710    /// table's.
711    fn runner_for(&self, target: &str) -> Option<Arc<Runner>> {
712        self.agents
713            .get(target)
714            .cloned()
715            .or_else(|| self.table.as_ref().and_then(|table| table.get(target)))
716    }
717
718    /// Runs whose target is not an agent execute through `workflows`.
719    pub fn with_workflows(mut self, workflows: Arc<dyn WorkflowExecutor>) -> Self {
720        self.workflows = Some(workflows);
721        self
722    }
723
724    /// Claims nothing while `control` refuses work (frozen, or a stale fail-closed mirror).
725    ///
726    /// A run that a claim in flight returns after `control` started refusing is handed
727    /// back unstarted; see [Kill switch](self#kill-switch).
728    pub fn with_governance(mut self, control: GovernanceControl) -> Self {
729        self.governance = Some(control);
730        self
731    }
732
733    /// Records refused run identities on `trail`; without one, an agent run's refusal is
734    /// recorded on its runner's audit trail.
735    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
736        self.audit = Some(trail);
737        self
738    }
739
740    /// Sets the configuration.
741    pub fn with_config(mut self, config: DurableWorkerConfig) -> Self {
742        self.config = config;
743        self
744    }
745
746    /// Sets the clock the worker reads, which defaults to `SystemClock`.
747    ///
748    /// Give it the run store's clock (`InMemoryRunStore::with_clock`,
749    /// `SqliteRunStore::with_clock`): the worker compares that clock's time with the
750    /// timestamps the store writes, to prune finished runs past
751    /// [`retain_finished`](DurableWorkerConfig::retain_finished), to time its idle waits on
752    /// `not_before`, and to set and expire the deadlines of the runs it parks. On another
753    /// clock, a store whose time trails the wall clock by more than `retain_finished` loses
754    /// runs that finished within the window.
755    ///
756    /// # Example
757    ///
758    /// ```rust
759    /// use std::sync::Arc;
760    /// use adk_core::{Clock, InMemoryRunStore, ManualClock};
761    /// use adk_server::background::DurableWorker;
762    ///
763    /// let clock: Arc<dyn Clock> = Arc::new(ManualClock::new(chrono::Utc::now()));
764    /// let runs = Arc::new(InMemoryRunStore::new().with_clock(Arc::clone(&clock)));
765    /// let worker = DurableWorker::new(runs).with_clock(clock);
766    /// ```
767    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
768        self.clock = clock;
769        self
770    }
771
772    /// Adds lifecycle hooks, called after those added before (spec 3.2 §10 S1).
773    ///
774    /// See [Lifecycle hooks](self#lifecycle-hooks) for when each hook is called.
775    pub fn with_hooks(mut self, hooks: Arc<dyn WorkerHooks>) -> Self {
776        self.hooks.push(hooks);
777        self
778    }
779
780    /// Asks the agent run `run_id`, in flight on this worker, to stop at its next model-call
781    /// boundary and park as `Waiting` on its `Session` checkpoint until woken (spec 3.2 §10
782    /// S1).
783    ///
784    /// Returns whether the request reached an attempt: `false` when this worker has no
785    /// attempt of `run_id` in flight, or the run is a workflow run, which is not
786    /// suspendable. A turn that ends without another model call finishes as it would
787    /// without the request, and a cancellation requested through the run store still
788    /// finishes the run `Cancelled`. Clones of the worker and its [`WorkerHandle`] share
789    /// the attempts in flight. See [Suspending a run](self#suspending-a-run).
790    ///
791    /// # Example
792    ///
793    /// ```rust
794    /// use std::sync::Arc;
795    /// use adk_core::InMemoryRunStore;
796    /// use adk_server::background::DurableWorker;
797    ///
798    /// let worker = DurableWorker::new(Arc::new(InMemoryRunStore::new()));
799    /// assert!(!worker.suspend("run-1"), "nothing is in flight");
800    /// ```
801    pub fn suspend(&self, run_id: &str) -> bool {
802        self.suspensions.request(run_id)
803    }
804
805    /// Wakes every run this worker parked under a freeze and returns how many it woke
806    /// (spec 3.2 §10 S3). The claim loop does the same when its control allows work
807    /// again; a run that can no longer be woken (pruned, cancelled) is forgotten, and one
808    /// the store could not reach stays listed for the next call. See
809    /// [Freeze parks](self#freeze-parks).
810    ///
811    /// # Example
812    ///
813    /// ```rust
814    /// use std::sync::Arc;
815    /// use adk_core::InMemoryRunStore;
816    /// use adk_server::background::DurableWorker;
817    ///
818    /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
819    /// let worker = DurableWorker::new(Arc::new(InMemoryRunStore::new()));
820    /// assert_eq!(worker.wake_frozen().await, 0, "nothing was parked under a freeze");
821    /// # });
822    /// ```
823    pub async fn wake_frozen(&self) -> usize {
824        self.frozen.wake(&self.runs).await
825    }
826
827    /// The ids of the runs this worker parked under a freeze and has not woken yet.
828    pub fn frozen_runs(&self) -> Vec<String> {
829        self.frozen.ids()
830    }
831
832    /// The configuration.
833    pub fn config(&self) -> &DurableWorkerConfig {
834        &self.config
835    }
836
837    /// The run store.
838    pub fn run_store(&self) -> &Arc<dyn DurableRunStore> {
839        &self.runs
840    }
841
842    /// Whether `target` names a registered agent, an agent the shared table hosts or
843    /// expects, or a workflow the executor knows.
844    pub fn has_target(&self, target: &str) -> bool {
845        self.agents.contains_key(target)
846            || self
847                .table
848                .as_ref()
849                .is_some_and(|table| table.contains(target) || table.is_expected(target))
850            || self.workflows.as_ref().is_some_and(|workflows| workflows.has_workflow(target))
851    }
852
853    /// The governance control's refusal, while it refuses work.
854    fn refusal(&self) -> Option<AdkError> {
855        self.governance.as_ref().and_then(|control| control.check().err())
856    }
857
858    /// Wakes the runs parked under a freeze, once the control allows work; called by the
859    /// claim loop and [`run_next`](Self::run_next) after checking the control.
860    async fn wake_frozen_if_any(&self) {
861        if self.frozen.is_empty() {
862            return;
863        }
864        let woken = self.wake_frozen().await;
865        if woken > 0 {
866            tracing::info!(
867                runs.woken = woken,
868                "governance allows work again; woke the runs parked under the freeze"
869            );
870        }
871    }
872
873    /// Claims one run and executes it to the end of the attempt.
874    ///
875    /// Returns the run as the attempt left it, or `None` when nothing was claimable, the
876    /// governance control refused work, or the lease was lost mid-attempt.
877    ///
878    /// # Errors
879    ///
880    /// Returns the run store's error from the claim.
881    pub async fn run_next(&self) -> adk_core::Result<Option<RunRecord>> {
882        if let Some(error) = self.refusal() {
883            tracing::debug!(error = %error, "governance refuses work; not claiming");
884            return Ok(None);
885        }
886        self.wake_frozen_if_any().await;
887        let Some(claimed) = self
888            .runs
889            .claim(&self.config.queue, &self.config.worker_id, self.config.lease_ttl)
890            .await?
891        else {
892            return Ok(None);
893        };
894        Ok(self.execute(claimed).await)
895    }
896
897    /// Spawns the claim loop and returns its handle.
898    ///
899    /// The loop claims while it has capacity, waits when nothing is claimable as
900    /// [Idle waits](self#idle-waits) describes, wakes the runs it parked under a freeze
901    /// once its control allows work again, and prunes finished runs past
902    /// `retain_finished`. Aborting the handle drops every in-flight attempt without
903    /// writing, as a crash would; their leases expire and another worker recovers them.
904    pub fn spawn(self) -> WorkerHandle {
905        let shutdown = CancellationToken::new();
906        let stop = shutdown.clone();
907        let wake = Arc::new(Notify::new());
908        let woken = Arc::clone(&wake);
909        let heartbeat_now = Arc::clone(&self.heartbeat_now);
910        let suspensions = Arc::clone(&self.suspensions);
911        let frozen = Arc::clone(&self.frozen);
912        let runs = Arc::clone(&self.runs);
913        let task = tokio::spawn(async move { self.claim_loop(stop, woken).await });
914        WorkerHandle { shutdown, task, wake, heartbeat_now, suspensions, frozen, runs }
915    }
916
917    /// How long the claim loop waits when nothing is claimable: `poll_interval`, or the
918    /// time to the earliest future `not_before` of a queued or parked run on its queue
919    /// when that comes first (spec 3.2 §7.9, §13 Q2).
920    async fn idle_wait(&self) -> Duration {
921        let poll = self.config.poll_interval;
922        let filter = RunFilter::default()
923            .queue(&self.config.queue)
924            .states([RunState::Queued, RunState::Waiting]);
925        let pending = match self.runs.list(filter).await {
926            Ok(pending) => pending,
927            Err(error) => {
928                tracing::debug!(error = %error, "could not read the queue's deadlines; polling");
929                return poll;
930            }
931        };
932        let now = self.clock.now();
933        let earliest = pending.iter().filter_map(|run| run.not_before).filter(|at| *at > now).min();
934        match earliest {
935            Some(at) => {
936                let until = (at - now).to_std().unwrap_or(Duration::ZERO);
937                until.clamp(IDLE_FLOOR.min(poll), poll)
938            }
939            None => poll,
940        }
941    }
942
943    async fn claim_loop(self, shutdown: CancellationToken, wake: Arc<Notify>) {
944        let worker = Arc::new(self);
945        let mut in_flight = tokio::task::JoinSet::new();
946        let mut last_prune: Option<Instant> = None;
947        tracing::info!(
948            worker.id = %worker.config.worker_id,
949            worker.queue = %worker.config.queue,
950            "durable worker started"
951        );
952        loop {
953            while in_flight.try_join_next().is_some() {}
954            if shutdown.is_cancelled() {
955                break;
956            }
957            if let Some(retain) = worker.config.retain_finished
958                && last_prune.is_none_or(|at| at.elapsed() >= Duration::from_secs(60))
959            {
960                last_prune = Some(Instant::now());
961                let cutoff = chrono::Duration::from_std(retain)
962                    .ok()
963                    .and_then(|retain| worker.clock.now().checked_sub_signed(retain));
964                if let Some(cutoff) = cutoff {
965                    match worker.runs.prune(cutoff).await {
966                        Ok(0) => {}
967                        Ok(pruned) => tracing::debug!(runs.pruned = pruned, "pruned finished runs"),
968                        Err(error) => {
969                            tracing::warn!(error = %error, "could not prune finished runs")
970                        }
971                    }
972                }
973            }
974            let refusal = worker.refusal();
975            match &refusal {
976                Some(error) => {
977                    tracing::debug!(error = %error, "governance refuses work; not claiming")
978                }
979                // Checked on every pass rather than on the refused-to-allowed edge, so a run
980                // parked after a freeze shorter than this loop's wait still resumes.
981                None => worker.wake_frozen_if_any().await,
982            }
983            let mut claimed = None;
984            let has_capacity = in_flight.len() < worker.config.max_concurrent_runs;
985            if refusal.is_none() && has_capacity {
986                match worker
987                    .runs
988                    .claim(&worker.config.queue, &worker.config.worker_id, worker.config.lease_ttl)
989                    .await
990                {
991                    Ok(run) => claimed = run,
992                    Err(error) => tracing::warn!(error = %error, "claim failed"),
993                }
994            }
995            match claimed {
996                Some(run) => {
997                    let worker = Arc::clone(&worker);
998                    in_flight.spawn(async move { worker.execute(run).await });
999                }
1000                None => {
1001                    // At capacity the next finished attempt ends the wait, so the queue's
1002                    // deadlines are not read.
1003                    let idle = if refusal.is_none() && has_capacity {
1004                        worker.idle_wait().await
1005                    } else {
1006                        worker.config.poll_interval
1007                    };
1008                    tokio::select! {
1009                        () = shutdown.cancelled() => break,
1010                        () = tokio::time::sleep(idle) => {}
1011                        () = wake.notified() => {}
1012                        Some(_) = in_flight.join_next(), if !in_flight.is_empty() => {}
1013                    }
1014                }
1015            }
1016        }
1017        // A graceful shutdown lets in-flight attempts finish and write their outcome.
1018        while in_flight.join_next().await.is_some() {}
1019        tracing::info!(worker.id = %worker.config.worker_id, "durable worker stopped");
1020    }
1021
1022    /// Executes one claimed attempt and writes its outcome, fenced by the claim's epoch.
1023    async fn execute(&self, claimed: ClaimedRun) -> Option<RunRecord> {
1024        let ClaimedRun { record, epoch } = claimed;
1025        let run_id = record.run_id.clone();
1026        let lease = Arc::new(LeaseState::new(self.config.lease_ttl));
1027        let cancel = CancellationToken::new();
1028        let span = tracing::info_span!(
1029            "durable_run",
1030            run.id = %run_id,
1031            run.target = %record.target,
1032            run.attempt = record.attempt,
1033            run.epoch = epoch
1034        );
1035        tracing::info!(parent: &span, "run claimed");
1036        // The control was read before the claim, which can return after a freeze landed;
1037        // the same check now keeps a run that nothing has started from failing at its start.
1038        if let Some(error) = self.refusal() {
1039            return self.hand_back(&record, epoch, &error, &span).await;
1040        }
1041        // Read once per claim, so a runner swapped in the table mid-attempt serves the next
1042        // claim and this one finishes on the runner it started on.
1043        let runner = self.runner_for(&record.target);
1044        if runner.is_none() && self.awaits_build(&record.target) {
1045            return self.hand_back_unbuilt(&record, epoch, &span).await;
1046        }
1047        // Registered before `on_claim`, so a suspend asked from that hook reaches the attempt.
1048        let _suspendable =
1049            runner.is_some().then(|| Suspensions::register(&self.suspensions, &run_id, &lease));
1050
1051        let work = async {
1052            for hooks in &self.hooks {
1053                hooks.on_claim(&record).await;
1054            }
1055            let attempt = self.run_target(runner.as_ref(), &record, epoch, &lease, &cancel);
1056            match self.config.run_timeout {
1057                Some(timeout) => match tokio::time::timeout(timeout, attempt).await {
1058                    Ok(result) => result,
1059                    Err(_) => Ok(Err(Failure::fatal(format!(
1060                        "run timed out after {}s",
1061                        timeout.as_secs()
1062                    )))),
1063                },
1064                None => attempt.await,
1065            }
1066        };
1067        let result = tokio::select! {
1068            result = work => result,
1069            () = self.heartbeat(&run_id, epoch, &lease, &cancel) => Err(Stop::LeaseLost),
1070            () = lease.lost.notified() => Err(Stop::LeaseLost),
1071        };
1072        // A cancellation requested since the last heartbeat wins over a suspension or a
1073        // freeze park, so `request_cancel` still finishes the run `Cancelled`; a server
1074        // freeze without a delegate asks for both at once.
1075        if matches!(result, Ok(Ok(Attempt::Suspended | Attempt::Frozen)))
1076            && !lease.cancel_requested.load(Ordering::SeqCst)
1077        {
1078            match self.runs.heartbeat(&run_id, epoch, self.config.lease_ttl).await {
1079                Ok(cancel_requested) => {
1080                    lease.cancel_requested.fetch_or(cancel_requested, Ordering::SeqCst);
1081                }
1082                // The park's own fenced write reports a lost lease.
1083                Err(error) => {
1084                    tracing::debug!(parent: &span, error = %error, "could not read a cancellation before parking")
1085                }
1086            }
1087        }
1088        let outcome = match result {
1089            Err(Stop::LeaseLost) => {
1090                tracing::warn!(parent: &span, "lease lost; the attempt was dropped without writing");
1091                return None;
1092            }
1093            Ok(_) if lease.cancel_requested.load(Ordering::SeqCst) => RunOutcome::Cancelled,
1094            Ok(Ok(Attempt::Refused(error))) => {
1095                return self.hand_back(&record, epoch, &error, &span).await;
1096            }
1097            Ok(Ok(Attempt::Parked(until))) => {
1098                return match self.runs.wait(&run_id, epoch, until).await {
1099                    Ok(()) => {
1100                        tracing::info!(parent: &span, wait.until = ?until, "run parked until its held tool calls are decided");
1101                        self.parked(&record, ParkReason::AwaitingApproval).await
1102                    }
1103                    Err(error) => {
1104                        tracing::warn!(parent: &span, error = %error, "could not park the run; another worker owns it");
1105                        None
1106                    }
1107                };
1108            }
1109            Ok(Ok(Attempt::Suspended)) => {
1110                return match self.runs.wait(&run_id, epoch, None).await {
1111                    Ok(()) => {
1112                        tracing::info!(parent: &span, "run suspended at a model-call boundary; parked until woken");
1113                        self.parked(&record, ParkReason::Suspended).await
1114                    }
1115                    Err(error) => {
1116                        tracing::warn!(parent: &span, error = %error, "could not park the suspended run; another worker owns it");
1117                        None
1118                    }
1119                };
1120            }
1121            Ok(Ok(Attempt::Frozen)) => {
1122                return match self.runs.wait(&run_id, epoch, None).await {
1123                    Ok(()) => {
1124                        tracing::info!(parent: &span, "governance refused the run at a model-call boundary; parked until unfrozen");
1125                        // Listed before the hooks run, so a hook that unfreezes wakes it.
1126                        self.frozen.insert(&run_id);
1127                        self.parked(&record, ParkReason::Frozen).await
1128                    }
1129                    Err(error) => {
1130                        tracing::warn!(parent: &span, error = %error, "could not park the frozen run; another worker owns it");
1131                        None
1132                    }
1133                };
1134            }
1135            Ok(Ok(Attempt::Done(value))) => RunOutcome::Completed(value),
1136            Ok(Err(failure)) if failure.retryable && record.attempt >= record.max_attempts => {
1137                // The last attempt: the run fails for good, and says so where `ps` shows it.
1138                RunOutcome::Failed {
1139                    error: format!(
1140                        "{}; attempts exhausted ({} of {})",
1141                        failure.error, record.attempt, record.max_attempts
1142                    ),
1143                    retryable: false,
1144                    backoff: None,
1145                }
1146            }
1147            Ok(Err(failure)) => {
1148                let backoff = (failure.retryable && failure.backs_off)
1149                    .then(|| self.config.retry_backoff.delay(record.attempt, failure.retry_after));
1150                if let Some(backoff) = backoff {
1151                    tracing::info!(
1152                        parent: &span,
1153                        run.attempt = record.attempt,
1154                        run.max_attempts = record.max_attempts,
1155                        retry.after_ms = backoff.as_millis() as u64,
1156                        "attempt failed; retrying after a backoff"
1157                    );
1158                }
1159                RunOutcome::Failed { error: failure.error, retryable: failure.retryable, backoff }
1160            }
1161        };
1162        match self.runs.finish(&run_id, epoch, outcome).await {
1163            Ok(finished) => {
1164                tracing::info!(parent: &span, run.state = ?finished.state, "attempt finished");
1165                for hooks in &self.hooks {
1166                    hooks.on_finish(&finished).await;
1167                }
1168                Some(finished)
1169            }
1170            Err(error) => {
1171                tracing::warn!(parent: &span, error = %error, "could not write the outcome; another worker owns the run");
1172                None
1173            }
1174        }
1175    }
1176
1177    /// Gives a claimed run that made no model or tool call back to its queue.
1178    ///
1179    /// The run is parked until the time it was claimed, so it is claimable at once — by
1180    /// this worker once its control allows work again — and the claim that resumes it
1181    /// counts no further attempt.
1182    async fn hand_back(
1183        &self,
1184        record: &RunRecord,
1185        epoch: u64,
1186        refusal: &AdkError,
1187        span: &tracing::Span,
1188    ) -> Option<RunRecord> {
1189        match self.runs.wait(&record.run_id, epoch, Some(record.updated_at)).await {
1190            Ok(()) => {
1191                tracing::info!(parent: span, error = %refusal.diagnostics(), "governance refuses work; the run was handed back unstarted");
1192                self.parked(record, ParkReason::HandedBack).await;
1193            }
1194            Err(error) => {
1195                tracing::warn!(parent: span, error = %error, "could not hand the run back; it is recovered once its lease expires");
1196            }
1197        }
1198        None
1199    }
1200
1201    /// Whether `target` is expected by the shared table but neither built there nor a
1202    /// workflow, so a claim of it waits for the host to build it (spec 3.3 §10 S4).
1203    fn awaits_build(&self, target: &str) -> bool {
1204        self.table.as_ref().is_some_and(|table| table.is_expected(target))
1205            && !self.workflows.as_ref().is_some_and(|workflows| workflows.has_workflow(target))
1206    }
1207
1208    /// Gives a claimed run of an expected target that is not built yet back to its queue,
1209    /// claimable one poll interval later, by this worker or a replica that built it.
1210    async fn hand_back_unbuilt(
1211        &self,
1212        record: &RunRecord,
1213        epoch: u64,
1214        span: &tracing::Span,
1215    ) -> Option<RunRecord> {
1216        let poll = chrono::Duration::from_std(self.config.poll_interval)
1217            .unwrap_or_else(|_| chrono::Duration::milliseconds(500));
1218        let until = self.clock.now() + poll;
1219        match self.runs.wait(&record.run_id, epoch, Some(until)).await {
1220            Ok(()) => {
1221                tracing::info!(parent: span, wait.until = %until, "target expected but not built yet; the run was handed back unstarted");
1222                self.parked(record, ParkReason::HandedBack).await;
1223            }
1224            Err(error) => {
1225                tracing::warn!(parent: span, error = %error, "could not hand the run back; it is recovered once its lease expires");
1226            }
1227        }
1228        None
1229    }
1230
1231    /// Reads back a run this worker just parked, reports it to the `on_park` hooks, and
1232    /// returns it as read.
1233    ///
1234    /// When the store cannot be read, the hooks receive the claimed record as parked, so a
1235    /// hook never misses a transition the store accepted.
1236    async fn parked(&self, claimed: &RunRecord, reason: ParkReason) -> Option<RunRecord> {
1237        let read = self.runs.get(&claimed.run_id).await;
1238        let parked = match &read {
1239            Ok(Some(parked)) => parked.clone(),
1240            Ok(None) | Err(_) => {
1241                tracing::warn!(run.id = %claimed.run_id, error = ?read.as_ref().err(), "could not read the parked run back; reporting it from its claim");
1242                RunRecord {
1243                    state: RunState::Waiting,
1244                    lease_owner: None,
1245                    lease_expires_at: None,
1246                    ..claimed.clone()
1247                }
1248            }
1249        };
1250        for hooks in &self.hooks {
1251            hooks.on_park(&parked, reason).await;
1252        }
1253        read.ok().flatten()
1254    }
1255
1256    /// Heartbeats until the lease is lost; returns only then.
1257    async fn heartbeat(
1258        &self,
1259        run_id: &str,
1260        epoch: u64,
1261        lease: &LeaseState,
1262        cancel: &CancellationToken,
1263    ) {
1264        let ttl = self.config.lease_ttl;
1265        loop {
1266            tokio::select! {
1267                () = tokio::time::sleep(ttl / 3) => {}
1268                () = self.heartbeat_now.notified() => {}
1269            }
1270            let sent = Instant::now();
1271            match self.runs.heartbeat(run_id, epoch, ttl).await {
1272                Ok(cancel_requested) => {
1273                    lease.renewed(sent);
1274                    if cancel_requested && !lease.cancel_requested.swap(true, Ordering::SeqCst) {
1275                        tracing::info!(run.id = run_id, "cancellation requested; stopping the run");
1276                        cancel.cancel();
1277                    }
1278                }
1279                Err(error)
1280                    if error.code == RUN_STALE_EPOCH_CODE || error.code == RUN_NOT_FOUND_CODE =>
1281                {
1282                    lease.lose();
1283                    cancel.cancel();
1284                    return;
1285                }
1286                Err(error) => {
1287                    tracing::warn!(run.id = run_id, error = %error, "heartbeat failed; retrying");
1288                    if !lease.is_valid() {
1289                        lease.lose();
1290                        cancel.cancel();
1291                        return;
1292                    }
1293                }
1294            }
1295        }
1296    }
1297
1298    async fn run_target(
1299        &self,
1300        runner: Option<&Arc<Runner>>,
1301        record: &RunRecord,
1302        epoch: u64,
1303        lease: &Arc<LeaseState>,
1304        cancel: &CancellationToken,
1305    ) -> Result<Result<Attempt, Failure>, Stop> {
1306        if let Some(runner) = runner {
1307            let root = runner.root_agent_name();
1308            let own = match runner.default_principal(root).await {
1309                Ok(principal) => principal,
1310                Err(error) => return Ok(Err(error.into())),
1311            };
1312            let mut acting = runner.run_config().acting.clone();
1313            let defaults = [
1314                own.id,
1315                AgentPrincipal::derived(runner.app_name(), root).id,
1316                AgentPrincipal::derived(&record.app_name, &record.target).id,
1317            ];
1318            if let Err(error) = self.admit_principal(record, &defaults, root, true, &mut acting) {
1319                return Ok(Err(self.refuse(record, error, runner.audit_trail()).await));
1320            }
1321            return self.run_agent(runner, record, acting, epoch, lease, cancel).await;
1322        }
1323        let Some(workflows) = self.workflows.as_ref().filter(|w| w.has_workflow(&record.target))
1324        else {
1325            return Ok(Err(Failure::fatal(format!(
1326                "no agent or workflow named '{}' is registered on worker '{}'",
1327                record.target, self.config.worker_id
1328            ))));
1329        };
1330        let defaults = [AgentPrincipal::derived(&record.app_name, &record.target).id];
1331        let mut acting = ActingConfig::default();
1332        if let Err(error) =
1333            self.admit_principal(record, &defaults, &record.target, false, &mut acting)
1334        {
1335            return Ok(Err(self.refuse(record, error, None).await));
1336        }
1337        let (thread_id, checkpoint_id) = match &record.checkpoint {
1338            Some(RunCheckpointRef::Graph { thread_id, checkpoint_id }) => {
1339                (thread_id.clone(), checkpoint_id.clone())
1340            }
1341            _ => (record.run_id.clone(), None),
1342        };
1343        let resumed = record.checkpoint.is_some();
1344        if !resumed {
1345            self.checkpoint(
1346                &record.run_id,
1347                epoch,
1348                RunCheckpointRef::Graph { thread_id: thread_id.clone(), checkpoint_id: None },
1349            )
1350            .await?;
1351        }
1352        let context = WorkflowRunContext {
1353            run_id: record.run_id.clone(),
1354            attempt: record.attempt,
1355            thread_id,
1356            checkpoint_id,
1357            resumed,
1358            cancel: cancel.clone(),
1359            sink: Some(super::CheckpointSink {
1360                runs: Arc::clone(&self.runs),
1361                run_id: record.run_id.clone(),
1362                epoch,
1363            }),
1364        };
1365        let input = workflow_input(&record.input);
1366        Ok(workflows
1367            .execute_durable(&record.target, input, context)
1368            .await
1369            .map(Attempt::Done)
1370            .map_err(|error| Failure {
1371                error,
1372                retryable: true,
1373                backs_off: false,
1374                retry_after: None,
1375            }))
1376    }
1377
1378    /// Applies the run's stored principal to `acting` under the rules in
1379    /// [Identity](self#identity).
1380    ///
1381    /// `defaults` are the agent ids the worker acts as anyway; `root` is the agent an
1382    /// allowed principal applies to. A subject other than the run's user is left on
1383    /// `acting` for the runner's delegation policy when `delegable`, and refused otherwise.
1384    fn admit_principal(
1385        &self,
1386        record: &RunRecord,
1387        defaults: &[AgentId],
1388        root: &str,
1389        delegable: bool,
1390        acting: &mut ActingConfig,
1391    ) -> Result<(), AdkError> {
1392        let Some(stored) = &record.principal else {
1393            return Ok(());
1394        };
1395        if !defaults.contains(&stored.agent.id) {
1396            if !self.config.allowed_principals.contains(&stored.agent.id) {
1397                return Err(AdkError::new(
1398                    ErrorComponent::Server,
1399                    ErrorCategory::Forbidden,
1400                    PRINCIPAL_NOT_ALLOWED_CODE,
1401                    format!(
1402                        "run '{}' asks to act as agent '{}', which worker '{}' may not act as; \
1403                         add the id with DurableWorkerConfig::with_allowed_principal, or \
1404                         enqueue the run without a principal",
1405                        record.run_id, stored.agent.id, self.config.worker_id
1406                    ),
1407                ));
1408            }
1409            acting.principals.insert(root.to_string(), stored.agent.clone());
1410        }
1411        match &stored.on_behalf_of {
1412            Some(subject) if subject.id == record.user_id => acting.subject_kind = subject.kind,
1413            Some(subject) if delegable => {
1414                // A delegated principal names the session's subject at the head of its
1415                // chain, as the runner records it; its kind is the run's subject kind.
1416                if let Some(head) =
1417                    stored.delegation_chain.first().filter(|head| head.id == record.user_id)
1418                {
1419                    acting.subject_kind = head.kind;
1420                }
1421                acting.on_behalf_of = Some(subject.clone());
1422            }
1423            Some(subject) => {
1424                let session = adk_core::SubjectRef::new(subject.kind, record.user_id.clone());
1425                return Err(adk_core::subject_mismatch_error(&session, subject));
1426            }
1427            None => {}
1428        }
1429        acting.delegation_chain.clone_from(&stored.delegation_chain);
1430        Ok(())
1431    }
1432
1433    /// Records a refused run identity and returns the run's non-retryable failure.
1434    async fn refuse(
1435        &self,
1436        record: &RunRecord,
1437        error: AdkError,
1438        runner_trail: Option<&AuditTrail>,
1439    ) -> Failure {
1440        tracing::warn!(run.id = %record.run_id, error = %error, "run identity refused");
1441        if let Some(trail) = self.audit.as_ref().or(runner_trail) {
1442            let actor = record
1443                .principal
1444                .as_ref()
1445                .map(|principal| AuditActor::new(principal, ""))
1446                .unwrap_or_default();
1447            let draft = AuditRecordDraft::new(AuditRecordKind::Access, error.code)
1448                .actor(actor)
1449                .decision(AuditDecision::Denied)
1450                .outcome(AuditRecordOutcome::NotRun)
1451                .ext("runId", Value::String(record.run_id.clone()))
1452                .ext("userId", Value::String(record.user_id.clone()))
1453                .ext("workerId", Value::String(self.config.worker_id.clone()));
1454            if let Err(audit_error) = trail.record(draft).await {
1455                tracing::warn!(run.id = %record.run_id, error = %audit_error, "could not record the refused run");
1456            }
1457        }
1458        Failure::fatal(error.to_string())
1459    }
1460
1461    async fn checkpoint(
1462        &self,
1463        run_id: &str,
1464        epoch: u64,
1465        checkpoint: RunCheckpointRef,
1466    ) -> Result<(), Stop> {
1467        match self.runs.set_checkpoint(run_id, epoch, checkpoint).await {
1468            Ok(()) => Ok(()),
1469            Err(error) => {
1470                tracing::warn!(run.id = run_id, error = %error, "could not record the checkpoint; stopping");
1471                Err(Stop::LeaseLost)
1472            }
1473        }
1474    }
1475
1476    async fn run_agent(
1477        &self,
1478        runner: &Arc<Runner>,
1479        record: &RunRecord,
1480        acting: ActingConfig,
1481        epoch: u64,
1482        lease: &Arc<LeaseState>,
1483        cancel: &CancellationToken,
1484    ) -> Result<Result<Attempt, Failure>, Stop> {
1485        let user_id = record.user_id.as_str();
1486        let session_id = match (&record.checkpoint, &record.session_id) {
1487            (
1488                Some(
1489                    RunCheckpointRef::Session { session_id, .. }
1490                    | RunCheckpointRef::AwaitingApproval { session_id, .. },
1491                ),
1492                _,
1493            ) => session_id.clone(),
1494            (_, Some(session_id)) => session_id.clone(),
1495            _ => format!("run-{}", record.run_id),
1496        };
1497        let mut config = runner.run_config().clone();
1498        config.acting = acting;
1499        // A budget or tool list in the input only narrows what the runner allows; one that
1500        // cannot be read refuses the run rather than running it without its limits.
1501        let limits = match adk_core::RunLimits::of_input(&record.input) {
1502            Ok(limits) => limits.unwrap_or_default(),
1503            Err(error) => return Ok(Err(Failure::fatal(error))),
1504        };
1505        apply_limits(runner, &limits, &mut config);
1506        let subagent = record.input.get(adk_core::subagent::SUBAGENT_INPUT_KEY).is_some();
1507        // A run an authenticated caller enqueued runs as that authenticated user (I6).
1508        if record.authenticated {
1509            config.request_context = Some(adk_core::RequestContext {
1510                user_id: record.user_id.clone(),
1511                scopes: Vec::new(),
1512                metadata: std::collections::HashMap::new(),
1513            });
1514        }
1515        // First, so no other hook acts on a model call a suspension or a freeze stops.
1516        let governance = (self.config.on_governance_refusal == GovernanceRefusal::Park)
1517            .then(|| self.governance.clone())
1518            .flatten();
1519        config
1520            .invocation_hooks
1521            .insert(0, Arc::new(SuspendGate { lease: Arc::clone(lease), governance }));
1522        config.invocation_hooks.push(Arc::new(LeaseFence(Arc::clone(lease))));
1523        // Approval requests for calls this run holds carry its id, so their decision
1524        // wakes exactly this run.
1525        config.durable_run_id = Some(record.run_id.clone());
1526        let resume_from = match &record.checkpoint {
1527            Some(
1528                RunCheckpointRef::Session { invocation_id, .. }
1529                | RunCheckpointRef::AwaitingApproval { invocation_id, .. },
1530            ) => invocation_id.clone(),
1531            _ => None,
1532        };
1533        let mut wake_input = None;
1534        if !matches!(record.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. })) {
1535            for hooks in &self.hooks {
1536                wake_input = hooks.wake_input(record).await;
1537                if wake_input.is_some() {
1538                    break;
1539                }
1540            }
1541        }
1542        let prepared = async {
1543            let session = ensure_session(runner, user_id, &session_id).await?;
1544            let events = session.events().all();
1545            // A recovered attempt finds the wake it already told the session and repeats nothing.
1546            if let Some(header) = wake_input.as_deref().and_then(|text| text.lines().next())
1547                && events.iter().any(|event| {
1548                    event.author == "user"
1549                        && event.llm_response.content.as_ref().is_some_and(|content| {
1550                            content
1551                                .parts
1552                                .iter()
1553                                .filter_map(Part::text)
1554                                .any(|text| text.lines().next() == Some(header))
1555                        })
1556                })
1557            {
1558                wake_input = None;
1559            }
1560            let Some(invocation_id) = resume_from else {
1561                return Ok::<_, AdkError>(Prepared::Start);
1562            };
1563            if let Some(answer) = completed_answer(&events, &invocation_id) {
1564                return Ok(Prepared::Done(answer));
1565            }
1566            let answered = runner
1567                .recover_unanswered_calls_with_config(user_id, &session_id, Some(config.clone()))
1568                .await?;
1569            let turn_persisted = events
1570                .iter()
1571                .any(|event| event.invocation_id == invocation_id && event.author == "user");
1572            // The invocation's latest notice is the freeze park's until a claim adds the resume
1573            // notice, so only a freeze-parked run gets one, and only once.
1574            let paused = format!("{SYSTEM_NOTICE_PREFIX}{FREEZE_PAUSED_NOTICE}");
1575            let unfrozen = turn_persisted
1576                && matches!(record.checkpoint, Some(RunCheckpointRef::Session { .. }))
1577                && events
1578                    .iter()
1579                    .rev()
1580                    .find(|event| {
1581                        event.invocation_id == invocation_id
1582                            && adk_core::history::is_system_notice_event(event)
1583                    })
1584                    .and_then(|event| event.llm_response.content.as_ref())
1585                    .and_then(|content| content.parts.first())
1586                    .and_then(Part::text)
1587                    == Some(paused.as_str());
1588            if unfrozen {
1589                // Recorded first, so a trail that refuses unrecorded actions leaves no notice.
1590                if let Some(trail) = self.audit.as_ref().or(runner.audit_trail()) {
1591                    let actor = record
1592                        .principal
1593                        .as_ref()
1594                        .map(|principal| AuditActor::new(principal, invocation_id.as_str()))
1595                        .unwrap_or_default();
1596                    let draft =
1597                        AuditRecordDraft::new(AuditRecordKind::Governance, FREEZE_RESUMED_ACTION)
1598                            .actor(actor)
1599                            .outcome(AuditRecordOutcome::Succeeded)
1600                            .ext("runId", Value::String(record.run_id.clone()))
1601                            .ext("userId", Value::String(record.user_id.clone()))
1602                            .ext("sessionId", Value::String(session_id.clone()))
1603                            .ext("invocationId", Value::String(invocation_id.clone()))
1604                            .ext("workerId", Value::String(self.config.worker_id.clone()))
1605                            .ext("notice", Value::String(FREEZE_RESUMED_NOTICE.to_string()));
1606                    trail.record(draft).await?;
1607                }
1608                append_notice(runner, user_id, &session_id, &invocation_id, FREEZE_RESUMED_NOTICE)
1609                    .await?;
1610            }
1611            tracing::info!(
1612                run.id = %record.run_id,
1613                session.id = %session_id,
1614                resumed.from = %invocation_id,
1615                calls.answered = answered,
1616                user_turn.persisted = turn_persisted,
1617                resumed.after_freeze = unfrozen,
1618                "resuming agent run"
1619            );
1620            Ok(if turn_persisted { Prepared::Continue } else { Prepared::Start })
1621        };
1622        let content = match prepared.await {
1623            Ok(Prepared::Done(text)) => {
1624                return Ok(Ok(Attempt::Done(agent_result(&text, &session_id, None))));
1625            }
1626            Ok(Prepared::Continue) => {
1627                Content::new("user").with_text(wake_input.take().unwrap_or_default())
1628            }
1629            Ok(Prepared::Start) => {
1630                // The agent takes a call a person asked for once, so a woken run that starts
1631                // from the same input never holds it again (spec 3.3 §7.4 rule 5).
1632                match requested_call(&record.input, record.authenticated) {
1633                    Ok(call) => config.requested_call = call,
1634                    Err(error) => return Ok(Err(Failure::fatal(error))),
1635                }
1636                let content = input_content(&record.input);
1637                match wake_input.take() {
1638                    Some(text) => content.with_text(text),
1639                    None => content,
1640                }
1641            }
1642            Err(error) => return Ok(Err(error.into())),
1643        };
1644
1645        // A sub-agent's slice covers all its runs, so each run, and each attempt that
1646        // recovers one, resumes from what its session shows it has spent.
1647        if let Some(budget) = limits.budget.as_ref().filter(|_| subagent) {
1648            let spent = match ensure_session(runner, user_id, &session_id).await {
1649                Ok(session) => adk_core::subagent::spent_in_session(&session.events().all()),
1650                Err(error) => return Ok(Err(error.into())),
1651            };
1652            let narrowed = config.budget.clone().unwrap_or_default().narrowed(budget);
1653            let parent = config.budget_tracker.take();
1654            config.budget_tracker =
1655                Some(Arc::new(adk_core::BudgetTracker::resume(narrowed.clone(), spent, parent)));
1656            config.budget = Some(narrowed);
1657        }
1658        let (user, session) =
1659            match (UserId::try_from(user_id), SessionId::try_from(session_id.as_str())) {
1660                (Ok(user), Ok(session)) => (user, session),
1661                (Err(error), _) | (_, Err(error)) => {
1662                    return Ok(Err(Failure::fatal(error.to_string())));
1663                }
1664            };
1665        let invocation = match runner.start_with_config(user, session, content, Some(config)).await
1666        {
1667            Ok(invocation) => invocation,
1668            Err(error) => return Ok(Err(error.into())),
1669        };
1670        let invocation_id = invocation.invocation_id().to_string();
1671        // Recorded before the stream is polled, so the user turn never reaches the session
1672        // without a checkpoint naming it.
1673        self.checkpoint(
1674            &record.run_id,
1675            epoch,
1676            RunCheckpointRef::Session {
1677                session_id: session_id.clone(),
1678                invocation_id: Some(invocation_id.clone()),
1679            },
1680        )
1681        .await?;
1682
1683        let mut events = invocation.into_events();
1684        let mut text = String::new();
1685        let mut interrupted = false;
1686        let mut produced = false;
1687        let mut stopped_by_refusal = false;
1688        loop {
1689            let next = tokio::select! {
1690                next = events.next() => next,
1691                () = cancel.cancelled(), if !interrupted => {
1692                    interrupted = true;
1693                    runner.interrupt_identity(runner.app_name(), user_id, &session_id);
1694                    continue;
1695                }
1696                () = lease.stopped.cancelled(), if !interrupted => {
1697                    interrupted = true;
1698                    tracing::info!(
1699                        run.id = %record.run_id,
1700                        frozen = lease.frozen.load(Ordering::SeqCst),
1701                        "stopping the run at its model-call boundary"
1702                    );
1703                    runner.interrupt_identity(runner.app_name(), user_id, &session_id);
1704                    continue;
1705                }
1706            };
1707            let Some(event) = next else { break };
1708            match event {
1709                Ok(event) => {
1710                    produced = true;
1711                    for hooks in &self.hooks {
1712                        hooks.on_event(record, &event).await;
1713                    }
1714                    if !event.llm_response.partial
1715                        && event.author != "user"
1716                        && event.is_final_response()
1717                        && let Some(content) = &event.llm_response.content
1718                    {
1719                        text = content
1720                            .parts
1721                            .iter()
1722                            .filter_map(Part::text)
1723                            .collect::<Vec<_>>()
1724                            .join("");
1725                    }
1726                }
1727                // Before any event, a kill-switch refusal comes from the runner's start
1728                // check or the agent's check before its first model call: no model or tool
1729                // call ran, and the checkpoint resumes the run from its input or its
1730                // persisted user turn.
1731                Err(error)
1732                    if !produced
1733                        && (error.code == GOVERNANCE_FROZEN_CODE
1734                            || error.code == GOVERNANCE_STALE_CODE)
1735                        && self.refusal().is_some() =>
1736                {
1737                    return Ok(Ok(Attempt::Refused(error)));
1738                }
1739                // A refusal after the run made a call is the model-call boundary the run
1740                // stops at: as a suspension when one was asked for, else as a freeze park
1741                // under `GovernanceRefusal::Park` (spec 3.2 §10 S3). Only a worker with a
1742                // control parks, since only its claim loop sees the unfreeze that wakes it.
1743                Err(error)
1744                    if (error.code == GOVERNANCE_FROZEN_CODE
1745                        || error.code == GOVERNANCE_STALE_CODE)
1746                        && (lease.suspend_requested.load(Ordering::SeqCst)
1747                            || (produced
1748                                && self.governance.is_some()
1749                                && self.config.on_governance_refusal
1750                                    == GovernanceRefusal::Park)) =>
1751                {
1752                    if lease.suspend_requested.load(Ordering::SeqCst) {
1753                        tracing::info!(run.id = %record.run_id, error = %error.diagnostics(), "governance refused the run it was asked to suspend; suspending it");
1754                    } else {
1755                        lease.frozen.store(true, Ordering::SeqCst);
1756                        tracing::info!(run.id = %record.run_id, error = %error.diagnostics(), "governance refused the run after it made a call; parking it until unfrozen");
1757                    }
1758                    stopped_by_refusal = true;
1759                    break;
1760                }
1761                Err(error) => return Ok(Err(error.into())),
1762            }
1763        }
1764        drop(events);
1765
1766        if stopped_by_refusal || lease.stopped.is_cancelled() {
1767            // The gate met the freeze before the run produced an event, as when the runner
1768            // has no control of its own: nothing ran, so the run is handed back.
1769            if !produced
1770                && lease.frozen.load(Ordering::SeqCst)
1771                && !lease.suspend_requested.load(Ordering::SeqCst)
1772                && let Some(error) = self.refusal()
1773            {
1774                return Ok(Ok(Attempt::Refused(error)));
1775            }
1776            // A run asked to suspend stays a suspension whatever stopped it, so an
1777            // unfreeze never wakes it.
1778            let suspended = lease.suspend_requested.load(Ordering::SeqCst);
1779            self.checkpoint(
1780                &record.run_id,
1781                epoch,
1782                RunCheckpointRef::Session {
1783                    session_id: session_id.clone(),
1784                    invocation_id: Some(invocation_id.clone()),
1785                },
1786            )
1787            .await?;
1788            if suspended {
1789                return Ok(Ok(Attempt::Suspended));
1790            }
1791            // The session, not this worker, remembers the park, so the claim that resumes the
1792            // run on any worker adds the resume notice.
1793            if let Err(error) =
1794                append_notice(runner, user_id, &session_id, &invocation_id, FREEZE_PAUSED_NOTICE)
1795                    .await
1796            {
1797                tracing::warn!(run.id = %record.run_id, error = %error, "could not record the freeze park in the session; the resumed run gets no resume notice");
1798            }
1799            return Ok(Ok(Attempt::Frozen));
1800        }
1801
1802        let held = match held_by_invocation(runner, user_id, &session_id, &invocation_id).await {
1803            Ok(held) => held,
1804            Err(error) => return Ok(Err(error.into())),
1805        };
1806        if held.is_empty() {
1807            return Ok(Ok(Attempt::Done(agent_result(&text, &session_id, Some(&invocation_id)))));
1808        }
1809        let now = self.clock.now();
1810        let previous = match &record.checkpoint {
1811            Some(RunCheckpointRef::AwaitingApproval { fingerprints, expires_at, .. })
1812                if fingerprints.iter().any(|fingerprint| held.contains(fingerprint)) =>
1813            {
1814                Some(*expires_at)
1815            }
1816            _ => None,
1817        };
1818        if let Some(Some(expired)) = previous
1819            && expired <= now
1820        {
1821            return Ok(Err(Failure::fatal(format!(
1822                "approval expired at {expired} for held tool calls {held:?}; no decision was recorded"
1823            ))));
1824        }
1825        let until = previous.unwrap_or_else(|| {
1826            self.config
1827                .approval_timeout
1828                .and_then(|timeout| chrono::Duration::from_std(timeout).ok())
1829                .and_then(|timeout| now.checked_add_signed(timeout))
1830        });
1831        tracing::info!(
1832            run.id = %record.run_id,
1833            session.id = %session_id,
1834            held.fingerprints = ?held,
1835            "agent run holds tool calls for approval"
1836        );
1837        self.checkpoint(
1838            &record.run_id,
1839            epoch,
1840            RunCheckpointRef::AwaitingApproval {
1841                session_id,
1842                invocation_id: Some(invocation_id),
1843                fingerprints: held,
1844                expires_at: until,
1845            },
1846        )
1847        .await?;
1848        Ok(Ok(Attempt::Parked(until)))
1849    }
1850}
1851
1852/// The fingerprints of the tool calls `invocation_id` holds for approval: calls it
1853/// surfaced as confirmation requests that no later response answers.
1854async fn held_by_invocation(
1855    runner: &Runner,
1856    user_id: &str,
1857    session_id: &str,
1858    invocation_id: &str,
1859) -> adk_core::Result<Vec<String>> {
1860    let identity = adk_core::AdkIdentity::new(
1861        adk_core::AppName::try_from(runner.app_name())?,
1862        UserId::try_from(user_id)?,
1863        SessionId::try_from(session_id)?,
1864    );
1865    let events = runner.session_service().get_for_identity(&identity).await?.events().all();
1866    let mut surfaced: Vec<(&str, &str, Option<&str>)> = events
1867        .iter()
1868        .filter(|event| event.invocation_id == invocation_id)
1869        .filter_map(|event| {
1870            event.actions.tool_confirmation.as_ref().map(|request| {
1871                (event.author.as_str(), event.branch.as_str(), request.function_call_id.as_deref())
1872            })
1873        })
1874        .collect();
1875    surfaced.dedup();
1876    let mut held = Vec::new();
1877    for (author, branch, _) in &surfaced {
1878        for call in adk_core::held_tool_calls(&events, author, branch) {
1879            let from_this_invocation = surfaced.iter().any(|(a, b, id)| {
1880                a == author && b == branch && *id == call.request.function_call_id.as_deref()
1881            });
1882            let fingerprint = call.request.fingerprint();
1883            if from_this_invocation && !held.contains(&fingerprint) {
1884                held.push(fingerprint);
1885            }
1886        }
1887    }
1888    Ok(held)
1889}
1890
1891enum Prepared {
1892    Start,
1893    Continue,
1894    Done(String),
1895}
1896
1897/// Handle to a spawned [`DurableWorker`] loop.
1898pub struct WorkerHandle {
1899    shutdown: CancellationToken,
1900    task: tokio::task::JoinHandle<()>,
1901    wake: Arc<Notify>,
1902    heartbeat_now: Arc<Notify>,
1903    suspensions: Arc<Suspensions>,
1904    frozen: Arc<FrozenRuns>,
1905    runs: Arc<dyn DurableRunStore>,
1906}
1907
1908impl std::fmt::Debug for WorkerHandle {
1909    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1910        f.debug_struct("WorkerHandle")
1911            .field("finished", &self.task.is_finished())
1912            .field("suspensions", &self.suspensions)
1913            .field("frozen", &self.frozen)
1914            .finish_non_exhaustive()
1915    }
1916}
1917
1918impl WorkerHandle {
1919    /// Makes the loop try a claim now instead of after its poll interval, for example
1920    /// right after this process enqueued a run.
1921    pub fn wake(&self) {
1922        self.wake.notify_one();
1923    }
1924
1925    /// Makes every in-flight attempt heartbeat now, so a cancellation requested through
1926    /// the run store is seen at once rather than at the next heartbeat interval.
1927    pub fn heartbeat_now(&self) {
1928        self.heartbeat_now.notify_waiters();
1929    }
1930
1931    /// Asks the agent run `run_id`, in flight on this worker, to stop at its next model-call
1932    /// boundary and park as `Waiting` on its `Session` checkpoint until woken (spec 3.2 §10
1933    /// S1). Returns whether the request reached an attempt; see
1934    /// [`DurableWorker::suspend`].
1935    pub fn suspend(&self, run_id: &str) -> bool {
1936        self.suspensions.request(run_id)
1937    }
1938
1939    /// Wakes every run the worker parked under a freeze and returns how many it woke
1940    /// (spec 3.2 §10 S3); see [`DurableWorker::wake_frozen`].
1941    pub async fn wake_frozen(&self) -> usize {
1942        self.frozen.wake(&self.runs).await
1943    }
1944
1945    /// The ids of the runs the worker parked under a freeze and has not woken yet.
1946    pub fn frozen_runs(&self) -> Vec<String> {
1947        self.frozen.ids()
1948    }
1949
1950    /// Stops claiming and waits for in-flight attempts to finish and write their outcome.
1951    pub async fn shutdown(self) {
1952        self.shutdown.cancel();
1953        let _ = self.task.await;
1954    }
1955
1956    /// Drops the loop and every in-flight attempt without writing, as a crash would.
1957    /// Their leases expire and another worker recovers the runs.
1958    pub fn abort(&self) {
1959        self.task.abort();
1960    }
1961
1962    /// Whether the loop has ended.
1963    pub fn is_finished(&self) -> bool {
1964        self.task.is_finished()
1965    }
1966}
1967
1968/// The agent attempts in flight on one worker, by run id.
1969#[derive(Default)]
1970struct Suspensions(std::sync::Mutex<HashMap<String, Arc<LeaseState>>>);
1971
1972impl std::fmt::Debug for Suspensions {
1973    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1974        let attempts = self.0.lock().unwrap_or_else(|e| e.into_inner());
1975        f.debug_struct("Suspensions").field("in_flight", &attempts.len()).finish()
1976    }
1977}
1978
1979impl Suspensions {
1980    /// Registers the agent attempt of `run_id` holding `lease` until the returned
1981    /// registration drops.
1982    fn register(
1983        suspensions: &Arc<Self>,
1984        run_id: &str,
1985        lease: &Arc<LeaseState>,
1986    ) -> SuspendRegistration {
1987        suspensions
1988            .0
1989            .lock()
1990            .unwrap_or_else(|e| e.into_inner())
1991            .insert(run_id.to_string(), Arc::clone(lease));
1992        SuspendRegistration {
1993            suspensions: Arc::clone(suspensions),
1994            run_id: run_id.to_string(),
1995            lease: Arc::clone(lease),
1996        }
1997    }
1998
1999    fn request(&self, run_id: &str) -> bool {
2000        let attempts = self.0.lock().unwrap_or_else(|e| e.into_inner());
2001        let Some(lease) = attempts.get(run_id) else {
2002            tracing::debug!(
2003                run.id = run_id,
2004                "no agent attempt of the run is in flight here; not suspending"
2005            );
2006            return false;
2007        };
2008        if !lease.suspend_requested.swap(true, Ordering::SeqCst) {
2009            tracing::info!(
2010                run.id = run_id,
2011                "suspend requested; the run parks at its next model-call boundary"
2012            );
2013        }
2014        true
2015    }
2016}
2017
2018/// One attempt's place in [`Suspensions`], removed when the attempt ends however it ends.
2019struct SuspendRegistration {
2020    suspensions: Arc<Suspensions>,
2021    run_id: String,
2022    lease: Arc<LeaseState>,
2023}
2024
2025impl Drop for SuspendRegistration {
2026    fn drop(&mut self) {
2027        let mut attempts = self.suspensions.0.lock().unwrap_or_else(|e| e.into_inner());
2028        if attempts.get(&self.run_id).is_some_and(|lease| Arc::ptr_eq(lease, &self.lease)) {
2029            attempts.remove(&self.run_id);
2030        }
2031    }
2032}
2033
2034/// The runs a worker parked under a freeze and has not woken yet, by id.
2035#[derive(Default)]
2036struct FrozenRuns(std::sync::Mutex<BTreeSet<String>>);
2037
2038impl std::fmt::Debug for FrozenRuns {
2039    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2040        let ids = self.0.lock().unwrap_or_else(|e| e.into_inner());
2041        f.debug_struct("FrozenRuns").field("parked", &ids.len()).finish()
2042    }
2043}
2044
2045impl FrozenRuns {
2046    fn insert(&self, run_id: &str) {
2047        self.0.lock().unwrap_or_else(|e| e.into_inner()).insert(run_id.to_string());
2048    }
2049
2050    fn ids(&self) -> Vec<String> {
2051        self.0.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect()
2052    }
2053
2054    fn is_empty(&self) -> bool {
2055        self.0.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
2056    }
2057
2058    /// Wakes every listed run in `runs`; a run the store no longer knows is forgotten, and
2059    /// one the store could not reach stays listed.
2060    async fn wake(&self, runs: &Arc<dyn DurableRunStore>) -> usize {
2061        let parked = std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner()));
2062        let mut woken = 0;
2063        for run_id in parked {
2064            match runs.wake(&run_id).await {
2065                Ok(()) => woken += 1,
2066                Err(error) if error.code == RUN_NOT_FOUND_CODE => {
2067                    tracing::debug!(run.id = %run_id, "frozen run no longer exists; not woken");
2068                }
2069                Err(error) => {
2070                    tracing::warn!(run.id = %run_id, error = %error, "could not wake the frozen run; it stays listed");
2071                    self.insert(&run_id);
2072                }
2073            }
2074        }
2075        woken
2076    }
2077}
2078
2079/// Stops an agent run at its next model-call boundary once it was asked to suspend, or
2080/// once the worker's governance control refuses work under [`GovernanceRefusal::Park`]:
2081/// the model call never starts, and the worker interrupts the turn.
2082struct SuspendGate {
2083    lease: Arc<LeaseState>,
2084    governance: Option<GovernanceControl>,
2085}
2086
2087impl std::fmt::Debug for SuspendGate {
2088    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2089        f.debug_struct("SuspendGate").finish_non_exhaustive()
2090    }
2091}
2092
2093#[async_trait]
2094impl InvocationHooks for SuspendGate {
2095    async fn before_model(
2096        &self,
2097        _ctx: Arc<dyn CallbackContext>,
2098        request: LlmRequest,
2099    ) -> adk_core::Result<BeforeModelResult> {
2100        if self.lease.suspend_requested.load(Ordering::SeqCst) {
2101            self.lease.stopped.cancel();
2102            // The worker interrupts the run, which drops this call before it returns.
2103            std::future::pending::<()>().await;
2104        }
2105        if let Some(control) = &self.governance
2106            && let Err(error) = control.check()
2107        {
2108            tracing::info!(error = %error.diagnostics(), "governance refuses work at a model-call boundary; stopping the run there");
2109            self.lease.frozen.store(true, Ordering::SeqCst);
2110            self.lease.stopped.cancel();
2111            std::future::pending::<()>().await;
2112        }
2113        Ok(BeforeModelResult::Continue(request))
2114    }
2115}
2116
2117/// What a worker knows about the lease it holds on one run, and the requests that stop
2118/// the attempt.
2119struct LeaseState {
2120    ttl: Duration,
2121    /// The lease is provably held until this instant: the last successful heartbeat (or
2122    /// the claim) was sent before it by `ttl`.
2123    valid_until: std::sync::Mutex<Instant>,
2124    lost_flag: AtomicBool,
2125    lost: Notify,
2126    cancel_requested: AtomicBool,
2127    /// Set by a suspend request; the attempt stops at its next model-call boundary.
2128    suspend_requested: AtomicBool,
2129    /// Set when the governance control refused the run after it made a call, so the stop
2130    /// is a freeze park rather than a suspension.
2131    frozen: AtomicBool,
2132    /// Cancelled by [`SuspendGate`] once the attempt stopped at a model-call boundary.
2133    stopped: CancellationToken,
2134}
2135
2136impl LeaseState {
2137    fn new(ttl: Duration) -> Self {
2138        Self {
2139            ttl,
2140            valid_until: std::sync::Mutex::new(Instant::now() + ttl),
2141            lost_flag: AtomicBool::new(false),
2142            lost: Notify::new(),
2143            cancel_requested: AtomicBool::new(false),
2144            suspend_requested: AtomicBool::new(false),
2145            frozen: AtomicBool::new(false),
2146            stopped: CancellationToken::new(),
2147        }
2148    }
2149
2150    fn renewed(&self, sent: Instant) {
2151        *self.valid_until.lock().unwrap_or_else(|e| e.into_inner()) = sent + self.ttl;
2152    }
2153
2154    fn is_valid(&self) -> bool {
2155        !self.lost_flag.load(Ordering::SeqCst)
2156            && Instant::now() < *self.valid_until.lock().unwrap_or_else(|e| e.into_inner())
2157    }
2158
2159    fn lose(&self) {
2160        if !self.lost_flag.swap(true, Ordering::SeqCst) {
2161            self.lost.notify_waiters();
2162        }
2163        self.lost.notify_one();
2164    }
2165
2166    /// Never returns once the lease is not provably held, so the attempt is dropped by
2167    /// the worker before it makes another call or writes another event.
2168    async fn fence(&self) {
2169        if !self.is_valid() {
2170            tracing::warn!("lease no longer provably held; fencing the attempt");
2171            self.lose();
2172            std::future::pending::<()>().await;
2173        }
2174    }
2175}
2176
2177/// Fences an agent run: every model call, model response, tool call, and tool result
2178/// waits on [`LeaseState::fence`].
2179struct LeaseFence(Arc<LeaseState>);
2180
2181impl std::fmt::Debug for LeaseFence {
2182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2183        f.debug_struct("LeaseFence").finish_non_exhaustive()
2184    }
2185}
2186
2187#[async_trait]
2188impl InvocationHooks for LeaseFence {
2189    async fn before_model(
2190        &self,
2191        _ctx: Arc<dyn CallbackContext>,
2192        request: LlmRequest,
2193    ) -> adk_core::Result<BeforeModelResult> {
2194        self.0.fence().await;
2195        Ok(BeforeModelResult::Continue(request))
2196    }
2197
2198    async fn after_model(
2199        &self,
2200        _ctx: Arc<dyn CallbackContext>,
2201        _response: LlmResponse,
2202    ) -> adk_core::Result<Option<LlmResponse>> {
2203        self.0.fence().await;
2204        Ok(None)
2205    }
2206
2207    async fn before_tool(
2208        &self,
2209        _ctx: Arc<dyn CallbackContext>,
2210    ) -> adk_core::Result<Option<Content>> {
2211        self.0.fence().await;
2212        Ok(None)
2213    }
2214
2215    async fn after_tool(
2216        &self,
2217        _ctx: Arc<dyn CallbackContext>,
2218    ) -> adk_core::Result<Option<Content>> {
2219        self.0.fence().await;
2220        Ok(None)
2221    }
2222}
2223
2224async fn ensure_session(
2225    runner: &Runner,
2226    user_id: &str,
2227    session_id: &str,
2228) -> adk_core::Result<Box<dyn adk_session::Session>> {
2229    let identity = adk_core::AdkIdentity::new(
2230        adk_core::AppName::try_from(runner.app_name())?,
2231        UserId::try_from(user_id)?,
2232        SessionId::try_from(session_id)?,
2233    );
2234    // Only a missing session is created: any other read failure is returned, so a transient
2235    // backend error never replaces the stored session. A create that loses a race to another
2236    // worker reads the session that worker created.
2237    match runner.session_service().get_for_identity(&identity).await {
2238        Err(error) if error.is_not_found() => {
2239            let created = runner
2240                .session_service()
2241                .create(adk_session::CreateRequest {
2242                    app_name: runner.app_name().to_string(),
2243                    user_id: user_id.to_string(),
2244                    session_id: Some(session_id.to_string()),
2245                    state: std::collections::HashMap::new(),
2246                })
2247                .await;
2248            match created {
2249                Err(error) if error.is_conflict() => {
2250                    runner.session_service().get_for_identity(&identity).await
2251                }
2252                other => other,
2253            }
2254        }
2255        other => other,
2256    }
2257}
2258
2259/// Appends the system notice `text` for `invocation_id` to the run's session.
2260async fn append_notice(
2261    runner: &Runner,
2262    user_id: &str,
2263    session_id: &str,
2264    invocation_id: &str,
2265    text: &str,
2266) -> adk_core::Result<()> {
2267    let identity = adk_core::AdkIdentity::new(
2268        adk_core::AppName::try_from(runner.app_name())?,
2269        UserId::try_from(user_id)?,
2270        SessionId::try_from(session_id)?,
2271    );
2272    runner
2273        .session_service()
2274        .append_event_for_identity(adk_session::AppendEventRequest {
2275            identity,
2276            event: adk_core::history::system_notice_event(invocation_id, text),
2277        })
2278        .await
2279}
2280
2281/// The final answer of `invocation_id`, when it is the last thing in the session.
2282fn completed_answer(events: &[adk_core::Event], invocation_id: &str) -> Option<String> {
2283    // An invocation that held tool calls ended on a notice, not an answer.
2284    if events.iter().any(|event| {
2285        event.invocation_id == invocation_id && event.actions.tool_confirmation.is_some()
2286    }) {
2287        return None;
2288    }
2289    // A system notice is the runtime's, never the run's answer.
2290    let last = events.iter().rev().find(|event| {
2291        !event.llm_response.partial && !adk_core::history::is_system_notice_event(event)
2292    })?;
2293    if last.invocation_id != invocation_id || last.author == "user" || !last.is_final_response() {
2294        return None;
2295    }
2296    let text: String = last
2297        .llm_response
2298        .content
2299        .as_ref()?
2300        .parts
2301        .iter()
2302        .filter_map(Part::text)
2303        .collect::<Vec<_>>()
2304        .join("");
2305    (!text.is_empty()).then_some(text)
2306}
2307
2308fn agent_result(text: &str, session_id: &str, invocation_id: Option<&str>) -> Value {
2309    let mut result = serde_json::json!({ "text": text, "sessionId": session_id });
2310    if let Some(invocation_id) = invocation_id {
2311        result["invocationId"] = Value::String(invocation_id.to_string());
2312    }
2313    result
2314}
2315
2316/// Narrows `config` by `limits`: the budget to the stricter of the two, and a ceiling layered
2317/// under the run's or the runner's tool policy, so the runner's decisions still apply.
2318fn apply_limits(runner: &Runner, limits: &adk_core::RunLimits, config: &mut adk_core::RunConfig) {
2319    if let Some(budget) = &limits.budget {
2320        config.budget = Some(match config.budget.take() {
2321            Some(own) => own.narrowed(budget),
2322            None => budget.clone(),
2323        });
2324    }
2325    if let Some(tools) = &limits.allowed_tools {
2326        let mut layers: Vec<Arc<dyn adk_core::ToolPolicy>> = config
2327            .tool_policy
2328            .clone()
2329            .or_else(|| runner.tool_policy().cloned())
2330            .into_iter()
2331            .collect();
2332        layers.push(Arc::new(adk_core::ToolCeiling::new(tools.iter().cloned())));
2333        config.tool_policy = Some(Arc::new(adk_core::StrictestPolicy::new(layers)));
2334    }
2335}
2336
2337/// The user turn an agent run starts from: a string, `{"text": ...}`, or
2338/// `{"content": Content}`; any other value is sent as its JSON text, except a
2339/// `{"requestedCall": ...}` without text, which starts from an empty turn.
2340pub(crate) fn input_content(input: &Value) -> Content {
2341    match input {
2342        Value::String(text) => Content::new("user").with_text(text),
2343        Value::Object(map) => {
2344            if let Some(content) = map
2345                .get("content")
2346                .and_then(|value| serde_json::from_value::<Content>(value.clone()).ok())
2347            {
2348                return content;
2349            }
2350            match map.get("text").and_then(Value::as_str) {
2351                Some(text) => Content::new("user").with_text(text),
2352                None if map.contains_key(REQUESTED_CALL_INPUT_KEY) => {
2353                    Content::new("user").with_text("")
2354                }
2355                None => Content::new("user").with_text(input.to_string()),
2356            }
2357        }
2358        other => Content::new("user").with_text(other.to_string()),
2359    }
2360}
2361
2362/// The run input key of a call a person asked for through something an agent drew.
2363const REQUESTED_CALL_INPUT_KEY: &str = "requestedCall";
2364
2365/// The call a person asked for that an agent run's `input` carries beside its text
2366/// (`{"text": ..., "requestedCall": RequestedCall}`), honoured only on a run an
2367/// authenticated caller enqueued (spec 3.3 §7.4 rule 5, wave 4 decision 13).
2368fn requested_call(input: &Value, authenticated: bool) -> Result<Option<RequestedCall>, String> {
2369    let Some(raw) = input.get(REQUESTED_CALL_INPUT_KEY) else {
2370        return Ok(None);
2371    };
2372    if !authenticated {
2373        tracing::warn!("ignored a requested call on a run no authenticated caller enqueued");
2374        return Ok(None);
2375    }
2376    serde_json::from_value(raw.clone()).map(Some).map_err(|error| {
2377        format!(
2378            "the run's {REQUESTED_CALL_INPUT_KEY} is not a requested call: {error}. Enqueue it \
2379             as an adk_core::RequestedCall"
2380        )
2381    })
2382}
2383
2384/// The workflow state a run's input becomes: an object's fields, or `{"input": value}`.
2385fn workflow_input(input: &Value) -> WorkflowState {
2386    match input {
2387        Value::Object(map) => map.clone().into_iter().collect(),
2388        Value::Null => WorkflowState::new(),
2389        other => [("input".to_string(), other.clone())].into_iter().collect(),
2390    }
2391}