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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! Approval inbox endpoints, a background ticker, and a signed webhook notifier for an
//! [`ApprovalService`].
//!
//! Mount the endpoints with [`ServerBuilder::with_approval_service`](crate::ServerBuilder::with_approval_service),
//! which places them behind the server's auth middleware. Every route needs an
//! authenticated caller: without a `RequestContextExtractor`, or without a request
//! context, they answer `401`. The caller is the approver: by default the person named
//! by `RequestContext::user_id`, a member of the groups in `RequestContext::scopes`
//! ([`ApprovalEndpoints::with_identity`] changes the mapping).
//!
//! | Route | Effect |
//! |-------|--------|
//! | `GET /api/approvals` | The caller's inbox. Query: `state` (repeatable via comma list), `group`, `app`, `user`, `session` (with `app`; one session of `user`, the caller by default), `cursor`, `limit` |
//! | `GET /api/approvals/{id}` | One request the caller may decide, cancel, or asked for |
//! | `POST /api/approvals/{id}/decide` | Body `{"expectedVersion": 3, "action": "approve" \| "edit" \| "reject" \| "respond", "editedArgs": {...}, "reason": "...", "via": {"kind": "human", "id": "ana"}}` |
//! | `POST /api/approvals/{id}/cancel` | Body `{"reason": "..."}`; the requester or an approver |
//! | `POST /api/approvals/delegations` | Body `{"to": {"kind": "human", "id": "bo"}, "notBefore": "...", "notAfter": "...", "scope": {...}}`; delegates the caller's authority |
//! | `DELETE /api/approvals/delegations/{id}?toKind=human&toId=bo` | Revokes a delegation the caller granted or holds |
//!
//! Errors are problem documents with the service's error code: `409` for
//! `approval.version_conflict` (re-read and decide again), `403` for self-approval or a
//! caller who is not an approver, `404` for an unknown request. Request bodies omit the
//! call's fingerprint, which carries the unredacted arguments, and add `showsCallArgs`:
//! whether `argsRedacted` are the call's own arguments, which an edit starting from them
//! needs. A resolution authorizes only
//! the call the request describes: the fingerprint names its acting agent and its tool's
//! [`ToolOrigin`](adk_core::ToolOrigin), shown on the request.
//!
//! A host that knows more about a decision than its approval policy — which surface may give
//! which answer (spec 3.3 §7.2) — installs a [`DecideGuard`] with
//! [`ApprovalEndpoints::with_decide_guard`]: it checks every decision on
//! `POST /api/approvals/{id}/decide` before the service records it, refusing with its own
//! problem document, and hears of each one the service recorded.

use std::sync::Arc;
use std::time::Duration;

use adk_core::principal::{SubjectKind, SubjectRef};
use adk_core::{
    AdkError, ApprovalAction, ApprovalDecision, ApprovalDelegation, ApprovalNotification,
    ApprovalNotifier, ApprovalRequest, ApprovalService, ApprovalState, DelegationScope,
    DelegationWindow, ErrorCategory, ErrorComponent, InboxQuery, RequestContext,
};
use async_trait::async_trait;
use axum::extract::{Path, Query, State};
use axum::http::{Extensions, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use axum::{Extension, Json, Router};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde_json::Value;

/// Maps an authenticated request to the approver it acts as: a subject and its groups.
pub type ApproverIdentity = Arc<dyn Fn(&RequestContext) -> (SubjectRef, Vec<String>) + Send + Sync>;

/// One decision on `POST /api/approvals/{id}/decide`, as a [`DecideGuard`] sees it: who
/// sends it, how the request reached the server, the request it answers and the answer.
#[derive(Debug)]
#[non_exhaustive]
pub struct DecideCall<'a> {
    /// The authenticated caller.
    pub caller: &'a RequestContext,
    /// The HTTP request's extensions, where a host's own middleware leaves what it
    /// established about the request, such as the transport it came on.
    pub extensions: &'a Extensions,
    /// The request being answered, as it is before the answer.
    pub request: &'a ApprovalRequest,
    /// The answer.
    pub action: ApprovalAction,
}

