adk-server 3.0.0

HTTP server for ADK-Rust agents: REST and SSE, A2A v1.0, background runs and cron, approvals, and the AWP agent edge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Admin endpoints for the organisation kill switch.
//!
//! Mounted by [`ServerBuilder::enable_governance_endpoints`](crate::ServerBuilder::enable_governance_endpoints)
//! behind the server's auth middleware:
//!
//! - `POST /api/admin/freeze` — freezes execution; on a mirrored control the freeze is
//!   written to the shared governance store and reaches every replica. Running durable
//!   runs are asked to cancel through the run store, or parked by a [`FreezeDelegate`]
//!   when one is registered (spec 3.2 §10 S4).
//! - `POST /api/admin/unfreeze` — lifts the freeze.
//! - `GET /api/admin/governance` — reports the current state, including what a freeze does
//!   with running runs (`runningRuns`: `park` under a delegate, `cancel` otherwise).
//!
//! A freeze or an unfreeze needs an administrator: a caller whose scopes include the admin
//! scope ([`SecurityConfig::admin_scope`](crate::SecurityConfig::admin_scope), `"admin"` by
//! default). A request with no caller — a server without a `RequestContextExtractor` — is
//! refused with `401` (`governance.unauthenticated`), and an authenticated caller without the
//! scope with `403` (`governance.forbidden`); either leaves the control as it was. The status
//! is open to every caller the auth middleware admits.
//!
//! When the control has an audit trail attached
//! ([`GovernanceControl::attach_audit`]), both changes are recorded with the calling
//! user as the actor. A freeze takes effect even when its record fails, and answers
//! `503`; an unfreeze that cannot be recorded under `AuditFailureMode::Block` is refused
//! with `503` and execution stays frozen. The `503` status's `error` follows
//! [`SecurityConfig::expose_error_details`](crate::SecurityConfig::expose_error_details).

use std::sync::Arc;

use adk_core::audit_log::AuditActor;
use adk_core::principal::SubjectRef;
use adk_core::{
    AdkError, DurableRunStore, ErrorCategory, ErrorComponent, GovernanceControl, RequestContext,
    RunFilter, RunState,
};
use async_trait::async_trait;
use axum::{
    Extension, Json,
    extract::State,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};

use super::error_details;

/// What a freeze does with the runs that were running (spec 3.2 §10 S4), as
/// `GET /api/admin/governance` reports it in `runningRuns`.
///
/// # Example
///
/// ```rust
/// use adk_server::rest::RunningRuns;
///
/// assert_eq!(serde_json::to_value(RunningRuns::Park).unwrap(), "park");
/// assert_eq!(serde_json::to_value(RunningRuns::Cancel).unwrap(), "cancel");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RunningRuns {
    /// Running runs are parked `Waiting` at their next checkpoint and resume on unfreeze.
    Park,
    /// Running runs are asked to cancel and cannot resume.
    Cancel,
}

/// What a [`FreezeDelegate`]'s freeze did with the runs that were running.
///
/// # Example
///
/// ```rust
/// use adk_server::rest::FreezeReport;
///
/// let report = FreezeReport { parked_runs: 6, cancelled_runs: 0 };
/// assert_eq!(report.parked_runs + report.cancelled_runs, 6);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FreezeReport {
    /// Runs parked `Waiting`, to resume on unfreeze.
    pub parked_runs: usize,
    /// Runs asked to cancel.
    pub cancelled_runs: usize,
}

