use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use adk_core::audit_log::{
AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome, AuditTrail,
};
use adk_core::history::SYSTEM_NOTICE_PREFIX;
use adk_core::{
ActingConfig, AdkError, AgentId, AgentPrincipal, BeforeModelResult, CallbackContext,
ClaimedRun, Clock, Content, DurableRunStore, ErrorCategory, ErrorComponent, Event,
GOVERNANCE_FROZEN_CODE, GOVERNANCE_STALE_CODE, GovernanceControl, InvocationHooks, LlmRequest,
LlmResponse, PRINCIPAL_NOT_ALLOWED_CODE, Part, RequestedCall, RunCheckpointRef, RunFilter,
RunOutcome, RunRecord, RunState, SessionId, SystemClock, UserId,
run_store::{RUN_NOT_FOUND_CODE, RUN_STALE_EPOCH_CODE, RetryBackoff},
};
use adk_runner::Runner;
use async_trait::async_trait;
use futures::StreamExt;
use serde_json::Value;
use tokio::sync::Notify;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use super::table::AgentTable;
use super::{WorkflowExecutor, WorkflowRunContext, WorkflowState};
const IDLE_FLOOR: Duration = Duration::from_millis(25);
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum GovernanceRefusal {
#[default]
Park,
Fail,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DurableWorkerConfig {
pub worker_id: String,
pub queue: String,
pub lease_ttl: Duration,
pub poll_interval: Duration,
pub max_concurrent_runs: usize,
pub run_timeout: Option<Duration>,
pub retain_finished: Option<Duration>,
pub approval_timeout: Option<Duration>,
pub allowed_principals: BTreeSet<AgentId>,
pub on_governance_refusal: GovernanceRefusal,
pub retry_backoff: RetryBackoff,
}
impl Default for DurableWorkerConfig {
fn default() -> Self {
Self {
worker_id: format!("worker-{}", uuid::Uuid::new_v4()),
queue: "default".to_string(),
lease_ttl: Duration::from_secs(30),
poll_interval: Duration::from_millis(500),
max_concurrent_runs: 4,
run_timeout: None,
retain_finished: Some(Duration::from_secs(24 * 60 * 60)),
approval_timeout: None,
allowed_principals: BTreeSet::new(),
on_governance_refusal: GovernanceRefusal::Park,
retry_backoff: RetryBackoff::default(),
}
}
}
impl DurableWorkerConfig {
pub fn with_retry_backoff(mut self, backoff: RetryBackoff) -> Self {
self.retry_backoff = backoff;
self
}
pub fn with_worker_id(mut self, worker_id: impl Into<String>) -> Self {
self.worker_id = worker_id.into();
self
}
pub fn with_queue(mut self, queue: impl Into<String>) -> Self {
self.queue = queue.into();
self
}
pub fn with_lease_ttl(mut self, ttl: Duration) -> Self {
self.lease_ttl = ttl;
self
}
pub fn with_poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
pub fn with_max_concurrent_runs(mut self, max: usize) -> Self {
self.max_concurrent_runs = max.max(1);
self
}
pub fn with_run_timeout(mut self, timeout: Duration) -> Self {
self.run_timeout = Some(timeout);
self
}
pub fn with_approval_timeout(mut self, timeout: Option<Duration>) -> Self {
self.approval_timeout = timeout;
self
}
pub fn with_allowed_principal(mut self, agent_id: AgentId) -> Self {
self.allowed_principals.insert(agent_id);
self
}
pub fn with_retain_finished(mut self, retain: Option<Duration>) -> Self {
self.retain_finished = retain;
self
}
pub fn with_governance_refusal(mut self, action: GovernanceRefusal) -> Self {
self.on_governance_refusal = action;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ParkReason {
AwaitingApproval,
Suspended,
HandedBack,
Frozen,
}
pub const FREEZE_PAUSED_NOTICE: &str = "Execution paused by an operator freeze.";
pub const FREEZE_RESUMED_NOTICE: &str = "Execution was paused by an operator freeze and has now \
resumed. The tool calls refused during the freeze did not run. Continue the task, and call \
again any refused call you still need.";
pub const FREEZE_RESUMED_ACTION: &str = "governance.run_resumed";
#[async_trait]
pub trait WorkerHooks: Send + Sync {
async fn on_claim(&self, _run: &RunRecord) {}
async fn on_park(&self, _run: &RunRecord, _reason: ParkReason) {}
async fn on_finish(&self, _run: &RunRecord) {}
async fn on_event(&self, _run: &RunRecord, _event: &Event) {}
async fn wake_input(&self, _run: &RunRecord) -> Option<String> {
None
}
}
#[derive(Clone)]
pub struct DurableWorker {
runs: Arc<dyn DurableRunStore>,
agents: BTreeMap<String, Arc<Runner>>,
table: Option<AgentTable>,
workflows: Option<Arc<dyn WorkflowExecutor>>,
governance: Option<GovernanceControl>,
audit: Option<AuditTrail>,
config: DurableWorkerConfig,
clock: Arc<dyn Clock>,
heartbeat_now: Arc<Notify>,
hooks: Vec<Arc<dyn WorkerHooks>>,
suspensions: Arc<Suspensions>,
frozen: Arc<FrozenRuns>,
}
impl std::fmt::Debug for DurableWorker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DurableWorker")
.field("agents", &self.agents.keys().collect::<Vec<_>>())
.field("table", &self.table)
.field("workflows", &self.workflows.is_some())
.field("config", &self.config)
.field("hooks", &self.hooks.len())
.field("frozen", &self.frozen)
.finish_non_exhaustive()
}
}
enum Stop {
LeaseLost,
}
enum Attempt {
Done(Value),
Parked(Option<chrono::DateTime<chrono::Utc>>),
Refused(AdkError),
Suspended,
Frozen,
}
struct Failure {
error: String,
retryable: bool,
backs_off: bool,
retry_after: Option<Duration>,
}
impl Failure {
fn fatal(error: impl Into<String>) -> Self {
Self { error: error.into(), retryable: false, backs_off: false, retry_after: None }
}
}
impl From<AdkError> for Failure {
fn from(error: AdkError) -> Self {
let retryable = error.is_retryable();
let retry_after = retryable.then(|| error.retry.retry_after()).flatten();
let backs_off =
retryable && (error.component == ErrorComponent::Model || retry_after.is_some());
Self { retryable, backs_off, retry_after, error: error.to_string() }
}
}
impl DurableWorker {
pub fn new(runs: Arc<dyn DurableRunStore>) -> Self {
Self {
runs,
agents: BTreeMap::new(),
table: None,
workflows: None,
governance: None,
audit: None,
config: DurableWorkerConfig::default(),
clock: Arc::new(SystemClock),
heartbeat_now: Arc::new(Notify::new()),
hooks: Vec::new(),
suspensions: Arc::default(),
frozen: Arc::default(),
}
}
pub fn with_agent(mut self, target: impl Into<String>, runner: Arc<Runner>) -> Self {
self.agents.insert(target.into(), runner);
self
}
pub fn with_agent_table(mut self, table: AgentTable) -> Self {
self.table = Some(table);
self
}
fn runner_for(&self, target: &str) -> Option<Arc<Runner>> {
self.agents
.get(target)
.cloned()
.or_else(|| self.table.as_ref().and_then(|table| table.get(target)))
}
pub fn with_workflows(mut self, workflows: Arc<dyn WorkflowExecutor>) -> Self {
self.workflows = Some(workflows);
self
}
pub fn with_governance(mut self, control: GovernanceControl) -> Self {
self.governance = Some(control);
self
}
pub fn with_audit(mut self, trail: AuditTrail) -> Self {
self.audit = Some(trail);
self
}
pub fn with_config(mut self, config: DurableWorkerConfig) -> Self {
self.config = config;
self
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
pub fn with_hooks(mut self, hooks: Arc<dyn WorkerHooks>) -> Self {
self.hooks.push(hooks);
self
}
pub fn suspend(&self, run_id: &str) -> bool {
self.suspensions.request(run_id)
}
pub async fn wake_frozen(&self) -> usize {
self.frozen.wake(&self.runs).await
}
pub fn frozen_runs(&self) -> Vec<String> {
self.frozen.ids()
}
pub fn config(&self) -> &DurableWorkerConfig {
&self.config
}
pub fn run_store(&self) -> &Arc<dyn DurableRunStore> {
&self.runs
}
pub fn has_target(&self, target: &str) -> bool {
self.agents.contains_key(target)
|| self
.table
.as_ref()
.is_some_and(|table| table.contains(target) || table.is_expected(target))
|| self.workflows.as_ref().is_some_and(|workflows| workflows.has_workflow(target))
}
fn refusal(&self) -> Option<AdkError> {
self.governance.as_ref().and_then(|control| control.check().err())
}
async fn wake_frozen_if_any(&self) {
if self.frozen.is_empty() {
return;
}
let woken = self.wake_frozen().await;
if woken > 0 {
tracing::info!(
runs.woken = woken,
"governance allows work again; woke the runs parked under the freeze"
);
}
}
pub async fn run_next(&self) -> adk_core::Result<Option<RunRecord>> {
if let Some(error) = self.refusal() {
tracing::debug!(error = %error, "governance refuses work; not claiming");
return Ok(None);
}
self.wake_frozen_if_any().await;
let Some(claimed) = self
.runs
.claim(&self.config.queue, &self.config.worker_id, self.config.lease_ttl)
.await?
else {
return Ok(None);
};
Ok(self.execute(claimed).await)
}
pub fn spawn(self) -> WorkerHandle {
let shutdown = CancellationToken::new();
let stop = shutdown.clone();
let wake = Arc::new(Notify::new());
let woken = Arc::clone(&wake);
let heartbeat_now = Arc::clone(&self.heartbeat_now);
let suspensions = Arc::clone(&self.suspensions);
let frozen = Arc::clone(&self.frozen);
let runs = Arc::clone(&self.runs);
let task = tokio::spawn(async move { self.claim_loop(stop, woken).await });
WorkerHandle { shutdown, task, wake, heartbeat_now, suspensions, frozen, runs }
}
async fn idle_wait(&self) -> Duration {
let poll = self.config.poll_interval;
let filter = RunFilter::default()
.queue(&self.config.queue)
.states([RunState::Queued, RunState::Waiting]);
let pending = match self.runs.list(filter).await {
Ok(pending) => pending,
Err(error) => {
tracing::debug!(error = %error, "could not read the queue's deadlines; polling");
return poll;
}
};
let now = self.clock.now();
let earliest = pending.iter().filter_map(|run| run.not_before).filter(|at| *at > now).min();
match earliest {
Some(at) => {
let until = (at - now).to_std().unwrap_or(Duration::ZERO);
until.clamp(IDLE_FLOOR.min(poll), poll)
}
None => poll,
}
}
async fn claim_loop(self, shutdown: CancellationToken, wake: Arc<Notify>) {
let worker = Arc::new(self);
let mut in_flight = tokio::task::JoinSet::new();
let mut last_prune: Option<Instant> = None;
tracing::info!(
worker.id = %worker.config.worker_id,
worker.queue = %worker.config.queue,
"durable worker started"
);
loop {
while in_flight.try_join_next().is_some() {}
if shutdown.is_cancelled() {
break;
}
if let Some(retain) = worker.config.retain_finished
&& last_prune.is_none_or(|at| at.elapsed() >= Duration::from_secs(60))
{
last_prune = Some(Instant::now());
let cutoff = chrono::Duration::from_std(retain)
.ok()
.and_then(|retain| worker.clock.now().checked_sub_signed(retain));
if let Some(cutoff) = cutoff {
match worker.runs.prune(cutoff).await {
Ok(0) => {}
Ok(pruned) => tracing::debug!(runs.pruned = pruned, "pruned finished runs"),
Err(error) => {
tracing::warn!(error = %error, "could not prune finished runs")
}
}
}
}
let refusal = worker.refusal();
match &refusal {
Some(error) => {
tracing::debug!(error = %error, "governance refuses work; not claiming")
}
None => worker.wake_frozen_if_any().await,
}
let mut claimed = None;
let has_capacity = in_flight.len() < worker.config.max_concurrent_runs;
if refusal.is_none() && has_capacity {
match worker
.runs
.claim(&worker.config.queue, &worker.config.worker_id, worker.config.lease_ttl)
.await
{
Ok(run) => claimed = run,
Err(error) => tracing::warn!(error = %error, "claim failed"),
}
}
match claimed {
Some(run) => {
let worker = Arc::clone(&worker);
in_flight.spawn(async move { worker.execute(run).await });
}
None => {
let idle = if refusal.is_none() && has_capacity {
worker.idle_wait().await
} else {
worker.config.poll_interval
};
tokio::select! {
() = shutdown.cancelled() => break,
() = tokio::time::sleep(idle) => {}
() = wake.notified() => {}
Some(_) = in_flight.join_next(), if !in_flight.is_empty() => {}
}
}
}
}
while in_flight.join_next().await.is_some() {}
tracing::info!(worker.id = %worker.config.worker_id, "durable worker stopped");
}
async fn execute(&self, claimed: ClaimedRun) -> Option<RunRecord> {
let ClaimedRun { record, epoch } = claimed;
let run_id = record.run_id.clone();
let lease = Arc::new(LeaseState::new(self.config.lease_ttl));
let cancel = CancellationToken::new();
let span = tracing::info_span!(
"durable_run",
run.id = %run_id,
run.target = %record.target,
run.attempt = record.attempt,
run.epoch = epoch
);
tracing::info!(parent: &span, "run claimed");
if let Some(error) = self.refusal() {
return self.hand_back(&record, epoch, &error, &span).await;
}
let runner = self.runner_for(&record.target);
if runner.is_none() && self.awaits_build(&record.target) {
return self.hand_back_unbuilt(&record, epoch, &span).await;
}
let _suspendable =
runner.is_some().then(|| Suspensions::register(&self.suspensions, &run_id, &lease));
let work = async {
for hooks in &self.hooks {
hooks.on_claim(&record).await;
}
let attempt = self.run_target(runner.as_ref(), &record, epoch, &lease, &cancel);
match self.config.run_timeout {
Some(timeout) => match tokio::time::timeout(timeout, attempt).await {
Ok(result) => result,
Err(_) => Ok(Err(Failure::fatal(format!(
"run timed out after {}s",
timeout.as_secs()
)))),
},
None => attempt.await,
}
};
let result = tokio::select! {
result = work => result,
() = self.heartbeat(&run_id, epoch, &lease, &cancel) => Err(Stop::LeaseLost),
() = lease.lost.notified() => Err(Stop::LeaseLost),
};
if matches!(result, Ok(Ok(Attempt::Suspended | Attempt::Frozen)))
&& !lease.cancel_requested.load(Ordering::SeqCst)
{
match self.runs.heartbeat(&run_id, epoch, self.config.lease_ttl).await {
Ok(cancel_requested) => {
lease.cancel_requested.fetch_or(cancel_requested, Ordering::SeqCst);
}
Err(error) => {
tracing::debug!(parent: &span, error = %error, "could not read a cancellation before parking")
}
}
}
let outcome = match result {
Err(Stop::LeaseLost) => {
tracing::warn!(parent: &span, "lease lost; the attempt was dropped without writing");
return None;
}
Ok(_) if lease.cancel_requested.load(Ordering::SeqCst) => RunOutcome::Cancelled,
Ok(Ok(Attempt::Refused(error))) => {
return self.hand_back(&record, epoch, &error, &span).await;
}
Ok(Ok(Attempt::Parked(until))) => {
return match self.runs.wait(&run_id, epoch, until).await {
Ok(()) => {
tracing::info!(parent: &span, wait.until = ?until, "run parked until its held tool calls are decided");
self.parked(&record, ParkReason::AwaitingApproval).await
}
Err(error) => {
tracing::warn!(parent: &span, error = %error, "could not park the run; another worker owns it");
None
}
};
}
Ok(Ok(Attempt::Suspended)) => {
return match self.runs.wait(&run_id, epoch, None).await {
Ok(()) => {
tracing::info!(parent: &span, "run suspended at a model-call boundary; parked until woken");
self.parked(&record, ParkReason::Suspended).await
}
Err(error) => {
tracing::warn!(parent: &span, error = %error, "could not park the suspended run; another worker owns it");
None
}
};
}
Ok(Ok(Attempt::Frozen)) => {
return match self.runs.wait(&run_id, epoch, None).await {
Ok(()) => {
tracing::info!(parent: &span, "governance refused the run at a model-call boundary; parked until unfrozen");
self.frozen.insert(&run_id);
self.parked(&record, ParkReason::Frozen).await
}
Err(error) => {
tracing::warn!(parent: &span, error = %error, "could not park the frozen run; another worker owns it");
None
}
};
}
Ok(Ok(Attempt::Done(value))) => RunOutcome::Completed(value),
Ok(Err(failure)) if failure.retryable && record.attempt >= record.max_attempts => {
RunOutcome::Failed {
error: format!(
"{}; attempts exhausted ({} of {})",
failure.error, record.attempt, record.max_attempts
),
retryable: false,
backoff: None,
}
}
Ok(Err(failure)) => {
let backoff = (failure.retryable && failure.backs_off)
.then(|| self.config.retry_backoff.delay(record.attempt, failure.retry_after));
if let Some(backoff) = backoff {
tracing::info!(
parent: &span,
run.attempt = record.attempt,
run.max_attempts = record.max_attempts,
retry.after_ms = backoff.as_millis() as u64,
"attempt failed; retrying after a backoff"
);
}
RunOutcome::Failed { error: failure.error, retryable: failure.retryable, backoff }
}
};
match self.runs.finish(&run_id, epoch, outcome).await {
Ok(finished) => {
tracing::info!(parent: &span, run.state = ?finished.state, "attempt finished");
for hooks in &self.hooks {
hooks.on_finish(&finished).await;
}
Some(finished)
}
Err(error) => {
tracing::warn!(parent: &span, error = %error, "could not write the outcome; another worker owns the run");
None
}
}
}
async fn hand_back(
&self,
record: &RunRecord,
epoch: u64,
refusal: &AdkError,
span: &tracing::Span,
) -> Option<RunRecord> {
match self.runs.wait(&record.run_id, epoch, Some(record.updated_at)).await {
Ok(()) => {
tracing::info!(parent: span, error = %refusal.diagnostics(), "governance refuses work; the run was handed back unstarted");
self.parked(record, ParkReason::HandedBack).await;
}
Err(error) => {
tracing::warn!(parent: span, error = %error, "could not hand the run back; it is recovered once its lease expires");
}
}
None
}
fn awaits_build(&self, target: &str) -> bool {
self.table.as_ref().is_some_and(|table| table.is_expected(target))
&& !self.workflows.as_ref().is_some_and(|workflows| workflows.has_workflow(target))
}
async fn hand_back_unbuilt(
&self,
record: &RunRecord,
epoch: u64,
span: &tracing::Span,
) -> Option<RunRecord> {
let poll = chrono::Duration::from_std(self.config.poll_interval)
.unwrap_or_else(|_| chrono::Duration::milliseconds(500));
let until = self.clock.now() + poll;
match self.runs.wait(&record.run_id, epoch, Some(until)).await {
Ok(()) => {
tracing::info!(parent: span, wait.until = %until, "target expected but not built yet; the run was handed back unstarted");
self.parked(record, ParkReason::HandedBack).await;
}
Err(error) => {
tracing::warn!(parent: span, error = %error, "could not hand the run back; it is recovered once its lease expires");
}
}
None
}
async fn parked(&self, claimed: &RunRecord, reason: ParkReason) -> Option<RunRecord> {
let read = self.runs.get(&claimed.run_id).await;
let parked = match &read {
Ok(Some(parked)) => parked.clone(),
Ok(None) | Err(_) => {
tracing::warn!(run.id = %claimed.run_id, error = ?read.as_ref().err(), "could not read the parked run back; reporting it from its claim");
RunRecord {
state: RunState::Waiting,
lease_owner: None,
lease_expires_at: None,
..claimed.clone()
}
}
};
for hooks in &self.hooks {
hooks.on_park(&parked, reason).await;
}
read.ok().flatten()
}
async fn heartbeat(
&self,
run_id: &str,
epoch: u64,
lease: &LeaseState,
cancel: &CancellationToken,
) {
let ttl = self.config.lease_ttl;
loop {
tokio::select! {
() = tokio::time::sleep(ttl / 3) => {}
() = self.heartbeat_now.notified() => {}
}
let sent = Instant::now();
match self.runs.heartbeat(run_id, epoch, ttl).await {
Ok(cancel_requested) => {
lease.renewed(sent);
if cancel_requested && !lease.cancel_requested.swap(true, Ordering::SeqCst) {
tracing::info!(run.id = run_id, "cancellation requested; stopping the run");
cancel.cancel();
}
}
Err(error)
if error.code == RUN_STALE_EPOCH_CODE || error.code == RUN_NOT_FOUND_CODE =>
{
lease.lose();
cancel.cancel();
return;
}
Err(error) => {
tracing::warn!(run.id = run_id, error = %error, "heartbeat failed; retrying");
if !lease.is_valid() {
lease.lose();
cancel.cancel();
return;
}
}
}
}
}
async fn run_target(
&self,
runner: Option<&Arc<Runner>>,
record: &RunRecord,
epoch: u64,
lease: &Arc<LeaseState>,
cancel: &CancellationToken,
) -> Result<Result<Attempt, Failure>, Stop> {
if let Some(runner) = runner {
let root = runner.root_agent_name();
let own = match runner.default_principal(root).await {
Ok(principal) => principal,
Err(error) => return Ok(Err(error.into())),
};
let mut acting = runner.run_config().acting.clone();
let defaults = [
own.id,
AgentPrincipal::derived(runner.app_name(), root).id,
AgentPrincipal::derived(&record.app_name, &record.target).id,
];
if let Err(error) = self.admit_principal(record, &defaults, root, true, &mut acting) {
return Ok(Err(self.refuse(record, error, runner.audit_trail()).await));
}
return self.run_agent(runner, record, acting, epoch, lease, cancel).await;
}
let Some(workflows) = self.workflows.as_ref().filter(|w| w.has_workflow(&record.target))
else {
return Ok(Err(Failure::fatal(format!(
"no agent or workflow named '{}' is registered on worker '{}'",
record.target, self.config.worker_id
))));
};
let defaults = [AgentPrincipal::derived(&record.app_name, &record.target).id];
let mut acting = ActingConfig::default();
if let Err(error) =
self.admit_principal(record, &defaults, &record.target, false, &mut acting)
{
return Ok(Err(self.refuse(record, error, None).await));
}
let (thread_id, checkpoint_id) = match &record.checkpoint {
Some(RunCheckpointRef::Graph { thread_id, checkpoint_id }) => {
(thread_id.clone(), checkpoint_id.clone())
}
_ => (record.run_id.clone(), None),
};
let resumed = record.checkpoint.is_some();
if !resumed {
self.checkpoint(
&record.run_id,
epoch,
RunCheckpointRef::Graph { thread_id: thread_id.clone(), checkpoint_id: None },
)
.await?;
}
let context = WorkflowRunContext {
run_id: record.run_id.clone(),
attempt: record.attempt,
thread_id,
checkpoint_id,
resumed,
cancel: cancel.clone(),
sink: Some(super::CheckpointSink {
runs: Arc::clone(&self.runs),
run_id: record.run_id.clone(),
epoch,
}),
};
let input = workflow_input(&record.input);
Ok(workflows
.execute_durable(&record.target, input, context)
.await
.map(Attempt::Done)
.map_err(|error| Failure {
error,
retryable: true,
backs_off: false,
retry_after: None,
}))
}
fn admit_principal(
&self,
record: &RunRecord,
defaults: &[AgentId],
root: &str,
delegable: bool,
acting: &mut ActingConfig,
) -> Result<(), AdkError> {
let Some(stored) = &record.principal else {
return Ok(());
};
if !defaults.contains(&stored.agent.id) {
if !self.config.allowed_principals.contains(&stored.agent.id) {
return Err(AdkError::new(
ErrorComponent::Server,
ErrorCategory::Forbidden,
PRINCIPAL_NOT_ALLOWED_CODE,
format!(
"run '{}' asks to act as agent '{}', which worker '{}' may not act as; \
add the id with DurableWorkerConfig::with_allowed_principal, or \
enqueue the run without a principal",
record.run_id, stored.agent.id, self.config.worker_id
),
));
}
acting.principals.insert(root.to_string(), stored.agent.clone());
}
match &stored.on_behalf_of {
Some(subject) if subject.id == record.user_id => acting.subject_kind = subject.kind,
Some(subject) if delegable => {
if let Some(head) =
stored.delegation_chain.first().filter(|head| head.id == record.user_id)
{
acting.subject_kind = head.kind;
}
acting.on_behalf_of = Some(subject.clone());
}
Some(subject) => {
let session = adk_core::SubjectRef::new(subject.kind, record.user_id.clone());
return Err(adk_core::subject_mismatch_error(&session, subject));
}
None => {}
}
acting.delegation_chain.clone_from(&stored.delegation_chain);
Ok(())
}
async fn refuse(
&self,
record: &RunRecord,
error: AdkError,
runner_trail: Option<&AuditTrail>,
) -> Failure {
tracing::warn!(run.id = %record.run_id, error = %error, "run identity refused");
if let Some(trail) = self.audit.as_ref().or(runner_trail) {
let actor = record
.principal
.as_ref()
.map(|principal| AuditActor::new(principal, ""))
.unwrap_or_default();
let draft = AuditRecordDraft::new(AuditRecordKind::Access, error.code)
.actor(actor)
.decision(AuditDecision::Denied)
.outcome(AuditRecordOutcome::NotRun)
.ext("runId", Value::String(record.run_id.clone()))
.ext("userId", Value::String(record.user_id.clone()))
.ext("workerId", Value::String(self.config.worker_id.clone()));
if let Err(audit_error) = trail.record(draft).await {
tracing::warn!(run.id = %record.run_id, error = %audit_error, "could not record the refused run");
}
}
Failure::fatal(error.to_string())
}
async fn checkpoint(
&self,
run_id: &str,
epoch: u64,
checkpoint: RunCheckpointRef,
) -> Result<(), Stop> {
match self.runs.set_checkpoint(run_id, epoch, checkpoint).await {
Ok(()) => Ok(()),
Err(error) => {
tracing::warn!(run.id = run_id, error = %error, "could not record the checkpoint; stopping");
Err(Stop::LeaseLost)
}
}
}
async fn run_agent(
&self,
runner: &Arc<Runner>,
record: &RunRecord,
acting: ActingConfig,
epoch: u64,
lease: &Arc<LeaseState>,
cancel: &CancellationToken,
) -> Result<Result<Attempt, Failure>, Stop> {
let user_id = record.user_id.as_str();
let session_id = match (&record.checkpoint, &record.session_id) {
(
Some(
RunCheckpointRef::Session { session_id, .. }
| RunCheckpointRef::AwaitingApproval { session_id, .. },
),
_,
) => session_id.clone(),
(_, Some(session_id)) => session_id.clone(),
_ => format!("run-{}", record.run_id),
};
let mut config = runner.run_config().clone();
config.acting = acting;
let limits = match adk_core::RunLimits::of_input(&record.input) {
Ok(limits) => limits.unwrap_or_default(),
Err(error) => return Ok(Err(Failure::fatal(error))),
};
apply_limits(runner, &limits, &mut config);
let subagent = record.input.get(adk_core::subagent::SUBAGENT_INPUT_KEY).is_some();
if record.authenticated {
config.request_context = Some(adk_core::RequestContext {
user_id: record.user_id.clone(),
scopes: Vec::new(),
metadata: std::collections::HashMap::new(),
});
}
let governance = (self.config.on_governance_refusal == GovernanceRefusal::Park)
.then(|| self.governance.clone())
.flatten();
config
.invocation_hooks
.insert(0, Arc::new(SuspendGate { lease: Arc::clone(lease), governance }));
config.invocation_hooks.push(Arc::new(LeaseFence(Arc::clone(lease))));
config.durable_run_id = Some(record.run_id.clone());
let resume_from = match &record.checkpoint {
Some(
RunCheckpointRef::Session { invocation_id, .. }
| RunCheckpointRef::AwaitingApproval { invocation_id, .. },
) => invocation_id.clone(),
_ => None,
};
let mut wake_input = None;
if !matches!(record.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. })) {
for hooks in &self.hooks {
wake_input = hooks.wake_input(record).await;
if wake_input.is_some() {
break;
}
}
}
let prepared = async {
let session = ensure_session(runner, user_id, &session_id).await?;
let events = session.events().all();
if let Some(header) = wake_input.as_deref().and_then(|text| text.lines().next())
&& events.iter().any(|event| {
event.author == "user"
&& event.llm_response.content.as_ref().is_some_and(|content| {
content
.parts
.iter()
.filter_map(Part::text)
.any(|text| text.lines().next() == Some(header))
})
})
{
wake_input = None;
}
let Some(invocation_id) = resume_from else {
return Ok::<_, AdkError>(Prepared::Start);
};
if let Some(answer) = completed_answer(&events, &invocation_id) {
return Ok(Prepared::Done(answer));
}
let answered = runner
.recover_unanswered_calls_with_config(user_id, &session_id, Some(config.clone()))
.await?;
let turn_persisted = events
.iter()
.any(|event| event.invocation_id == invocation_id && event.author == "user");
let paused = format!("{SYSTEM_NOTICE_PREFIX}{FREEZE_PAUSED_NOTICE}");
let unfrozen = turn_persisted
&& matches!(record.checkpoint, Some(RunCheckpointRef::Session { .. }))
&& events
.iter()
.rev()
.find(|event| {
event.invocation_id == invocation_id
&& adk_core::history::is_system_notice_event(event)
})
.and_then(|event| event.llm_response.content.as_ref())
.and_then(|content| content.parts.first())
.and_then(Part::text)
== Some(paused.as_str());
if unfrozen {
if let Some(trail) = self.audit.as_ref().or(runner.audit_trail()) {
let actor = record
.principal
.as_ref()
.map(|principal| AuditActor::new(principal, invocation_id.as_str()))
.unwrap_or_default();
let draft =
AuditRecordDraft::new(AuditRecordKind::Governance, FREEZE_RESUMED_ACTION)
.actor(actor)
.outcome(AuditRecordOutcome::Succeeded)
.ext("runId", Value::String(record.run_id.clone()))
.ext("userId", Value::String(record.user_id.clone()))
.ext("sessionId", Value::String(session_id.clone()))
.ext("invocationId", Value::String(invocation_id.clone()))
.ext("workerId", Value::String(self.config.worker_id.clone()))
.ext("notice", Value::String(FREEZE_RESUMED_NOTICE.to_string()));
trail.record(draft).await?;
}
append_notice(runner, user_id, &session_id, &invocation_id, FREEZE_RESUMED_NOTICE)
.await?;
}
tracing::info!(
run.id = %record.run_id,
session.id = %session_id,
resumed.from = %invocation_id,
calls.answered = answered,
user_turn.persisted = turn_persisted,
resumed.after_freeze = unfrozen,
"resuming agent run"
);
Ok(if turn_persisted { Prepared::Continue } else { Prepared::Start })
};
let content = match prepared.await {
Ok(Prepared::Done(text)) => {
return Ok(Ok(Attempt::Done(agent_result(&text, &session_id, None))));
}
Ok(Prepared::Continue) => {
Content::new("user").with_text(wake_input.take().unwrap_or_default())
}
Ok(Prepared::Start) => {
match requested_call(&record.input, record.authenticated) {
Ok(call) => config.requested_call = call,
Err(error) => return Ok(Err(Failure::fatal(error))),
}
let content = input_content(&record.input);
match wake_input.take() {
Some(text) => content.with_text(text),
None => content,
}
}
Err(error) => return Ok(Err(error.into())),
};
if let Some(budget) = limits.budget.as_ref().filter(|_| subagent) {
let spent = match ensure_session(runner, user_id, &session_id).await {
Ok(session) => adk_core::subagent::spent_in_session(&session.events().all()),
Err(error) => return Ok(Err(error.into())),
};
let narrowed = config.budget.clone().unwrap_or_default().narrowed(budget);
let parent = config.budget_tracker.take();
config.budget_tracker =
Some(Arc::new(adk_core::BudgetTracker::resume(narrowed.clone(), spent, parent)));
config.budget = Some(narrowed);
}
let (user, session) =
match (UserId::try_from(user_id), SessionId::try_from(session_id.as_str())) {
(Ok(user), Ok(session)) => (user, session),
(Err(error), _) | (_, Err(error)) => {
return Ok(Err(Failure::fatal(error.to_string())));
}
};
let invocation = match runner.start_with_config(user, session, content, Some(config)).await
{
Ok(invocation) => invocation,
Err(error) => return Ok(Err(error.into())),
};
let invocation_id = invocation.invocation_id().to_string();
self.checkpoint(
&record.run_id,
epoch,
RunCheckpointRef::Session {
session_id: session_id.clone(),
invocation_id: Some(invocation_id.clone()),
},
)
.await?;
let mut events = invocation.into_events();
let mut text = String::new();
let mut interrupted = false;
let mut produced = false;
let mut stopped_by_refusal = false;
loop {
let next = tokio::select! {
next = events.next() => next,
() = cancel.cancelled(), if !interrupted => {
interrupted = true;
runner.interrupt_identity(runner.app_name(), user_id, &session_id);
continue;
}
() = lease.stopped.cancelled(), if !interrupted => {
interrupted = true;
tracing::info!(
run.id = %record.run_id,
frozen = lease.frozen.load(Ordering::SeqCst),
"stopping the run at its model-call boundary"
);
runner.interrupt_identity(runner.app_name(), user_id, &session_id);
continue;
}
};
let Some(event) = next else { break };
match event {
Ok(event) => {
produced = true;
for hooks in &self.hooks {
hooks.on_event(record, &event).await;
}
if !event.llm_response.partial
&& event.author != "user"
&& event.is_final_response()
&& let Some(content) = &event.llm_response.content
{
text = content
.parts
.iter()
.filter_map(Part::text)
.collect::<Vec<_>>()
.join("");
}
}
Err(error)
if !produced
&& (error.code == GOVERNANCE_FROZEN_CODE
|| error.code == GOVERNANCE_STALE_CODE)
&& self.refusal().is_some() =>
{
return Ok(Ok(Attempt::Refused(error)));
}
Err(error)
if (error.code == GOVERNANCE_FROZEN_CODE
|| error.code == GOVERNANCE_STALE_CODE)
&& (lease.suspend_requested.load(Ordering::SeqCst)
|| (produced
&& self.governance.is_some()
&& self.config.on_governance_refusal
== GovernanceRefusal::Park)) =>
{
if lease.suspend_requested.load(Ordering::SeqCst) {
tracing::info!(run.id = %record.run_id, error = %error.diagnostics(), "governance refused the run it was asked to suspend; suspending it");
} else {
lease.frozen.store(true, Ordering::SeqCst);
tracing::info!(run.id = %record.run_id, error = %error.diagnostics(), "governance refused the run after it made a call; parking it until unfrozen");
}
stopped_by_refusal = true;
break;
}
Err(error) => return Ok(Err(error.into())),
}
}
drop(events);
if stopped_by_refusal || lease.stopped.is_cancelled() {
if !produced
&& lease.frozen.load(Ordering::SeqCst)
&& !lease.suspend_requested.load(Ordering::SeqCst)
&& let Some(error) = self.refusal()
{
return Ok(Ok(Attempt::Refused(error)));
}
let suspended = lease.suspend_requested.load(Ordering::SeqCst);
self.checkpoint(
&record.run_id,
epoch,
RunCheckpointRef::Session {
session_id: session_id.clone(),
invocation_id: Some(invocation_id.clone()),
},
)
.await?;
if suspended {
return Ok(Ok(Attempt::Suspended));
}
if let Err(error) =
append_notice(runner, user_id, &session_id, &invocation_id, FREEZE_PAUSED_NOTICE)
.await
{
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");
}
return Ok(Ok(Attempt::Frozen));
}
let held = match held_by_invocation(runner, user_id, &session_id, &invocation_id).await {
Ok(held) => held,
Err(error) => return Ok(Err(error.into())),
};
if held.is_empty() {
return Ok(Ok(Attempt::Done(agent_result(&text, &session_id, Some(&invocation_id)))));
}
let now = self.clock.now();
let previous = match &record.checkpoint {
Some(RunCheckpointRef::AwaitingApproval { fingerprints, expires_at, .. })
if fingerprints.iter().any(|fingerprint| held.contains(fingerprint)) =>
{
Some(*expires_at)
}
_ => None,
};
if let Some(Some(expired)) = previous
&& expired <= now
{
return Ok(Err(Failure::fatal(format!(
"approval expired at {expired} for held tool calls {held:?}; no decision was recorded"
))));
}
let until = previous.unwrap_or_else(|| {
self.config
.approval_timeout
.and_then(|timeout| chrono::Duration::from_std(timeout).ok())
.and_then(|timeout| now.checked_add_signed(timeout))
});
tracing::info!(
run.id = %record.run_id,
session.id = %session_id,
held.fingerprints = ?held,
"agent run holds tool calls for approval"
);
self.checkpoint(
&record.run_id,
epoch,
RunCheckpointRef::AwaitingApproval {
session_id,
invocation_id: Some(invocation_id),
fingerprints: held,
expires_at: until,
},
)
.await?;
Ok(Ok(Attempt::Parked(until)))
}
}
async fn held_by_invocation(
runner: &Runner,
user_id: &str,
session_id: &str,
invocation_id: &str,
) -> adk_core::Result<Vec<String>> {
let identity = adk_core::AdkIdentity::new(
adk_core::AppName::try_from(runner.app_name())?,
UserId::try_from(user_id)?,
SessionId::try_from(session_id)?,
);
let events = runner.session_service().get_for_identity(&identity).await?.events().all();
let mut surfaced: Vec<(&str, &str, Option<&str>)> = events
.iter()
.filter(|event| event.invocation_id == invocation_id)
.filter_map(|event| {
event.actions.tool_confirmation.as_ref().map(|request| {
(event.author.as_str(), event.branch.as_str(), request.function_call_id.as_deref())
})
})
.collect();
surfaced.dedup();
let mut held = Vec::new();
for (author, branch, _) in &surfaced {
for call in adk_core::held_tool_calls(&events, author, branch) {
let from_this_invocation = surfaced.iter().any(|(a, b, id)| {
a == author && b == branch && *id == call.request.function_call_id.as_deref()
});
let fingerprint = call.request.fingerprint();
if from_this_invocation && !held.contains(&fingerprint) {
held.push(fingerprint);
}
}
}
Ok(held)
}
enum Prepared {
Start,
Continue,
Done(String),
}
pub struct WorkerHandle {
shutdown: CancellationToken,
task: tokio::task::JoinHandle<()>,
wake: Arc<Notify>,
heartbeat_now: Arc<Notify>,
suspensions: Arc<Suspensions>,
frozen: Arc<FrozenRuns>,
runs: Arc<dyn DurableRunStore>,
}
impl std::fmt::Debug for WorkerHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WorkerHandle")
.field("finished", &self.task.is_finished())
.field("suspensions", &self.suspensions)
.field("frozen", &self.frozen)
.finish_non_exhaustive()
}
}
impl WorkerHandle {
pub fn wake(&self) {
self.wake.notify_one();
}
pub fn heartbeat_now(&self) {
self.heartbeat_now.notify_waiters();
}
pub fn suspend(&self, run_id: &str) -> bool {
self.suspensions.request(run_id)
}
pub async fn wake_frozen(&self) -> usize {
self.frozen.wake(&self.runs).await
}
pub fn frozen_runs(&self) -> Vec<String> {
self.frozen.ids()
}
pub async fn shutdown(self) {
self.shutdown.cancel();
let _ = self.task.await;
}
pub fn abort(&self) {
self.task.abort();
}
pub fn is_finished(&self) -> bool {
self.task.is_finished()
}
}
#[derive(Default)]
struct Suspensions(std::sync::Mutex<HashMap<String, Arc<LeaseState>>>);
impl std::fmt::Debug for Suspensions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let attempts = self.0.lock().unwrap_or_else(|e| e.into_inner());
f.debug_struct("Suspensions").field("in_flight", &attempts.len()).finish()
}
}
impl Suspensions {
fn register(
suspensions: &Arc<Self>,
run_id: &str,
lease: &Arc<LeaseState>,
) -> SuspendRegistration {
suspensions
.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(run_id.to_string(), Arc::clone(lease));
SuspendRegistration {
suspensions: Arc::clone(suspensions),
run_id: run_id.to_string(),
lease: Arc::clone(lease),
}
}
fn request(&self, run_id: &str) -> bool {
let attempts = self.0.lock().unwrap_or_else(|e| e.into_inner());
let Some(lease) = attempts.get(run_id) else {
tracing::debug!(
run.id = run_id,
"no agent attempt of the run is in flight here; not suspending"
);
return false;
};
if !lease.suspend_requested.swap(true, Ordering::SeqCst) {
tracing::info!(
run.id = run_id,
"suspend requested; the run parks at its next model-call boundary"
);
}
true
}
}
struct SuspendRegistration {
suspensions: Arc<Suspensions>,
run_id: String,
lease: Arc<LeaseState>,
}
impl Drop for SuspendRegistration {
fn drop(&mut self) {
let mut attempts = self.suspensions.0.lock().unwrap_or_else(|e| e.into_inner());
if attempts.get(&self.run_id).is_some_and(|lease| Arc::ptr_eq(lease, &self.lease)) {
attempts.remove(&self.run_id);
}
}
}
#[derive(Default)]
struct FrozenRuns(std::sync::Mutex<BTreeSet<String>>);
impl std::fmt::Debug for FrozenRuns {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let ids = self.0.lock().unwrap_or_else(|e| e.into_inner());
f.debug_struct("FrozenRuns").field("parked", &ids.len()).finish()
}
}
impl FrozenRuns {
fn insert(&self, run_id: &str) {
self.0.lock().unwrap_or_else(|e| e.into_inner()).insert(run_id.to_string());
}
fn ids(&self) -> Vec<String> {
self.0.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect()
}
fn is_empty(&self) -> bool {
self.0.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
}
async fn wake(&self, runs: &Arc<dyn DurableRunStore>) -> usize {
let parked = std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner()));
let mut woken = 0;
for run_id in parked {
match runs.wake(&run_id).await {
Ok(()) => woken += 1,
Err(error) if error.code == RUN_NOT_FOUND_CODE => {
tracing::debug!(run.id = %run_id, "frozen run no longer exists; not woken");
}
Err(error) => {
tracing::warn!(run.id = %run_id, error = %error, "could not wake the frozen run; it stays listed");
self.insert(&run_id);
}
}
}
woken
}
}
struct SuspendGate {
lease: Arc<LeaseState>,
governance: Option<GovernanceControl>,
}
impl std::fmt::Debug for SuspendGate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SuspendGate").finish_non_exhaustive()
}
}
#[async_trait]
impl InvocationHooks for SuspendGate {
async fn before_model(
&self,
_ctx: Arc<dyn CallbackContext>,
request: LlmRequest,
) -> adk_core::Result<BeforeModelResult> {
if self.lease.suspend_requested.load(Ordering::SeqCst) {
self.lease.stopped.cancel();
std::future::pending::<()>().await;
}
if let Some(control) = &self.governance
&& let Err(error) = control.check()
{
tracing::info!(error = %error.diagnostics(), "governance refuses work at a model-call boundary; stopping the run there");
self.lease.frozen.store(true, Ordering::SeqCst);
self.lease.stopped.cancel();
std::future::pending::<()>().await;
}
Ok(BeforeModelResult::Continue(request))
}
}
struct LeaseState {
ttl: Duration,
valid_until: std::sync::Mutex<Instant>,
lost_flag: AtomicBool,
lost: Notify,
cancel_requested: AtomicBool,
suspend_requested: AtomicBool,
frozen: AtomicBool,
stopped: CancellationToken,
}
impl LeaseState {
fn new(ttl: Duration) -> Self {
Self {
ttl,
valid_until: std::sync::Mutex::new(Instant::now() + ttl),
lost_flag: AtomicBool::new(false),
lost: Notify::new(),
cancel_requested: AtomicBool::new(false),
suspend_requested: AtomicBool::new(false),
frozen: AtomicBool::new(false),
stopped: CancellationToken::new(),
}
}
fn renewed(&self, sent: Instant) {
*self.valid_until.lock().unwrap_or_else(|e| e.into_inner()) = sent + self.ttl;
}
fn is_valid(&self) -> bool {
!self.lost_flag.load(Ordering::SeqCst)
&& Instant::now() < *self.valid_until.lock().unwrap_or_else(|e| e.into_inner())
}
fn lose(&self) {
if !self.lost_flag.swap(true, Ordering::SeqCst) {
self.lost.notify_waiters();
}
self.lost.notify_one();
}
async fn fence(&self) {
if !self.is_valid() {
tracing::warn!("lease no longer provably held; fencing the attempt");
self.lose();
std::future::pending::<()>().await;
}
}
}
struct LeaseFence(Arc<LeaseState>);
impl std::fmt::Debug for LeaseFence {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LeaseFence").finish_non_exhaustive()
}
}
#[async_trait]
impl InvocationHooks for LeaseFence {
async fn before_model(
&self,
_ctx: Arc<dyn CallbackContext>,
request: LlmRequest,
) -> adk_core::Result<BeforeModelResult> {
self.0.fence().await;
Ok(BeforeModelResult::Continue(request))
}
async fn after_model(
&self,
_ctx: Arc<dyn CallbackContext>,
_response: LlmResponse,
) -> adk_core::Result<Option<LlmResponse>> {
self.0.fence().await;
Ok(None)
}
async fn before_tool(
&self,
_ctx: Arc<dyn CallbackContext>,
) -> adk_core::Result<Option<Content>> {
self.0.fence().await;
Ok(None)
}
async fn after_tool(
&self,
_ctx: Arc<dyn CallbackContext>,
) -> adk_core::Result<Option<Content>> {
self.0.fence().await;
Ok(None)
}
}
async fn ensure_session(
runner: &Runner,
user_id: &str,
session_id: &str,
) -> adk_core::Result<Box<dyn adk_session::Session>> {
let identity = adk_core::AdkIdentity::new(
adk_core::AppName::try_from(runner.app_name())?,
UserId::try_from(user_id)?,
SessionId::try_from(session_id)?,
);
match runner.session_service().get_for_identity(&identity).await {
Err(error) if error.is_not_found() => {
let created = runner
.session_service()
.create(adk_session::CreateRequest {
app_name: runner.app_name().to_string(),
user_id: user_id.to_string(),
session_id: Some(session_id.to_string()),
state: std::collections::HashMap::new(),
})
.await;
match created {
Err(error) if error.is_conflict() => {
runner.session_service().get_for_identity(&identity).await
}
other => other,
}
}
other => other,
}
}
async fn append_notice(
runner: &Runner,
user_id: &str,
session_id: &str,
invocation_id: &str,
text: &str,
) -> adk_core::Result<()> {
let identity = adk_core::AdkIdentity::new(
adk_core::AppName::try_from(runner.app_name())?,
UserId::try_from(user_id)?,
SessionId::try_from(session_id)?,
);
runner
.session_service()
.append_event_for_identity(adk_session::AppendEventRequest {
identity,
event: adk_core::history::system_notice_event(invocation_id, text),
})
.await
}
fn completed_answer(events: &[adk_core::Event], invocation_id: &str) -> Option<String> {
if events.iter().any(|event| {
event.invocation_id == invocation_id && event.actions.tool_confirmation.is_some()
}) {
return None;
}
let last = events.iter().rev().find(|event| {
!event.llm_response.partial && !adk_core::history::is_system_notice_event(event)
})?;
if last.invocation_id != invocation_id || last.author == "user" || !last.is_final_response() {
return None;
}
let text: String = last
.llm_response
.content
.as_ref()?
.parts
.iter()
.filter_map(Part::text)
.collect::<Vec<_>>()
.join("");
(!text.is_empty()).then_some(text)
}
fn agent_result(text: &str, session_id: &str, invocation_id: Option<&str>) -> Value {
let mut result = serde_json::json!({ "text": text, "sessionId": session_id });
if let Some(invocation_id) = invocation_id {
result["invocationId"] = Value::String(invocation_id.to_string());
}
result
}
fn apply_limits(runner: &Runner, limits: &adk_core::RunLimits, config: &mut adk_core::RunConfig) {
if let Some(budget) = &limits.budget {
config.budget = Some(match config.budget.take() {
Some(own) => own.narrowed(budget),
None => budget.clone(),
});
}
if let Some(tools) = &limits.allowed_tools {
let mut layers: Vec<Arc<dyn adk_core::ToolPolicy>> = config
.tool_policy
.clone()
.or_else(|| runner.tool_policy().cloned())
.into_iter()
.collect();
layers.push(Arc::new(adk_core::ToolCeiling::new(tools.iter().cloned())));
config.tool_policy = Some(Arc::new(adk_core::StrictestPolicy::new(layers)));
}
}
pub(crate) fn input_content(input: &Value) -> Content {
match input {
Value::String(text) => Content::new("user").with_text(text),
Value::Object(map) => {
if let Some(content) = map
.get("content")
.and_then(|value| serde_json::from_value::<Content>(value.clone()).ok())
{
return content;
}
match map.get("text").and_then(Value::as_str) {
Some(text) => Content::new("user").with_text(text),
None if map.contains_key(REQUESTED_CALL_INPUT_KEY) => {
Content::new("user").with_text("")
}
None => Content::new("user").with_text(input.to_string()),
}
}
other => Content::new("user").with_text(other.to_string()),
}
}
const REQUESTED_CALL_INPUT_KEY: &str = "requestedCall";
fn requested_call(input: &Value, authenticated: bool) -> Result<Option<RequestedCall>, String> {
let Some(raw) = input.get(REQUESTED_CALL_INPUT_KEY) else {
return Ok(None);
};
if !authenticated {
tracing::warn!("ignored a requested call on a run no authenticated caller enqueued");
return Ok(None);
}
serde_json::from_value(raw.clone()).map(Some).map_err(|error| {
format!(
"the run's {REQUESTED_CALL_INPUT_KEY} is not a requested call: {error}. Enqueue it \
as an adk_core::RequestedCall"
)
})
}
fn workflow_input(input: &Value) -> WorkflowState {
match input {
Value::Object(map) => map.clone().into_iter().collect(),
Value::Null => WorkflowState::new(),
other => [("input".to_string(), other.clone())].into_iter().collect(),
}
}