/// A host's check of every decision the approval endpoints receive (spec 3.3 §7.2, §11): it
/// runs after the caller is authenticated and before the service records the decision, and
/// hears of each decision the service recorded.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_core::{
///     AdkError, ApprovalAction, ErrorCategory, ErrorComponent, InMemoryApprovalStore,
///     StoreApprovalService,
/// };
/// use adk_server::approvals::{ApprovalEndpoints, DecideCall, DecideGuard, approvals_router};
///
/// struct NoEdits;
///
/// #[async_trait::async_trait]
/// impl DecideGuard for NoEdits {
///     async fn check(&self, call: &DecideCall<'_>) -> Result<(), AdkError> {
///         match call.action {
///             ApprovalAction::Edit => Err(AdkError::new(
///                 ErrorComponent::Server,
///                 ErrorCategory::Forbidden,
///                 "example.no_edits",
///                 "edit it in the home",
///             )),
///             _ => Ok(()),
///         }
///     }
/// }
///
/// let service = Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())));
/// let router = approvals_router(ApprovalEndpoints::new(service).with_decide_guard(Arc::new(NoEdits)));
/// # let _ = router;
/// ```
#[async_trait]
pub trait DecideGuard: Send + Sync {
    /// Refuses `call` with the error the caller gets, or admits it.
    ///
    /// # Errors
    ///
    /// The refusal, answered as a problem document with its status.
    async fn check(&self, call: &DecideCall<'_>) -> Result<(), AdkError>;

    /// Hears that the service recorded `call` and answered `decided`. Nothing it does
    /// changes the response.
    async fn decided(&self, call: &DecideCall<'_>, decided: &ApprovalRequest) {
        let _ = (call, decided);
    }
}

/// State for the approval endpoints.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
/// use adk_server::approvals::{ApprovalEndpoints, approvals_router};
///
/// let service = Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())));
/// let router = approvals_router(ApprovalEndpoints::new(service));
/// # let _ = router;
/// ```
#[derive(Clone)]
pub struct ApprovalEndpoints {
    service: Arc<dyn ApprovalService>,
    identity: ApproverIdentity,
    guard: Option<Arc<dyn DecideGuard>>,
}

impl ApprovalEndpoints {
    /// Endpoints over `service`, with callers mapped to `human(user_id)` in the groups
    /// named by their scopes.
    pub fn new(service: Arc<dyn ApprovalService>) -> Self {
        Self {
            service,
            identity: Arc::new(|caller: &RequestContext| {
                (SubjectRef::human(caller.user_id.clone()), caller.scopes.clone())
            }),
            guard: None,
        }
    }

    /// Checks every decision with `guard` before the service records it (spec 3.3 §7.2).
    #[must_use]
    pub fn with_decide_guard(mut self, guard: Arc<dyn DecideGuard>) -> Self {
        self.guard = Some(guard);
        self
    }

    /// The approval service the endpoints serve, which
    /// [`ServerBuilder::with_approval_endpoints`](crate::ServerBuilder::with_approval_endpoints)
    /// also hands its runtime routes (spec 3.3 §7.2).
    pub fn service(&self) -> &Arc<dyn ApprovalService> {
        &self.service
    }

    /// Maps callers to approvers with `identity`.
    #[must_use]
    pub fn with_identity(
        mut self,
        identity: impl Fn(&RequestContext) -> (SubjectRef, Vec<String>) + Send + Sync + 'static,
    ) -> Self {
        self.identity = Arc::new(identity);
        self
    }

    fn caller(
        &self,
        context: Option<RequestContext>,
    ) -> Result<(SubjectRef, Vec<String>), Response> {
        match context {
            Some(context) => Ok((self.identity)(&context)),
            None => Err((
                StatusCode::UNAUTHORIZED,
                Json(serde_json::json!({
                    "error": "approval endpoints need an authenticated caller; configure a \
                              RequestContextExtractor"
                })),
            )
                .into_response()),
        }
    }

    /// Whether `subject` in `groups` may see `request`: an approver now, directly or by
    /// a live delegation, or the requester.
    async fn may_see(
        &self,
        request: &ApprovalRequest,
        subject: &SubjectRef,
        groups: &[String],
    ) -> Result<bool, AdkError> {
        if request.is_eligible(subject, groups) || request.is_self(subject) {
            return Ok(true);
        }
        let now = Utc::now();
        Ok(self
            .service
            .delegations_to(subject)
            .await?
            .iter()
            .any(|delegation| delegation.applies_to(request, now)))
    }
}

impl std::fmt::Debug for ApprovalEndpoints {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ApprovalEndpoints").field("service", &self.service).finish_non_exhaustive()
    }
}