/// Freezes and unfreezes on behalf of the admin endpoints, in place of the controller's own
/// freeze (spec 3.2 §10 S4): a kernel registers one so `POST /api/admin/freeze` parks its
/// running processes instead of cancelling them, and `POST /api/admin/unfreeze` wakes them.
///
/// The delegate owns the whole change: it writes the control, with
/// [`GovernanceControl::freeze_recorded`] and [`unfreeze_recorded`], records the audit
/// records, and stops or resumes the runs. The endpoints report what it returns.
///
/// [`unfreeze_recorded`]: GovernanceControl::unfreeze_recorded
///
/// # Example
///
/// ```rust
/// use adk_core::GovernanceControl;
/// use adk_core::audit_log::AuditActor;
/// use adk_server::rest::{FreezeDelegate, FreezeReport};
/// use async_trait::async_trait;
///
/// struct ParkEverything(GovernanceControl);
///
/// #[async_trait]
/// impl FreezeDelegate for ParkEverything {
///     async fn freeze(&self, reason: &str, by: AuditActor) -> adk_core::Result<FreezeReport> {
///         self.0.freeze_recorded(reason, by).await?;
///         // ... suspend every running process at its next checkpoint ...
///         Ok(FreezeReport { parked_runs: 0, cancelled_runs: 0 })
///     }
///
///     async fn unfreeze(&self, by: AuditActor) -> adk_core::Result<()> {
///         self.0.unfreeze_recorded(by).await
///         // ... then wake what the freeze parked ...
///     }
/// }
/// ```
#[async_trait]
pub trait FreezeDelegate: Send + Sync {
    /// Freezes execution for `reason` as `by`, stops the running runs, and reports what
    /// happened to them.
    ///
    /// # Errors
    ///
    /// Returns the control's or the store's error; the endpoint answers `503` with it, and
    /// the delegate is expected to have frozen this replica regardless.
    async fn freeze(&self, reason: &str, by: AuditActor) -> adk_core::Result<FreezeReport>;

    /// Lifts the freeze as `by` and resumes what the freeze stopped.
    ///
    /// # Errors
    ///
    /// Returns the control's or the store's error; the endpoint answers `503` with it, and
    /// execution stays frozen.
    async fn unfreeze(&self, by: AuditActor) -> adk_core::Result<()>;

    /// What a freeze does with running runs, reported as `runningRuns`. A delegate parks.
    fn running_runs(&self) -> RunningRuns {
        RunningRuns::Park
    }
}

/// State for the governance admin endpoints.
#[derive(Clone)]
pub struct GovernanceController {
    control: GovernanceControl,
    run_stores: Vec<Arc<dyn DurableRunStore>>,
    delegate: Option<Arc<dyn FreezeDelegate>>,
    expose_error_details: bool,
    admin_scope: String,
}

impl std::fmt::Debug for GovernanceController {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GovernanceController")
            .field("control", &self.control)
            .field("run_stores", &self.run_stores.len())
            .field("delegate", &self.delegate.is_some())
            .field("expose_error_details", &self.expose_error_details)
            .field("admin_scope", &self.admin_scope)
            .finish()
    }
}

impl GovernanceController {
    /// Endpoints over `control`, whose freeze and unfreeze admit callers with the
    /// [`ADMIN_SCOPE`](crate::ADMIN_SCOPE).
    pub fn new(control: GovernanceControl) -> Self {
        Self {
            control,
            run_stores: Vec::new(),
            delegate: None,
            expose_error_details: false,
            admin_scope: crate::ADMIN_SCOPE.to_string(),
        }
    }

    /// Whether a `503`'s `error` carries the store's or the delegate's own message (default:
    /// `false`); see [`SecurityConfig::expose_error_details`](crate::SecurityConfig::expose_error_details).
    /// `ServerBuilder::enable_governance_endpoints` sets it from the server's
    /// [`SecurityConfig`](crate::SecurityConfig).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::GovernanceControl;
    /// use adk_server::GovernanceController;
    ///
    /// let controller = GovernanceController::new(GovernanceControl::new()).with_error_details(true);
    /// ```
    #[must_use]
    pub fn with_error_details(mut self, expose: bool) -> Self {
        self.expose_error_details = expose;
        self
    }

    /// Admits to the freeze and the unfreeze only callers whose scopes include `scope`.
    /// [`ServerBuilder`](crate::ServerBuilder) sets the server's
    /// [`SecurityConfig::admin_scope`](crate::SecurityConfig::admin_scope).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::GovernanceControl;
    /// use adk_server::GovernanceController;
    ///
    /// let controller = GovernanceController::new(GovernanceControl::new()).with_admin_scope("ops");
    /// # let _ = controller;
    /// ```
    pub fn with_admin_scope(mut self, scope: impl Into<String>) -> Self {
        self.admin_scope = scope.into();
        self
    }

    /// A freeze also requests cancellation of every running run in `store`, unless a
    /// [`FreezeDelegate`] handles the freeze.
    pub fn with_run_store(mut self, store: Arc<dyn DurableRunStore>) -> Self {
        if !self.run_stores.iter().any(|existing| Arc::ptr_eq(existing, &store)) {
            self.run_stores.push(store);
        }
        self
    }

