Skip to main content

adk_surface/web/
mod.rs

1//! The web home (spec 3.3 §5.1, §6; feature `web`): its HTTP API and its page.
2//!
3//! [`home`] serves the page — the React app built from `adk-surface/web`, embedded — at
4//! `/ui/` as root routes (§10 S1); mount it with `ServerBuilder::add_root_routes`.
5//!
6//! [`router`] serves the engine under `/surface`, relative to the `/api` prefix: mount it
7//! with `ServerBuilder::add_api_routes`, beside the kernel's control-plane routes, so the
8//! server's auth middleware puts the caller's `RequestContext` in every request. Every route
9//! needs that caller (`401` without one) and reads or acts only on the caller's own sessions
10//! and decisions (spec 3.3 §11 S-I8): anything else answers `404`. **Stop all** and **Resume
11//! all** are the exception: they freeze and unfreeze every run of the source, so a server
12//! that admits more than one person builds its engine with
13//! [`SurfaceEngineBuilder::stops_need`](crate::SurfaceEngineBuilder::stops_need), and a caller
14//! without that group (the `RequestContext`'s scopes) gets `403 surface.operator_only`
15//! (§11 S-I10).
16//!
17//! | Route (under `/api`) | Answer |
18//! |---|---|
19//! | `GET /surface/decisions` | [`DecisionsResponse`]: the caller's open decisions as cards; `?session=` for one session's; `?decidedSince=` adds those answered since, newest first |
20//! | `GET /surface/decisions/{id}` | [`DecisionCard`]: waiting, or decided with who, where and when |
21//! | `GET /surface/sessions/{session}/thread` | [`ThreadResponse`]: the session's entries, numbered by store position |
22//! | `GET /surface/sessions/{session}/feed` | Server-sent events: `entry` (with `id` = `seq`), `decisions`, `reset`, and `changed` for an entry already sent whose turn then failed; resumes after `Last-Event-ID` or `?after=` |
23//! | `GET /surface/sessions/{session}/queued` | [`QueuedResponse`]: what the caller typed while a decision of the session was open or a turn ran, not yet sent; a message the running turn holds is listed until the turn takes it |
24//! | `GET /surface/agents` | [`AgentsResponse`] |
25//! | `GET /surface/status` | [`StatusLine`]; `?session=` for that session's mode |
26//! | `GET /surface/briefing` | [`Briefing`] since `?since=` (default: the last 24 hours) |
27//! | `POST /surface/commands` | [`CommandRequest`] → [`CommandOutcome`]; `send` answers at once, and `steer` once the running turn took the message or handed it back |
28//! | `GET /surface/openapi.json` | The OpenAPI 3.1 document of these routes |
29//! | `POST /surface/decisions/{id}/take-over` | [`TakeOverRequest`] → [`CommandOutcome`]; mounted by [`take_over_router`] beside a harness that takes over |
30//! | `/surface/workflow/…` | The Runs tab's routes (feature `workflow`), mounted by `workflow::router` beside these |
31//! | `GET /surface/genui/capabilities`, `GET /surface/genui/sessions/{session}/forms` | Agent-drawn UI (spec 3.3 §6.1 `genui`): mounted by [`genui::router`](mod@genui) with feature `genui` |
32//!
33//! Reads take `?surface=` (`web`, `terminal`, `phone`, `tray`, `chat`, `voice`) so a card
34//! lists the answers that surface may give (§7.2). A declared surface or origin can only
35//! narrow what a caller may decide. What widens it is set by the server, never the client:
36//! [`PRESENCE_METADATA_KEY`] (the person confirmed it is them, which high-risk approvals on the
37//! web home and the phone need) and [`PAIRED_LOCAL_METADATA_KEY`] (a paired local terminal),
38//! read from the `RequestContext` metadata the server's extractor builds. Errors are problem
39//! documents with the engine's `surface.*` code.
40//!
41//! A paired device's context (a device token, spec 3.3 §10 K2) is never the web home and never
42//! a paired local terminal, whatever it declares: it reads as the terminal row, typed, and
43//! carries its device to every audit record. `POST /surface/commands` answers it
44//! `403 surface.not_here`. **Resume all** and resuming an agent are the web home's only when
45//! the request comes from the home's own page — a browser's same-origin request
46//! (`Sec-Fetch-Site: same-origin`) — and otherwise read as a terminal elsewhere, which may not
47//! resume (`403 surface.not_here`, spec 3.3 §11 S-I10). A `decide` declaring the voice surface or origin answers
48//! `400 surface.invalid`, because a spoken answer reaches the engine through the voice
49//! surface; `cancelAnswer` stays open (§5.6, §7.2).
50
51mod devices;
52pub mod genui;
53mod home;
54mod openapi;
55pub(crate) mod phone;
56mod take_over;
57#[cfg(feature = "verb-ui")]
58pub mod verbs;
59mod vocabulary;
60#[cfg(feature = "website")]
61pub mod website;
62#[cfg(feature = "workflow")]
63pub mod workflow;
64
65use std::time::Duration;
66
67use adk_core::{AdkError, RequestContext};
68use axum::extract::{DefaultBodyLimit, Path, Query, State};
69use axum::http::{HeaderMap, StatusCode};
70use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
71use axum::response::{IntoResponse, Response};
72use axum::routing::{get, post, put};
73use axum::{Extension, Json, Router};
74use chrono::{DateTime, Utc};
75use futures::{FutureExt as _, StreamExt};
76use schemars::JsonSchema;
77use serde::{Deserialize, Serialize};
78
79pub use devices::{device_scope_for, devices_router, router_with_devices};
80#[cfg(feature = "genui-apps")]
81pub use home::home_with_apps_origin;
82pub use home::{HOME_PATH, home};
83pub use openapi::{openapi, typescript};
84pub use phone::{
85    AgentConfirmOptionsRequest, AnswerRequest, ComputerPasskey, ConfirmOptions,
86    ConfirmOptionsRequest, ConfirmRequest, DeliveriesResponse, Delivery, PasskeyOptions,
87    PasskeyRegistration, PhoneDevice, PhoneDevicesResponse, PhoneInfo, PushKeys,
88    PushReceivedRequest, PushSubscriptionRequest, QrRequest, StopRequest,
89};
90pub use take_over::{TakeOverRequest, take_over_router};
91pub use vocabulary::words_typescript;
92
93use crate::engine::{Command, CommandOutcome, FeedFrame, SurfaceEngine};
94use crate::error::SurfaceError;
95use crate::model::{AgentRef, AgentRow, Briefing, DecisionCard, FeedEntry, StatusLine};
96use crate::origin::{Caller, Origin, SurfaceKind};
97
98/// The largest command body: a message's images, each at its largest in base64, and room for
99/// the rest of the command.
100const COMMAND_BODY_MAX: usize =
101    crate::images::MAX_IMAGES * (crate::images::MAX_IMAGE_BYTES / 3 * 4 + 4) + 256 * 1024;
102
103/// The route paths, relative to the `/api` prefix (spec 3.3 §6).
104pub mod paths {
105    /// Every route's prefix.
106    pub const PREFIX: &str = "/surface";
107    /// `GET`: open decisions.
108    pub const DECISIONS: &str = "/surface/decisions";
109    /// `GET`: one decision.
110    pub const DECISION: &str = "/surface/decisions/{id}";
111    /// `GET`: a session's thread.
112    pub const THREAD: &str = "/surface/sessions/{session}/thread";
113    /// `GET`: a session's feed, as server-sent events.
114    pub const FEED: &str = "/surface/sessions/{session}/feed";
115    /// `GET`: the input queued behind a session's open decisions or its running turn.
116    pub const QUEUED: &str = "/surface/sessions/{session}/queued";
117    /// `POST`: the secret a person typed for a take-over decision.
118    pub const TAKE_OVER: &str = "/surface/decisions/{id}/take-over";
119    /// `GET`: one of the images a decision holds as evidence, its digest checked, for a viewer
120    /// who may see the decision (spec 3.7 §8.2, §8.3).
121    pub const EVIDENCE: &str = "/surface/decisions/{id}/evidence/{index}";
122    /// `GET`: the annotated viewer of one image of a session — a digest, or the name of an
123    /// image the session holds — with every answer the vision tools gave for it (spec 3.7
124    /// §8.2, X12).
125    pub const VISION_VIEW: &str = "/surface/vision/{session}/images/{image}/view";
126    /// `GET`: one image of a session, its digest checked, for the session's owner (spec 3.7
127    /// §8.3).
128    pub const VISION_IMAGE: &str = "/surface/vision/{session}/images/{image}";
129    /// `GET`: one answer's `RegionSet` as a file (board choice V14).
130    pub const VISION_REGIONS: &str = "/surface/vision/{session}/answers/{answer}/regions";
131    /// `POST`: save a labelled example from an answer (board choice V13).
132    pub const VISION_EXAMPLES: &str = "/surface/vision/{session}/examples";
133    /// `GET`: every camera the caller may see, as a grid (spec 3.7 §8.2, board choice C8).
134    pub const CAMERAS: &str = "/surface/cameras";
135    /// `GET`: one camera, watched large (board choice C1).
136    pub const CAMERA: &str = "/surface/cameras/{camera}";
137    /// `GET`: a frame the hub holds in memory, its digest checked; never cached.
138    pub const CAMERA_FRAME: &str = "/surface/cameras/{camera}/frames/{frame}";
139    /// `GET`: a camera's picture after each frame, as server-sent events.
140    pub const CAMERA_FEED: &str = "/surface/cameras/{camera}/feed";
141    /// `POST`: one frame this screen's camera captured, for a camera that takes them.
142    pub const CAMERA_FRAMES: &str = "/surface/cameras/{camera}/frames";
143    /// `POST`: switch a camera on (board choice C2).
144    pub const CAMERA_ON: &str = "/surface/cameras/{camera}/on";
145    /// `POST`: switch a camera off: its frames are dropped on the server from then on.
146    pub const CAMERA_OFF: &str = "/surface/cameras/{camera}/off";
147    /// `POST`: end a camera's stream.
148    pub const CAMERA_STOP: &str = "/surface/cameras/{camera}/stop";
149    /// `POST`: try a lost camera again (board choice C6).
150    pub const CAMERA_RETRY: &str = "/surface/cameras/{camera}/retry";
151    /// `PUT`: change a zone (board choice C12).
152    pub const CAMERA_ZONE: &str = "/surface/cameras/{camera}/zones/{zone}";
153    /// `POST`: freeze the frame on screen for a card; held in memory, never written.
154    pub const CAMERA_FREEZE: &str = "/surface/cameras/{camera}/freeze";
155    /// `POST`: raise a card from a frozen frame (board choice C11).
156    pub const CAMERA_CARDS: &str = "/surface/cameras/{camera}/cards";
157    /// `GET`: the roster.
158    pub const AGENTS: &str = "/surface/agents";
159    /// `GET`: one agent a person added (spec 3.3 §5.7).
160    pub const AGENT: &str = "/surface/agents/{id}";
161    /// `GET`: how the caller answered since a time (spec 3.3 §5.1 "How you answered").
162    pub const ANSWERS: &str = "/surface/answers";
163    /// `GET`: an agent's threads, newest first (spec 3.3 §5.1 "Thread history").
164    pub const AGENT_THREADS: &str = "/surface/agents/{id}/threads";
165    /// `GET`: what a person may choose for an agent (spec 3.3 §5.7).
166    pub const AGENT_CHOICES: &str = "/surface/agents/choices";
167    /// `POST`: **Here is what Finance can do** — the preview of a change (spec 3.3 §5.7).
168    pub const AGENT_PREVIEW: &str = "/surface/agents/preview";
169    /// `GET`: the status line.
170    pub const STATUS: &str = "/surface/status";
171    /// `GET`: "While you were away".
172    pub const BRIEFING: &str = "/surface/briefing";
173    /// `POST`: a command.
174    pub const COMMANDS: &str = "/surface/commands";
175    /// `GET`: the OpenAPI document.
176    pub const OPENAPI: &str = "/surface/openapi.json";
177    /// `POST`: a paired device's answer (spec 3.3 §10 K2).
178    pub const ANSWER: &str = "/surface/decisions/{id}/answer";
179    /// `POST`: a paired device's Stop all (spec 3.3 §11 S-I10).
180    pub const STOP: &str = "/surface/stop";
181    /// `POST`: starts "Confirm it's you" for one answer (spec 3.3 §8.2).
182    pub const CONFIRM_OPTIONS: &str = "/surface/decisions/{id}/confirm/options";
183    /// `POST`: the passkey's assertion for the bound answer (spec 3.3 §8.2).
184    pub const CONFIRM: &str = "/surface/decisions/{id}/confirm";
185    /// `POST`: starts "Confirm it's you" for one change that adds an agent or lets one do more
186    /// at high risk (spec 3.3 §7.2).
187    pub const AGENT_CONFIRM_OPTIONS: &str = "/surface/agents/confirm/options";
188    /// `POST`: the passkey's assertion for the bound agent change, then made with presence.
189    pub const AGENT_CONFIRM: &str = "/surface/agents/confirm";
190    /// `GET`: what the phone needs to subscribe and to confirm it is you (spec 3.3 §5.4).
191    pub const PHONE: &str = "/surface/phone";
192    /// `PUT`, `DELETE`: the phone's push subscription.
193    pub const PHONE_PUSH: &str = "/surface/phone/push";
194    /// `POST`: the phone received a wake-up.
195    pub const PHONE_PUSH_RECEIVED: &str = "/surface/phone/push/received";
196    /// `GET`: the latest acknowledged wake-ups, for the operator.
197    pub const PHONE_PUSH_DELIVERIES: &str = "/surface/phone/push/deliveries";
198    /// `POST`: starts setting up a passkey.
199    pub const PHONE_PASSKEY_OPTIONS: &str = "/surface/phone/passkey/options";
200    /// `POST`: finishes setting up a passkey.
201    pub const PHONE_PASSKEY: &str = "/surface/phone/passkey";
202    /// `DELETE`: removes a computer passkey of the caller.
203    pub const PHONE_PASSKEY_ONE: &str = "/surface/phone/passkey/{id}";
204    /// `POST`: a pairing link as a QR code, for the operator.
205    pub const PHONE_QR: &str = "/surface/phone/qr";
206    /// `GET`: the paired devices' passkeys and push, for the operator.
207    pub const PHONE_DEVICES: &str = "/surface/phone/devices";
208}
209
210/// `RequestContext` metadata key the server's extractor sets to `confirmed` when the person
211/// confirmed it is them for this request, by passkey or device check (spec 3.3 §7.2, §8.2).
212pub const PRESENCE_METADATA_KEY: &str = "surface.presence";
213
214/// `RequestContext` metadata key set to `true` for a paired local terminal (spec 3.3 §7.2,
215/// §11 S-I10).
216pub const PAIRED_LOCAL_METADATA_KEY: &str = "surface.pairedLocal";
217
218/// The engine's routes, relative to `/api` (spec 3.3 §6).
219///
220/// **Stop all** and **Resume all** act on every run of the engine's source: build the engine
221/// with [`stops_need`](crate::SurfaceEngineBuilder::stops_need) so only the operator gives them
222/// (spec 3.3 §11 S-I10).
223///
224/// # Example
225///
226/// ```rust,no_run
227/// use std::sync::Arc;
228/// use adk_surface::{LocalSource, SurfaceEngine};
229///
230/// # fn example(source: LocalSource, builder: adk_server::ServerBuilder) {
231/// let engine = SurfaceEngine::builder(Arc::new(source)).stops_need("operator").build();
232/// let builder = builder.add_api_routes(adk_surface::web::router(engine));
233/// # let _ = builder;
234/// # }
235/// ```
236pub fn router(engine: SurfaceEngine) -> Router {
237    Router::new()
238        .route(paths::DECISIONS, get(decisions))
239        .route(paths::DECISION, get(decision))
240        .route(paths::EVIDENCE, get(evidence))
241        .route(paths::VISION_VIEW, get(vision_view))
242        .route(paths::VISION_IMAGE, get(vision_image))
243        .route(paths::VISION_REGIONS, get(vision_regions))
244        .route(paths::VISION_EXAMPLES, post(vision_example))
245        .route(paths::CAMERAS, get(cameras))
246        .route(paths::CAMERA, get(camera))
247        .route(paths::CAMERA_FRAME, get(camera_frame))
248        .route(paths::CAMERA_FEED, get(camera_feed))
249        .route(
250            paths::CAMERA_FRAMES,
251            post(camera_frames).layer(DefaultBodyLimit::max(crate::camera::MAX_SENT_FRAME_BYTES)),
252        )
253        .route(paths::CAMERA_ON, post(camera_on))
254        .route(paths::CAMERA_OFF, post(camera_off))
255        .route(paths::CAMERA_STOP, post(camera_stop))
256        .route(paths::CAMERA_RETRY, post(camera_retry))
257        .route(paths::CAMERA_ZONE, put(camera_zone))
258        .route(paths::CAMERA_FREEZE, post(camera_freeze))
259        .route(paths::CAMERA_CARDS, post(camera_card))
260        .route(paths::THREAD, get(thread))
261        .route(paths::FEED, get(feed))
262        .route(paths::QUEUED, get(queued))
263        .route(paths::AGENTS, get(agents))
264        .route(paths::AGENT_CHOICES, get(agent_choices))
265        .route(paths::AGENT_PREVIEW, post(agent_preview))
266        .route(paths::AGENT, get(agent))
267        .route(paths::AGENT_THREADS, get(agent_threads))
268        .route(paths::ANSWERS, get(answers))
269        .route(paths::STATUS, get(status))
270        .route(paths::BRIEFING, get(briefing))
271        // A message may carry images (spec 3.3 §5.1): room for each at its largest, base64.
272        .route(paths::COMMANDS, post(command).layer(DefaultBodyLimit::max(COMMAND_BODY_MAX)))
273        .route(paths::OPENAPI, get(openapi_document))
274        .with_state(engine)
275}
276
277/// `GET /surface/decisions` answer.
278#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
279#[serde(rename_all = "camelCase")]
280pub struct DecisionsResponse {
281    /// The open decisions, oldest first.
282    pub decisions: Vec<DecisionCard>,
283}
284
285/// `GET /surface/sessions/{session}/thread` answer.
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
287#[serde(rename_all = "camelCase")]
288pub struct ThreadResponse {
289    /// The session.
290    pub session_id: String,
291    /// Every event of the session store, numbered by position from 1.
292    pub entries: Vec<FeedEntry>,
293}
294
295/// `GET /surface/sessions/{session}/queued` answer (spec 3.3 §7.4 rule 2, S-I4).
296#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
297#[serde(rename_all = "camelCase")]
298pub struct QueuedResponse {
299    /// The session.
300    pub session_id: String,
301    /// What the caller typed while a decision of the session was open or a turn ran, oldest
302    /// first; each is sent once the session is free, or leaves the list when the running turn
303    /// takes it.
304    pub queued: Vec<String>,
305}
306
307/// `GET /surface/agents` answer.
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
309#[serde(rename_all = "camelCase")]
310pub struct AgentsResponse {
311    /// The caller's agents.
312    pub agents: Vec<AgentRow>,
313    /// The agent a message goes to when the person names none: the tray's "Ask Finance"
314    /// (spec 3.3 §5.5). Absent when the source has no single primary agent.
315    #[serde(default, skip_serializing_if = "Option::is_none")]
316    pub primary: Option<AgentRef>,
317    /// The roster ends with **New agent**: the source keeps agents a person adds and the
318    /// caller may add one here (spec 3.3 §5.7). Absent when false.
319    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
320    pub can_add: bool,
321    /// The agents the person removed, whose threads stay readable through "Removed agents"
322    /// at the roster's foot (spec 3.3 §5.7). Absent when none.
323    #[serde(default, skip_serializing_if = "Vec::is_empty")]
324    pub removed: Vec<crate::agents::RemovedAgent>,
325}
326
327/// `POST /surface/commands` body: the command, the surface it was given on and how.
328///
329/// # Example
330///
331/// ```rust
332/// use adk_surface::web::CommandRequest;
333///
334/// let request: CommandRequest = serde_json::from_value(serde_json::json!({
335///     "surface": "phone",
336///     "origin": { "kind": "touch" },
337///     "command": { "type": "stopAll" },
338/// }))
339/// .unwrap();
340/// assert_eq!(request.surface, adk_surface::SurfaceKind::Phone);
341/// ```
342#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
343#[serde(rename_all = "camelCase")]
344pub struct CommandRequest {
345    /// The surface; defaults to the web home.
346    #[serde(default = "web")]
347    pub surface: SurfaceKind,
348    /// How the input was given.
349    pub origin: Origin,
350    /// The command.
351    pub command: Command,
352}
353
354fn web() -> SurfaceKind {
355    SurfaceKind::Web
356}
357
358/// Query of the reads: the surface the answers are computed for.
359#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
360#[serde(rename_all = "camelCase")]
361pub struct SurfaceQuery {
362    /// The surface; defaults to the web home.
363    #[serde(default)]
364    pub surface: Option<SurfaceKind>,
365    /// `GET /surface/status`: the session whose mode to show; `GET /surface/decisions`: only
366    /// that session's decisions.
367    #[serde(default)]
368    pub session: Option<String>,
369    /// `GET /surface/briefing` and `GET /surface/answers`: since when.
370    #[serde(default)]
371    pub since: Option<DateTime<Utc>>,
372    /// `GET .../feed`: resume after this `seq` when no `Last-Event-ID` is sent.
373    #[serde(default)]
374    pub after: Option<u64>,
375    /// `GET /surface/decisions`: also the decisions answered or ended since then, newest
376    /// first, after the open ones (spec 3.3 §5.4).
377    #[serde(default)]
378    pub decided_since: Option<DateTime<Utc>>,
379}
380
381pub(crate) type Context = Option<Extension<Option<RequestContext>>>;
382
383/// No authenticated caller: the route answers `401`.
384pub(crate) struct Unauthenticated;
385
386pub(crate) fn unauthenticated() -> Response {
387    problem(&AdkError::new(
388        adk_core::ErrorComponent::Server,
389        adk_core::ErrorCategory::Unauthorized,
390        "surface.unauthenticated",
391        "the surface API needs an authenticated caller; mount it with \
392         ServerBuilder::add_api_routes behind a RequestContextExtractor",
393    ))
394}
395
396/// The paired device a context authenticated as, when it carries a device token's metadata
397/// (spec 3.3 §10 K2).
398pub(crate) fn device_of(context: &RequestContext) -> Option<&String> {
399    context.metadata.get(adk_kernel::pairing::DEVICE_ID_METADATA)
400}
401
402/// The kind of a paired device's context — `phone`, `terminal` or `tray` — which the issuer
403/// of its pairing code set; `None` for a device paired without one, a remote terminal.
404pub(crate) fn device_kind(context: &RequestContext) -> Option<&str> {
405    context.metadata.get(adk_kernel::pairing::DEVICE_KIND_METADATA).map(String::as_str)
406}
407
408/// The caller from the server's authentication; the client chooses only the surface and the
409/// origin, which can narrow what it may decide and never widen it.
410///
411/// A device token's context is never the web home and never a paired local terminal, whatever
412/// the query or body declares: its kind, which the issuer of its pairing code set, picks the
413/// row — a phone by touch, a tray by pointer, anything else a terminal by keyboard — and the
414/// caller carries its device (spec 3.3 §7.2, §11 S-I10). Its presence comes only from a route
415/// that checked it, never from metadata.
416pub(crate) fn caller(
417    context: Context,
418    surface: SurfaceKind,
419    origin: Option<Origin>,
420) -> Result<Caller, Unauthenticated> {
421    let Some(Extension(Some(context))) = context else {
422        return Err(Unauthenticated);
423    };
424    if let Some(device) = device_of(&context) {
425        let (surface, origin) = match device_kind(&context) {
426            Some("phone") => (SurfaceKind::Phone, Origin::Touch),
427            Some("tray") => (SurfaceKind::Tray, Origin::Pointer),
428            _ => (SurfaceKind::Terminal, Origin::Keyboard),
429        };
430        return Ok(Caller::human(context.user_id.clone(), surface, origin)
431            .with_groups(context.scopes.clone())
432            .with_device(device.clone()));
433    }
434    let origin = origin.unwrap_or(match surface {
435        SurfaceKind::Web | SurfaceKind::Tray => Origin::Pointer,
436        SurfaceKind::Phone => Origin::Touch,
437        SurfaceKind::Terminal => Origin::Keyboard,
438        SurfaceKind::Voice => Origin::Voice,
439        SurfaceKind::Chat => Origin::Chat { channel: "chat".to_string() },
440    });
441    let mut caller =
442        Caller::human(context.user_id.clone(), surface, origin).with_groups(context.scopes.clone());
443    if context.metadata.get(PRESENCE_METADATA_KEY).map(String::as_str) == Some("confirmed") {
444        caller = caller.with_presence_confirmed();
445    }
446    if context.metadata.get(PAIRED_LOCAL_METADATA_KEY).map(String::as_str) == Some("true") {
447        caller = caller.with_paired_local();
448    }
449    Ok(caller)
450}
451
452pub(crate) fn problem(error: &AdkError) -> Response {
453    let status =
454        StatusCode::from_u16(error.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
455    (status, Json(error.to_problem_json())).into_response()
456}
457
458pub(crate) fn failed(error: SurfaceError) -> Response {
459    problem(&AdkError::from(error))
460}
461
462macro_rules! try_or_respond {
463    ($result:expr) => {
464        match $result {
465            Ok(value) => value,
466            Err(Unauthenticated) => return unauthenticated(),
467        }
468    };
469}
470
471async fn decisions(
472    State(engine): State<SurfaceEngine>,
473    context: Context,
474    Query(query): Query<SurfaceQuery>,
475) -> Response {
476    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
477    let decisions = match &query.session {
478        Some(session) => engine.session_decisions(&caller, session).await,
479        None => engine.decisions(&caller).await,
480    };
481    let decisions = match (decisions, query.decided_since) {
482        (Ok(mut open), Some(since)) => engine.decided_since(&caller, since).await.map(|decided| {
483            open.extend(decided);
484            open
485        }),
486        (decisions, _) => decisions,
487    };
488    match decisions {
489        Ok(decisions) => Json(DecisionsResponse { decisions }).into_response(),
490        Err(error) => failed(error),
491    }
492}
493
494async fn decision(
495    State(engine): State<SurfaceEngine>,
496    context: Context,
497    Path(id): Path<String>,
498    Query(query): Query<SurfaceQuery>,
499) -> Response {
500    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
501    match engine.decision(&caller, &id).await {
502        Ok(card) => Json(card).into_response(),
503        Err(error) => failed(error),
504    }
505}
506
507/// An image a decision holds as evidence, for a viewer who may see the decision: the exact
508/// bytes whose digest the card shows, never cached and never sniffed (spec 3.7 §8.2).
509async fn evidence(
510    State(engine): State<SurfaceEngine>,
511    context: Context,
512    Path((id, index)): Path<(String, usize)>,
513    Query(query): Query<SurfaceQuery>,
514) -> Response {
515    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
516    match engine.evidence_image(&caller, &id, index).await {
517        Ok(image) => image_response(image),
518        Err(error) => failed(error),
519    }
520}
521
522/// `GET /surface/vision/{session}/images/{image}/view` query.
523#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
524#[serde(rename_all = "camelCase")]
525pub struct ViewerQuery {
526    /// The surface asking; defaults to the web home.
527    #[serde(default)]
528    pub surface: Option<SurfaceKind>,
529    /// The answer to show, by its call; the newest otherwise.
530    #[serde(default)]
531    pub answer: Option<String>,
532    /// A second answer to compare with it.
533    #[serde(default)]
534    pub compare: Option<String>,
535}
536
537/// `GET /surface/vision/{session}/answers/{answer}/regions` query.
538#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
539#[serde(rename_all = "camelCase")]
540pub struct RegionsQuery {
541    /// The surface asking; defaults to the web home.
542    #[serde(default)]
543    pub surface: Option<SurfaceKind>,
544    /// A second answer: both `RegionSet`s, in an array (board choice V14).
545    #[serde(default)]
546    pub with: Option<String>,
547}
548
549/// The annotated viewer of one image (spec 3.7 §8.2, X12), for the session's owner.
550async fn vision_view(
551    State(engine): State<SurfaceEngine>,
552    context: Context,
553    Path((session, image)): Path<(String, String)>,
554    Query(query): Query<ViewerQuery>,
555) -> Response {
556    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
557    match engine
558        .viewer(&caller, &session, &image, query.answer.as_deref(), query.compare.as_deref())
559        .await
560    {
561        Ok(view) => Json(view).into_response(),
562        Err(error) => failed(error),
563    }
564}
565
566/// One image of a session, for the session's owner: the exact bytes whose digest the viewer
567/// shows, never cached and never sniffed (spec 3.7 §8.3).
568async fn vision_image(
569    State(engine): State<SurfaceEngine>,
570    context: Context,
571    Path((session, image)): Path<(String, String)>,
572    Query(query): Query<SurfaceQuery>,
573) -> Response {
574    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
575    match engine.viewer_image(&caller, &session, &image).await {
576        Ok(image) => image_response(image),
577        Err(error) => failed(error),
578    }
579}
580
581/// An image's bytes with the headers every evidence and viewer image is served with.
582fn image_response(image: crate::evidence::EvidenceBytes) -> Response {
583    let mime = match image.mime_type.as_str() {
584        "image/png" | "image/jpeg" | "image/webp" | "image/gif" => image.mime_type,
585        _ => "application/octet-stream".to_string(),
586    };
587    (
588        [
589            (axum::http::header::CONTENT_TYPE, mime),
590            (axum::http::header::CACHE_CONTROL, "private, no-store".to_string()),
591            (axum::http::header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
592        ],
593        image.bytes,
594    )
595        .into_response()
596}
597
598/// One answer's `RegionSet` as a file to save (board choice V14).
599async fn vision_regions(
600    State(engine): State<SurfaceEngine>,
601    context: Context,
602    Path((session, answer)): Path<(String, String)>,
603    Query(query): Query<RegionsQuery>,
604) -> Response {
605    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
606    match engine.viewer_export(&caller, &session, &answer, query.with.as_deref()).await {
607        Ok(set) => {
608            let safe: String = answer
609                .chars()
610                .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
611                .collect();
612            let name = if query.with.is_some() {
613                format!("{safe}-compared.regions.json")
614            } else {
615                format!("{safe}.regions.json")
616            };
617            (
618                [
619                    (axum::http::header::CACHE_CONTROL, "private, no-store".to_string()),
620                    (
621                        axum::http::header::CONTENT_DISPOSITION,
622                        format!("attachment; filename=\"{name}\""),
623                    ),
624                ],
625                Json(set),
626            )
627                .into_response()
628        }
629        Err(error) => failed(error),
630    }
631}
632
633/// Saves a labelled example from an answer (board choice V13). A paired device reads the
634/// viewer and saves nothing: the phone is read-only (board choice V15).
635async fn vision_example(
636    State(engine): State<SurfaceEngine>,
637    context: Context,
638    Path(session): Path<String>,
639    Json(example): Json<crate::viewer::LabelledExample>,
640) -> Response {
641    if let Some(Extension(Some(context))) = &context
642        && device_of(context).is_some()
643    {
644        return failed(SurfaceError::NotHere(
645            "a phone shows the viewer read-only; save examples on a computer".into(),
646        ));
647    }
648    let caller = try_or_respond!(caller(context, SurfaceKind::Web, None));
649    match engine.save_example(&caller, &session, &example).await {
650        Ok(saved) => Json(saved).into_response(),
651        Err(error) => failed(error),
652    }
653}
654
655/// Every camera the caller may see (spec 3.7 §8.2, board choice C8).
656async fn cameras(
657    State(engine): State<SurfaceEngine>,
658    context: Context,
659    Query(query): Query<SurfaceQuery>,
660) -> Response {
661    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
662    match engine.cameras_view(&caller).await {
663        Ok(view) => Json(view).into_response(),
664        Err(error) => failed(error),
665    }
666}
667
668/// One camera, watched large (board choice C1).
669async fn camera(
670    State(engine): State<SurfaceEngine>,
671    context: Context,
672    Path(camera): Path<String>,
673    Query(query): Query<SurfaceQuery>,
674) -> Response {
675    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
676    match engine.camera_view(&caller, &camera).await {
677        Ok(view) => Json(view).into_response(),
678        Err(error) => failed(error),
679    }
680}
681
682/// A frame the hub holds in memory: the exact bytes whose digest the picture names, never cached
683/// and never sniffed. A camera that is off holds none.
684async fn camera_frame(
685    State(engine): State<SurfaceEngine>,
686    context: Context,
687    Path((camera, frame)): Path<(String, String)>,
688    Query(query): Query<SurfaceQuery>,
689) -> Response {
690    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
691    match engine.camera_frame(&caller, &camera, &frame).await {
692        Ok(image) => image_response(image),
693        Err(error) => failed(error),
694    }
695}
696
697/// A camera's picture after each frame (`frame`, a [`StageView`](crate::camera::StageView)) and
698/// a note when anything else changed (`changed`), as server-sent events.
699async fn camera_feed(
700    State(engine): State<SurfaceEngine>,
701    context: Context,
702    ends: Option<Extension<devices::DeviceEnds>>,
703    Path(camera): Path<String>,
704    Query(query): Query<SurfaceQuery>,
705) -> Response {
706    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
707    // Refuse a camera the caller may not see before the stream starts (S-I8).
708    if let Err(error) = engine.camera_view(&caller, &camera).await {
709        return failed(error);
710    }
711    let Some(hub) = engine.camera_hub() else {
712        return failed(SurfaceError::unsupported("the live camera surface"));
713    };
714    let device_ends = match (ends, caller.device.clone()) {
715        (Some(Extension(devices::DeviceEnds(pairing))), Some(device)) => {
716            pairing.until_device_ends(device).boxed()
717        }
718        _ => futures::future::pending().boxed(),
719    };
720    let updates = camera_updates(hub.subscribe());
721    let frames = updates
722        .filter(move |update| futures::future::ready(update.camera() == camera))
723        .then(move |update| {
724            let engine = engine.clone();
725            let caller = caller.clone();
726            async move {
727                let event = match update {
728                    crate::camera::CameraUpdate::Frame { camera, .. } => {
729                        match engine.camera_stage_after_check(&caller, &camera).await {
730                            Ok(stage) => SseEvent::default().event("frame").json_data(&stage),
731                            Err(error) => SseEvent::default()
732                                .event("error")
733                                .json_data(AdkError::from(error).to_problem_json()),
734                        }
735                    }
736                    crate::camera::CameraUpdate::Changed { .. } => {
737                        SseEvent::default().event("changed").json_data(serde_json::json!({}))
738                    }
739                };
740                Ok::<_, std::convert::Infallible>(event.unwrap_or_else(|_| {
741                    SseEvent::default().comment("a frame could not be encoded")
742                }))
743            }
744        })
745        .take_until(device_ends);
746    Sse::new(frames).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))).into_response()
747}
748
749/// Every update of the hub, a slow reader skipping what it missed.
750fn camera_updates(
751    updates: tokio::sync::broadcast::Receiver<crate::camera::CameraUpdate>,
752) -> impl futures::Stream<Item = crate::camera::CameraUpdate> + Send {
753    futures::stream::unfold(updates, |mut updates| async move {
754        loop {
755            match updates.recv().await {
756                Ok(update) => return Some((update, updates)),
757                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
758                Err(tokio::sync::broadcast::error::RecvError::Closed) => return None,
759            }
760        }
761    })
762}
763
764/// One frame this screen's camera captured, its type from `Content-Type`: handed to the camera's
765/// pipeline through the server's gate, or dropped with the reason while the camera is off.
766async fn camera_frames(
767    State(engine): State<SurfaceEngine>,
768    context: Context,
769    headers: HeaderMap,
770    Path(camera): Path<String>,
771    Query(query): Query<SurfaceQuery>,
772    body: axum::body::Bytes,
773) -> Response {
774    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
775    let mime_type = headers
776        .get(axum::http::header::CONTENT_TYPE)
777        .and_then(|value| value.to_str().ok())
778        .unwrap_or_default();
779    match engine.send_camera_frame(&caller, &camera, mime_type, body.to_vec()).await {
780        Ok(taken) => Json(taken).into_response(),
781        Err(error) => failed(error),
782    }
783}
784
785/// Switches a camera on.
786async fn camera_on(
787    State(engine): State<SurfaceEngine>,
788    context: Context,
789    Path(camera): Path<String>,
790    Query(query): Query<SurfaceQuery>,
791) -> Response {
792    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
793    match engine.switch_camera(&caller, &camera, true).await {
794        Ok(view) => Json(view).into_response(),
795        Err(error) => failed(error),
796    }
797}
798
799/// Switches a camera off: the server drops its frames from then on (spec 3.7 §8.2).
800async fn camera_off(
801    State(engine): State<SurfaceEngine>,
802    context: Context,
803    Path(camera): Path<String>,
804    Query(query): Query<SurfaceQuery>,
805) -> Response {
806    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
807    match engine.switch_camera(&caller, &camera, false).await {
808        Ok(view) => Json(view).into_response(),
809        Err(error) => failed(error),
810    }
811}
812
813/// Ends a camera's stream.
814async fn camera_stop(
815    State(engine): State<SurfaceEngine>,
816    context: Context,
817    Path(camera): Path<String>,
818    Query(query): Query<SurfaceQuery>,
819) -> Response {
820    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
821    match engine.stop_camera(&caller, &camera).await {
822        Ok(view) => Json(view).into_response(),
823        Err(error) => failed(error),
824    }
825}
826
827/// Tries a lost camera again now.
828async fn camera_retry(
829    State(engine): State<SurfaceEngine>,
830    context: Context,
831    Path(camera): Path<String>,
832    Query(query): Query<SurfaceQuery>,
833) -> Response {
834    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
835    match engine.retry_camera(&caller, &camera).await {
836        Ok(view) => Json(view).into_response(),
837        Err(error) => failed(error),
838    }
839}
840
841/// Changes a zone; closed to paired devices, which open the zone in the web home.
842async fn camera_zone(
843    State(engine): State<SurfaceEngine>,
844    context: Context,
845    Path((camera, zone)): Path<(String, String)>,
846    Json(change): Json<crate::camera::ZoneChange>,
847) -> Response {
848    let caller = try_or_respond!(caller(context, SurfaceKind::Web, None));
849    match engine.save_camera_zone(&caller, &camera, &zone, &change).await {
850        Ok(saved) => Json(saved).into_response(),
851        Err(error) => failed(error),
852    }
853}
854
855/// Freezes the frame on screen for a card: held in memory while the person writes it.
856async fn camera_freeze(
857    State(engine): State<SurfaceEngine>,
858    context: Context,
859    Path(camera): Path<String>,
860    Query(query): Query<SurfaceQuery>,
861    Json(freeze): Json<crate::camera::FreezeFrame>,
862) -> Response {
863    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
864    match engine.freeze_camera_frame(&caller, &camera, &freeze.frame).await {
865        Ok(stage) => Json(stage).into_response(),
866        Err(error) => failed(error),
867    }
868}
869
870/// Raises a card from a frozen frame: that frame alone is kept as evidence.
871async fn camera_card(
872    State(engine): State<SurfaceEngine>,
873    context: Context,
874    Path(camera): Path<String>,
875    Query(query): Query<SurfaceQuery>,
876    Json(card): Json<crate::camera::RaiseCard>,
877) -> Response {
878    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
879    match engine.raise_camera_card(&caller, &camera, &card).await {
880        Ok(raised) => Json(raised).into_response(),
881        Err(error) => failed(error),
882    }
883}
884
885async fn thread(
886    State(engine): State<SurfaceEngine>,
887    context: Context,
888    Path(session): Path<String>,
889    Query(query): Query<SurfaceQuery>,
890) -> Response {
891    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
892    match engine.thread(&caller, &session).await {
893        Ok(entries) => Json(ThreadResponse { session_id: session, entries }).into_response(),
894        Err(error) => failed(error),
895    }
896}
897
898async fn feed(
899    State(engine): State<SurfaceEngine>,
900    context: Context,
901    ends: Option<Extension<devices::DeviceEnds>>,
902    headers: HeaderMap,
903    Path(session): Path<String>,
904    Query(query): Query<SurfaceQuery>,
905) -> Response {
906    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
907    let after = headers
908        .get("last-event-id")
909        .and_then(|value| value.to_str().ok())
910        .and_then(|value| value.trim().parse::<u64>().ok())
911        .or(query.after);
912    // Refuse a session the caller does not own before the stream starts (S-I8).
913    if let Err(error) = engine.thread(&caller, &session).await {
914        return failed(error);
915    }
916    // A paired device's feed ends with the device: removed, or its pairing over (S-I7).
917    let device_ends = match (ends, caller.device.clone()) {
918        (Some(Extension(devices::DeviceEnds(pairing))), Some(device)) => {
919            pairing.until_device_ends(device).boxed()
920        }
921        _ => futures::future::pending().boxed(),
922    };
923    let frames = engine.feed(caller, session, after).take_until(device_ends).map(|frame| {
924        let event = match frame {
925            Ok(FeedFrame::Entry { entry }) => {
926                SseEvent::default().id(entry.seq.to_string()).event("entry").json_data(&entry)
927            }
928            Ok(FeedFrame::Decisions { cards }) => {
929                SseEvent::default().event("decisions").json_data(&cards)
930            }
931            Ok(FeedFrame::Reset { len }) => {
932                SseEvent::default().event("reset").json_data(serde_json::json!({ "len": len }))
933            }
934            // No `id`: a changed entry is not where a reconnect resumes.
935            Ok(FeedFrame::Changed { entry }) => {
936                SseEvent::default().event("changed").json_data(&entry)
937            }
938            Err(error) => SseEvent::default()
939                .event("error")
940                .json_data(AdkError::from(error).to_problem_json()),
941        };
942        Ok::<_, std::convert::Infallible>(
943            event.unwrap_or_else(|_| SseEvent::default().comment("a frame could not be encoded")),
944        )
945    });
946    Sse::new(frames).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))).into_response()
947}
948
949async fn queued(
950    State(engine): State<SurfaceEngine>,
951    context: Context,
952    Path(session): Path<String>,
953    Query(query): Query<SurfaceQuery>,
954) -> Response {
955    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
956    // The queue is kept per caller, so a caller only ever reads their own.
957    let queued = engine.queued(&caller, &session);
958    Json(QueuedResponse { session_id: session, queued }).into_response()
959}
960
961async fn agents(
962    State(engine): State<SurfaceEngine>,
963    context: Context,
964    Query(query): Query<SurfaceQuery>,
965) -> Response {
966    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
967    match engine.agents(&caller).await {
968        Ok(agents) => Json(AgentsResponse {
969            agents,
970            primary: engine.primary_agent(),
971            can_add: engine.can_add_agents(&caller),
972            removed: engine.removed_agents(&caller).await.unwrap_or_default(),
973        })
974        .into_response(),
975        Err(error) => failed(error),
976    }
977}
978
979async fn agent(
980    State(engine): State<SurfaceEngine>,
981    context: Context,
982    Path(id): Path<String>,
983    Query(query): Query<SurfaceQuery>,
984) -> Response {
985    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
986    match engine.agent(&caller, &id).await {
987        Ok(detail) => Json::<crate::agents::AgentDetail>(detail).into_response(),
988        Err(error) => failed(error),
989    }
990}
991
992async fn agent_threads(
993    State(engine): State<SurfaceEngine>,
994    context: Context,
995    Path(id): Path<String>,
996    Query(query): Query<SurfaceQuery>,
997) -> Response {
998    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
999    match engine.agent_threads(&caller, &id).await {
1000        Ok(threads) => Json::<crate::agents::AgentThreads>(threads).into_response(),
1001        Err(error) => failed(error),
1002    }
1003}
1004
1005async fn agent_choices(
1006    State(engine): State<SurfaceEngine>,
1007    context: Context,
1008    Query(query): Query<SurfaceQuery>,
1009) -> Response {
1010    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
1011    match engine.agent_choices(&caller).await {
1012        Ok(choices) => Json::<crate::agents::AgentChoices>(choices).into_response(),
1013        Err(error) => failed(error),
1014    }
1015}
1016
1017async fn agent_preview(
1018    State(engine): State<SurfaceEngine>,
1019    context: Context,
1020    Query(query): Query<SurfaceQuery>,
1021    Json(request): Json<crate::agents::AgentPreviewRequest>,
1022) -> Response {
1023    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
1024    match engine.preview_agent(&caller, request).await {
1025        Ok(preview) => Json::<crate::agents::AgentPreview>(preview).into_response(),
1026        Err(error) => failed(error),
1027    }
1028}
1029
1030async fn status(
1031    State(engine): State<SurfaceEngine>,
1032    context: Context,
1033    Query(query): Query<SurfaceQuery>,
1034) -> Response {
1035    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
1036    match engine.status(&caller, query.session.as_deref()).await {
1037        Ok(line) => Json::<StatusLine>(line).into_response(),
1038        Err(error) => failed(error),
1039    }
1040}
1041
1042async fn answers(
1043    State(engine): State<SurfaceEngine>,
1044    context: Context,
1045    Query(query): Query<SurfaceQuery>,
1046) -> Response {
1047    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
1048    let since = query.since.unwrap_or_else(|| Utc::now() - chrono::Duration::days(7));
1049    match engine.answers_since(&caller, since).await {
1050        Ok(summary) => Json::<crate::answers::AnswerSummary>(summary).into_response(),
1051        Err(error) => failed(error),
1052    }
1053}
1054
1055async fn briefing(
1056    State(engine): State<SurfaceEngine>,
1057    context: Context,
1058    Query(query): Query<SurfaceQuery>,
1059) -> Response {
1060    let caller = try_or_respond!(caller(context, query.surface.unwrap_or(SurfaceKind::Web), None));
1061    let since = query.since.unwrap_or_else(|| Utc::now() - chrono::Duration::hours(24));
1062    match engine.briefing(&caller, since).await {
1063        Ok(briefing) => Json::<Briefing>(briefing).into_response(),
1064        Err(error) => failed(error),
1065    }
1066}
1067
1068/// Whether `headers` are those of the web home's own page: a browser's same-origin request.
1069/// Browsers set `Sec-Fetch-Site` themselves and page scripts cannot change it, so another
1070/// client sends it only by imitating a browser on purpose.
1071fn from_home_page(headers: &HeaderMap) -> bool {
1072    headers.get("sec-fetch-site").and_then(|value| value.to_str().ok()) == Some("same-origin")
1073}
1074
1075async fn command(
1076    State(engine): State<SurfaceEngine>,
1077    context: Context,
1078    headers: HeaderMap,
1079    Json(request): Json<CommandRequest>,
1080) -> Response {
1081    // A device has its own routes, each opened by its token's scopes; commands would let it
1082    // send, change the mode or resume (spec 3.3 §10 K2, §11 S-I10).
1083    if let Some(Extension(Some(context))) = &context
1084        && device_of(context).is_some()
1085    {
1086        return failed(SurfaceError::NotHere(
1087            "a paired device answers and stops through its own routes, not commands".into(),
1088        ));
1089    }
1090    // Chat and agent input reach the engine in process, from their adapters; over HTTP a
1091    // client could otherwise put a channel it never used on the record (spec 3.3 §11).
1092    if matches!(request.origin, Origin::Chat { .. } | Origin::Agent { .. })
1093        || matches!(request.surface, SurfaceKind::Chat)
1094    {
1095        return failed(SurfaceError::Invalid(
1096            "chat and agent input reach the engine through their adapters, not this API".into(),
1097        ));
1098    }
1099    // A spoken answer comes from the voice surface's own transcript, never a declared one;
1100    // cancelling a spoken answer stays open to every surface (spec 3.3 §5.6, §7.2).
1101    if matches!(request.command, Command::Decide { .. })
1102        && (request.surface == SurfaceKind::Voice || request.origin == Origin::Voice)
1103    {
1104        return failed(SurfaceError::Invalid(
1105            "a spoken answer reaches the engine through the voice surface, not this API".into(),
1106        ));
1107    }
1108    // Resuming happens only in the web home or on a paired local terminal (spec 3.3 S-I10),
1109    // and a declared surface never shows the web home: a resume is the home's only from its
1110    // own page; from any other client it is a terminal's elsewhere, which may not resume.
1111    let surface = match request.command {
1112        Command::ResumeAll | Command::ResumeAgent { .. } if !from_home_page(&headers) => {
1113            SurfaceKind::Terminal
1114        }
1115        _ => request.surface,
1116    };
1117    let caller = try_or_respond!(caller(context, surface, Some(request.origin)));
1118    match engine.execute(&caller, request.command).await {
1119        Ok(outcome) => Json::<CommandOutcome>(outcome).into_response(),
1120        Err(error) => failed(error),
1121    }
1122}
1123
1124async fn openapi_document() -> Response {
1125    Json(openapi()).into_response()
1126}