/// The approval routes, relative to `/api`. Mount them behind the auth middleware, as
/// [`ServerBuilder::with_approval_service`](crate::ServerBuilder::with_approval_service)
/// does.
pub fn approvals_router(endpoints: ApprovalEndpoints) -> Router {
    Router::new()
        .route("/approvals", get(inbox))
        .route("/approvals/delegations", post(create_delegation))
        .route("/approvals/delegations/{id}", delete(revoke_delegation))
        .route("/approvals/{id}", get(get_request))
        .route("/approvals/{id}/decide", post(decide))
        .route("/approvals/{id}/cancel", post(cancel))
        .with_state(endpoints)
}

/// Runs [`ApprovalService::tick`] every `interval` until the task is aborted, so
/// requests expire and escalate on time. Safe to run on every replica.
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use std::time::Duration;
/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
///
/// # async fn demo() {
/// let service = Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())));
/// let ticker = adk_server::approvals::spawn_approval_ticker(service, Duration::from_secs(30));
/// # ticker.abort();
/// # }
/// ```
pub fn spawn_approval_ticker(
    service: Arc<dyn ApprovalService>,
    interval: Duration,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut timer = tokio::time::interval(interval);
        timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        loop {
            timer.tick().await;
            match service.tick(Utc::now()).await {
                Ok(report) if report.expired.is_empty() && report.escalated.is_empty() => {}
                Ok(report) => tracing::info!(
                    approvals.expired = report.expired.len(),
                    approvals.escalated = report.escalated.len(),
                    "approval tick"
                ),
                Err(error) => tracing::warn!(error = %error, "approval tick failed"),
            }
        }
    })
}

fn problem(error: &AdkError) -> Response {
    let status =
        StatusCode::from_u16(error.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    (status, Json(error.to_problem_json())).into_response()
}

fn not_found(id: &str) -> Response {
    problem(&AdkError::new(
        ErrorComponent::Server,
        ErrorCategory::NotFound,
        "approval.not_found",
        format!("no approval request '{id}'"),
    ))
}

/// A request as shown to callers: without its fingerprint, which holds the raw
/// arguments, and with `showsCallArgs`, whether `argsRedacted` are the call's own, so a
/// client knows an edit that starts from them changes nothing else (spec 3.3 §7.2).
fn view(request: &ApprovalRequest) -> Value {
    let mut value = serde_json::to_value(request).unwrap_or(Value::Null);
    if let Some(object) = value.as_object_mut() {
        object.remove("fingerprint");
        object.insert("showsCallArgs".into(), Value::Bool(request.shows_call_args()));
    }
    value
}

/// `GET /api/approvals` query.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InboxParams {
    /// Comma-separated states; defaults to pending.
    #[serde(default)]
    pub state: Option<String>,
    /// List one of the caller's groups' queue instead of the caller's inbox.
    #[serde(default)]
    pub group: Option<String>,
    /// Only one application.
    #[serde(default)]
    pub app: Option<String>,
    /// Only requests of this user.
    #[serde(default)]
    pub user: Option<String>,
    /// Only one session: the session with this ID of `user` (the caller when `user` is
    /// unset) in `app`, which it needs (spec 3.3 §10 C1). It narrows the caller's inbox and
    /// never widens it.
    #[serde(default)]
    pub session: Option<String>,
    /// Page token.
    #[serde(default)]
    pub cursor: Option<String>,
    /// Page size, at most 200.
    #[serde(default)]
    pub limit: Option<usize>,
}