    /// Hands freezes and unfreezes to `delegate` (spec 3.2 §10 S4), so a freeze parks the
    /// running runs the delegate supervises instead of cancelling the run stores' runs.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let controller = GovernanceController::new(control).with_freeze_delegate(kernel);
    /// ```
    pub fn with_freeze_delegate(mut self, delegate: Arc<dyn FreezeDelegate>) -> Self {
        self.delegate = Some(delegate);
        self
    }

    /// What a freeze does with running runs.
    pub fn running_runs(&self) -> RunningRuns {
        self.delegate.as_ref().map_or(RunningRuns::Cancel, |delegate| delegate.running_runs())
    }

    fn status(&self) -> GovernanceStatus {
        GovernanceStatus {
            frozen: self.control.is_frozen(),
            reason: self.control.reason(),
            mirrored: self.control.is_mirrored(),
            stale: self.control.is_stale(),
            running_runs: self.running_runs(),
            parked_runs: None,
            cancelled_runs: None,
            error: None,
        }
    }

    /// Asks every running run in the run stores to cancel and returns how many were asked.
    async fn cancel_running(&self) -> usize {
        let mut cancelled = 0;
        for store in &self.run_stores {
            let running = store.list(RunFilter::default().states([RunState::Running])).await;
            match running {
                Ok(runs) => {
                    for run in runs {
                        match store.request_cancel(&run.run_id).await {
                            Ok(()) => cancelled += 1,
                            Err(error) => {
                                tracing::error!(run.id = %run.run_id, error = %error, "could not request cancellation of a running run")
                            }
                        }
                    }
                }
                Err(error) => {
                    tracing::error!(error = %error, "could not list running runs to cancel")
                }
            }
        }
        cancelled
    }
}

/// `POST /api/admin/freeze` request body.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FreezeRequest {
    /// Why execution is frozen; carried in every error a frozen run returns.
    #[serde(default)]
    pub reason: Option<String>,
}

/// The kill switch's current state.
///
/// # Example
///
/// ```rust
/// use adk_server::rest::{GovernanceStatus, RunningRuns};
///
/// let status = GovernanceStatus {
///     frozen: true,
///     reason: Some("incident 7".into()),
///     mirrored: false,
///     stale: false,
///     running_runs: RunningRuns::Park,
///     parked_runs: Some(6),
///     cancelled_runs: Some(0),
///     error: None,
/// };
/// let json = serde_json::to_value(&status).unwrap();
/// assert_eq!(json["runningRuns"], "park");
/// assert_eq!(json["parkedRuns"], 6);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GovernanceStatus {
    /// Whether execution is frozen.
    pub frozen: bool,
    /// The freeze reason, while frozen.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Whether the control mirrors a shared governance store.
    pub mirrored: bool,
    /// Whether a mirrored control has gone past its staleness limit.
    pub stale: bool,
    /// What a freeze does with running runs: `park` under a [`FreezeDelegate`], else `cancel`.
    pub running_runs: RunningRuns,
    /// Running durable runs this freeze parked, to resume on unfreeze.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parked_runs: Option<usize>,
    /// Running durable runs asked to cancel by this freeze.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancelled_runs: Option<usize>,
    /// Why the shared store could not be written, as `{component}.{category}: {message}`. The
    /// message is the generic one for its category unless
    /// [`SecurityConfig::expose_error_details`](crate::SecurityConfig::expose_error_details) is
    /// set or the server wrote it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// The audit actor for an administrator's request: the authenticated user, who is also
/// the issuer written to the shared store.
fn admin_actor(caller: &RequestContext) -> AuditActor {
    AuditActor {
        on_behalf_of: Some(SubjectRef::human(caller.user_id.clone())),
        ..AuditActor::default()
    }
}