async fn inbox(
    State(endpoints): State<ApprovalEndpoints>,
    Extension(caller): Extension<Option<RequestContext>>,
    Query(params): Query<InboxParams>,
) -> Response {
    let caller_user = caller.as_ref().map(|context| context.user_id.clone());
    let (subject, groups) = match endpoints.caller(caller) {
        Ok(caller) => caller,
        Err(response) => return response,
    };
    if params.session.is_some() && params.app.is_none() {
        return problem(&AdkError::new(
            ErrorComponent::Server,
            ErrorCategory::InvalidInput,
            "approval.session_needs_app",
            "a session is named by its application, user and ID: pass `app` with `session`",
        ));
    }
    let mut states = Vec::new();
    for name in params.state.iter().flat_map(|states| states.split(',')) {
        match serde_json::from_value::<ApprovalState>(Value::String(name.trim().to_string())) {
            Ok(state) => states.push(state),
            Err(_) => {
                return problem(&AdkError::new(
                    ErrorComponent::Server,
                    ErrorCategory::InvalidInput,
                    "approval.invalid_state",
                    format!("unknown approval state '{name}'"),
                ));
            }
        }
    }
    let mut query = match &params.group {
        // A group's queue is visible only to its members.
        Some(group) if groups.contains(group) => InboxQuery::for_group(group.clone()),
        Some(group) => {
            return problem(&AdkError::new(
                ErrorComponent::Server,
                ErrorCategory::Forbidden,
                "approval.not_a_member",
                format!("the caller is not a member of '{group}'"),
            ));
        }
        None => InboxQuery::for_approver(subject, groups),
    }
    .with_states(states)
    .with_cursor(params.cursor)
    .with_limit(params.limit.unwrap_or(50).clamp(1, 200));
    if let Some(app) = params.app {
        query = query.with_app_name(app);
    }
    let user = match (&params.session, params.user) {
        (Some(_), None) => caller_user,
        (_, user) => user,
    };
    if let Some(user) = user {
        query = query.with_user_id(user);
    }
    if let Some(session) = params.session {
        query = query.with_session_id(session);
    }
    match endpoints.service.inbox(query).await {
        Ok(page) => Json(serde_json::json!({
            "items": page.items.iter().map(view).collect::<Vec<_>>(),
            "nextCursor": page.next_cursor,
        }))
        .into_response(),
        Err(error) => problem(&error),
    }
}

async fn get_request(
    State(endpoints): State<ApprovalEndpoints>,
    Extension(caller): Extension<Option<RequestContext>>,
    Path(id): Path<String>,
) -> Response {
    let (subject, groups) = match endpoints.caller(caller) {
        Ok(caller) => caller,
        Err(response) => return response,
    };
    match endpoints.service.get(&id).await {
        Ok(Some(request)) => match endpoints.may_see(&request, &subject, &groups).await {
            Ok(true) => Json(view(&request)).into_response(),
            Ok(false) => not_found(&id),
            Err(error) => problem(&error),
        },
        Ok(None) => not_found(&id),
        Err(error) => problem(&error),
    }
}

/// `POST /api/approvals/{id}/decide` body.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DecideBody {
    /// The version the caller read; a stale one answers `409`.
    pub expected_version: u64,
    /// What the caller does.
    pub action: ApprovalAction,
    /// Replacement arguments for `edit`.
    #[serde(default)]
    pub edited_args: Option<Value>,
    /// Rejection reason, or the text of `respond`.
    #[serde(default)]
    pub reason: Option<String>,
    /// Act under the delegation from this subject.
    #[serde(default)]
    pub via: Option<SubjectRef>,
}

async fn decide(
    State(endpoints): State<ApprovalEndpoints>,
    Extension(caller): Extension<Option<RequestContext>>,
    extensions: Extensions,
    Path(id): Path<String>,
    Json(body): Json<DecideBody>,
) -> Response {
    let context = caller.clone();
    let (subject, groups) = match endpoints.caller(caller) {
        Ok(caller) => caller,
        Err(response) => return response,
    };
    // The host's check sees the request as it is now; a request the caller may not see is
    // answered as the service answers it.
    let guarded = match (&endpoints.guard, &context) {
        (Some(guard), Some(context)) => match endpoints.service.get(&id).await {
            Ok(Some(request)) => {
                let call = DecideCall {
                    caller: context,
                    extensions: &extensions,
                    request: &request,
                    action: body.action,
                };
                if let Err(error) = guard.check(&call).await {
                    return problem(&error);
                }
                Some((guard.clone(), request))
            }
            Ok(None) => None,
            Err(error) => return problem(&error),
        },
        _ => None,
    };
    let mut decision = match body.action {
        ApprovalAction::Approve => ApprovalDecision::approve(subject),
        ApprovalAction::Edit => {
            ApprovalDecision::edit(subject, body.edited_args.unwrap_or(Value::Null))
        }
        ApprovalAction::Reject => {
            ApprovalDecision::reject(subject, body.reason.clone().unwrap_or_default())
        }
        ApprovalAction::Respond => {
            ApprovalDecision::respond(subject, body.reason.clone().unwrap_or_default())
        }
    }
    .with_groups(groups);
    if matches!(body.action, ApprovalAction::Edit) && decision.edited_args == Some(Value::Null) {
        decision.edited_args = None;
    }
    if matches!(body.action, ApprovalAction::Reject)
        && body.reason.as_deref().is_none_or(str::is_empty)
    {
        decision.reason = None;
    }
    if let Some(via) = body.via {
        decision = decision.via(via);
    }
    match endpoints.service.decide(&id, body.expected_version, decision).await {
        Ok(decided) => {
            if let (Some((guard, request)), Some(context)) = (&guarded, &context) {
                let call = DecideCall {
                    caller: context,
                    extensions: &extensions,
                    request,
                    action: body.action,
                };
                guard.decided(&call, &decided).await;
            }
            Json(view(&decided)).into_response()
        }
        Err(error) => problem(&error),
    }
}