/// The caller of a freeze or an unfreeze when they are an administrator; otherwise the
/// refusal: `401` without a caller, `403` without the admin scope.
fn administrator(
    controller: &GovernanceController,
    caller: Option<RequestContext>,
    action: &str,
) -> Result<RequestContext, Response> {
    let scope = &controller.admin_scope;
    let refusal = |category, code, message: String| {
        let error = AdkError::new(ErrorComponent::Server, category, code, message);
        let status = StatusCode::from_u16(error.http_status_code())
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        (status, Json(error.to_problem_json())).into_response()
    };
    let Some(caller) = caller else {
        tracing::warn!(governance.action = action, "governance change refused: no caller");
        return Err(refusal(
            ErrorCategory::Unauthorized,
            "governance.unauthenticated",
            format!(
                "{action} needs an authenticated administrator; configure a \
                 RequestContextExtractor that grants the `{scope}` scope"
            ),
        ));
    };
    if !caller.scopes.iter().any(|granted| granted == scope) {
        tracing::warn!(
            caller.user_id = %caller.user_id,
            governance.action = action,
            "governance change refused: the caller is not an administrator"
        );
        return Err(refusal(
            ErrorCategory::Forbidden,
            "governance.forbidden",
            format!("{} may not {action}: it needs the `{scope}` scope", caller.user_id),
        ));
    }
    Ok(caller)
}

/// `POST /api/admin/freeze`
///
/// Responds `401` without a caller and `403` to a caller without the admin scope, and
/// leaves the control as it was.
///
/// Responds `503` with the status when the shared store could not be written; this
/// replica is frozen regardless.
pub async fn freeze(
    State(controller): State<GovernanceController>,
    Extension(caller): Extension<Option<RequestContext>>,
    Json(request): Json<FreezeRequest>,
) -> Response {
    let caller = match administrator(&controller, caller, "freeze") {
        Ok(caller) => caller,
        Err(refusal) => return refusal,
    };
    let reason = request.reason.unwrap_or_else(|| "frozen by an administrator".to_string());
    tracing::warn!(
        caller.user_id = %caller.user_id,
        governance.reason = %reason,
        "governance freeze requested"
    );
    let actor = admin_actor(&caller);
    let mut status = controller.status();
    let written = match &controller.delegate {
        Some(delegate) => match delegate.freeze(&reason, actor).await {
            Ok(report) => {
                status.parked_runs = Some(report.parked_runs);
                status.cancelled_runs = Some(report.cancelled_runs);
                tracing::warn!(
                    runs.parked = report.parked_runs,
                    runs.cancel_requested = report.cancelled_runs,
                    "governance freeze applied by the delegate"
                );
                Ok(())
            }
            Err(error) => Err(error),
        },
        None => {
            let written = controller.control.freeze_recorded(reason, actor).await;
            let cancelled = controller.cancel_running().await;
            tracing::warn!(runs.cancel_requested = cancelled, "governance freeze applied");
            status.parked_runs = Some(0);
            status.cancelled_runs = Some(cancelled);
            written
        }
    };
    // Read again, so the status carries the state the freeze left.
    let current = controller.status();
    status.frozen = current.frozen;
    status.reason = current.reason;
    status.stale = current.stale;
    match written {
        Ok(()) => Json(status).into_response(),
        Err(error) => {
            status.error = Some(error_details::display(&error, controller.expose_error_details));
            (StatusCode::SERVICE_UNAVAILABLE, Json(status)).into_response()
        }
    }
}

/// `POST /api/admin/unfreeze`
///
/// Responds `401` without a caller and `403` to a caller without the admin scope, and
/// leaves the freeze in force.
///
/// Responds `503` with the status when the shared store could not be written; the
/// freeze then stays in force.
pub async fn unfreeze(
    State(controller): State<GovernanceController>,
    Extension(caller): Extension<Option<RequestContext>>,
) -> Response {
    let caller = match administrator(&controller, caller, "unfreeze") {
        Ok(caller) => caller,
        Err(refusal) => return refusal,
    };
    tracing::warn!(caller.user_id = %caller.user_id, "governance unfreeze requested");
    let actor = admin_actor(&caller);
    let lifted = match &controller.delegate {
        Some(delegate) => delegate.unfreeze(actor).await,
        None => controller.control.unfreeze_recorded(actor).await,
    };
    match lifted {
        Ok(()) => Json(controller.status()).into_response(),
        Err(error) => {
            let mut status = controller.status();
            status.error = Some(error_details::display(&error, controller.expose_error_details));
            (StatusCode::SERVICE_UNAVAILABLE, Json(status)).into_response()
        }
    }
}

/// `GET /api/admin/governance`
pub async fn status(State(controller): State<GovernanceController>) -> Json<GovernanceStatus> {
    Json(controller.status())
}