/// `POST /api/approvals/{id}/cancel` body.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelBody {
    /// Why; reported to the model as part of the denial.
    #[serde(default)]
    pub reason: Option<String>,
}

async fn cancel(
    State(endpoints): State<ApprovalEndpoints>,
    Extension(caller): Extension<Option<RequestContext>>,
    Path(id): Path<String>,
    body: Option<Json<CancelBody>>,
) -> Response {
    let (subject, groups) = match endpoints.caller(caller) {
        Ok(caller) => caller,
        Err(response) => return response,
    };
    let request = match endpoints.service.get(&id).await {
        Ok(Some(request)) => request,
        Ok(None) => return not_found(&id),
        Err(error) => return problem(&error),
    };
    match endpoints.may_see(&request, &subject, &groups).await {
        Ok(true) => {}
        Ok(false) => return not_found(&id),
        Err(error) => return problem(&error),
    }
    let reason = body.and_then(|Json(body)| body.reason);
    match endpoints.service.cancel(&id, reason).await {
        Ok(request) => Json(view(&request)).into_response(),
        Err(error) => problem(&error),
    }
}

/// `POST /api/approvals/delegations` body.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DelegateBody {
    /// The delegate.
    pub to: SubjectRef,
    /// When the delegation starts; defaults to now.
    #[serde(default)]
    pub not_before: Option<DateTime<Utc>>,
    /// When it ends.
    pub not_after: DateTime<Utc>,
    /// Which requests it covers; defaults to all.
    #[serde(default)]
    pub scope: Option<DelegationScope>,
}

async fn create_delegation(
    State(endpoints): State<ApprovalEndpoints>,
    Extension(caller): Extension<Option<RequestContext>>,
    Json(body): Json<DelegateBody>,
) -> Response {
    let (subject, groups) = match endpoints.caller(caller) {
        Ok(caller) => caller,
        Err(response) => return response,
    };
    let window = DelegationWindow::new(body.not_before.unwrap_or_else(Utc::now), body.not_after);
    let delegation = ApprovalDelegation::new(subject, body.to, window)
        .with_from_groups(groups)
        .with_scope(body.scope.unwrap_or_default());
    match endpoints.service.delegate(delegation).await {
        Ok(delegation) => (StatusCode::CREATED, Json(delegation)).into_response(),
        Err(error) => problem(&error),
    }
}

/// `DELETE /api/approvals/delegations/{id}` query: the delegate, so the delegation can
/// be found.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RevokeParams {
    /// The delegate's kind.
    pub to_kind: SubjectKind,
    /// The delegate's ID.
    pub to_id: String,
}

async fn revoke_delegation(
    State(endpoints): State<ApprovalEndpoints>,
    Extension(caller): Extension<Option<RequestContext>>,
    Path(id): Path<String>,
    Query(params): Query<RevokeParams>,
) -> Response {
    let (subject, _) = match endpoints.caller(caller) {
        Ok(caller) => caller,
        Err(response) => return response,
    };
    let to = SubjectRef::new(params.to_kind, params.to_id);
    let held = match endpoints.service.delegations_to(&to).await {
        Ok(held) => held,
        Err(error) => return problem(&error),
    };
    let Some(delegation) = held.into_iter().find(|delegation| delegation.id == id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    if delegation.from != subject && delegation.to != subject {
        return StatusCode::NOT_FOUND.into_response();
    }
    match endpoints.service.revoke_delegation(&id).await {
        Ok(_) => StatusCode::NO_CONTENT.into_response(),
        Err(error) => problem(&error),
    }
}

// ---------------------------------------------------------------------------
// Webhook notifier
// ---------------------------------------------------------------------------

/// Delivers [`ApprovalNotification`]s as signed webhooks in the Standard Webhooks
/// format, through the shared [`WebhookDelivery`](adk_core::webhook_delivery::WebhookDelivery).
///
/// Each delivery is a `POST` of the notification as JSON with `webhook-id` (the
/// notification ID, stable across retries), `webhook-timestamp` (Unix seconds), and
/// `webhook-signature` ([`adk_core::webhook`]). Deliveries run in the background with
/// retries, exponential backoff, and jitter, so a slow receiver never holds up a decision;
/// the last failure is dead-lettered. The default egress policy allows HTTPS to public
/// addresses only; [`with_delivery`](Self::with_delivery) changes it.
///
/// # Example
///
/// ```rust
/// use adk_server::approvals::WebhookApprovalNotifier;
///
/// let notifier = WebhookApprovalNotifier::new(
///     "https://hooks.example.com/approvals",
///     "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw",
/// )?;
/// # Ok::<(), adk_core::AdkError>(())
/// ```
#[derive(Clone)]
pub struct WebhookApprovalNotifier {
    endpoint: adk_core::webhook_delivery::WebhookEndpoint,
    secret: adk_core::webhook::WebhookSecret,
    delivery: Arc<adk_core::webhook_delivery::WebhookDelivery>,
}

impl std::fmt::Debug for WebhookApprovalNotifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WebhookApprovalNotifier")
            .field("url", &self.endpoint.url)
            .finish_non_exhaustive()
    }
}

impl WebhookApprovalNotifier {
    /// Delivers to `url`, signing with `secret`: base64, optionally `whsec_`-prefixed.
    ///
    /// # Errors
    ///
    /// Returns `approval.webhook_secret` when the secret is not base64.
    pub fn new(url: impl Into<String>, secret: &str) -> Result<Self, AdkError> {
        let secret = adk_core::webhook::WebhookSecret::from_base64(secret).map_err(|e| {
            AdkError::new(
                ErrorComponent::Server,
                ErrorCategory::InvalidInput,
                "approval.webhook_secret",
                format!("{e}"),
            )
        })?;
        Ok(Self {
            endpoint: adk_core::webhook_delivery::WebhookEndpoint::new(url, secret.clone()),
            secret,
            delivery: Arc::new(adk_core::webhook_delivery::WebhookDelivery::new()),
        })
    }

    /// Delivers through `delivery`, for a custom retry policy, dead-letter sink, or egress
    /// policy (for example `EgressPolicy::allow_private_networks()` for an in-cluster receiver).
    pub fn with_delivery(mut self, delivery: adk_core::webhook_delivery::WebhookDelivery) -> Self {
        self.delivery = Arc::new(delivery);
        self
    }

    /// The `webhook-signature` header for `body` sent as `id` at `timestamp`.
    pub fn signature(&self, id: &str, timestamp: i64, body: &str) -> String {
        self.secret.signature(id, timestamp, body.as_bytes())
    }
}

#[async_trait::async_trait]
impl ApprovalNotifier for WebhookApprovalNotifier {
    async fn notify(&self, notification: &ApprovalNotification) -> adk_core::Result<()> {
        let message =
            adk_core::webhook_delivery::WebhookMessage::json(notification.id.clone(), notification)
                .map_err(|e| {
                    AdkError::new(
                        ErrorComponent::Server,
                        ErrorCategory::Internal,
                        "approval.webhook_encode",
                        format!("could not encode the approval notification: {e}"),
                    )
                })?;
        let delivery = Arc::clone(&self.delivery);
        let endpoint = self.endpoint.clone();
        tokio::spawn(async move {
            let report = delivery.deliver(&endpoint, &message).await;
            tracing::debug!(
                webhook.id = %message.id,
                delivered = report.is_delivered(),
                "approval notification delivery finished"
            );
        });
        Ok(())
    }
}