adk_surface/web/verbs.rs
1//! The screen actions' routes on the web home (spec 3.3 §2 item 7, §6.1; features `verb-ui`
2//! and `web`), with their own OpenAPI document, so the engine's document stays the same in
3//! every `web` build.
4//!
5//! | Route (under `/api`) | Answer |
6//! |---|---|
7//! | `GET /surface/verbs` | [`VerbsResponse`]: the catalogue and the caller's Coming up with the times each item may move to |
8//! | `POST /surface/verbs/call` | [`VerbCallRequest`] → [`VerbDone`](crate::verbs::VerbDone), once it ran |
9//! | `GET /surface/verbs/openapi.json` | This API's OpenAPI document |
10//!
11//! Every route needs the server's authenticated caller (`401` without one) and acts only on the
12//! caller's own items (`404` for anyone else's, S-I8). A declared voice or agent origin, or
13//! the voice or chat surface, answers `400`: spoken actions come through the voice surface's
14//! own transcript, and agents ask through their tools. A paired device's token reads as its
15//! row: a phone may snooze; a terminal paired from another machine gets `403` (owner question
16//! 27).
17
18use axum::extract::{Query, State};
19use axum::response::{IntoResponse, Response};
20use axum::routing::{get, post};
21use axum::{Extension, Json, Router};
22use schemars::JsonSchema;
23use serde::{Deserialize, Serialize};
24
25use super::{Context, SurfaceQuery, Unauthenticated, caller, device_of, problem, unauthenticated};
26use crate::origin::{Origin, SurfaceKind};
27use crate::verbs::{ComingUpItem, VerbError, VerbGate, VerbIntent, VerbView, words};
28
29/// The route paths, relative to the `/api` prefix.
30pub mod paths {
31 /// `GET`: the catalogue and the caller's Coming up.
32 pub const VERBS: &str = "/surface/verbs";
33 /// `POST`: takes an action.
34 pub const CALL: &str = "/surface/verbs/call";
35 /// `GET`: the OpenAPI document.
36 pub const OPENAPI: &str = "/surface/verbs/openapi.json";
37}
38
39/// `GET /surface/verbs` answer (spec 3.3 §2 item 7).
40///
41/// # Example
42///
43/// ```rust
44/// use adk_surface::web::verbs::VerbsResponse;
45///
46/// let answer: VerbsResponse = serde_json::from_value(serde_json::json!({ "verbs": [], "comingUp": [] })).unwrap();
47/// assert!(answer.coming_up.is_empty());
48/// ```
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
50#[serde(rename_all = "camelCase")]
51pub struct VerbsResponse {
52 /// The actions this home offers.
53 pub verbs: Vec<VerbView>,
54 /// The caller's Coming up, soonest first, with the times each item may move to.
55 pub coming_up: Vec<ComingUpItem>,
56}
57
58/// `POST /surface/verbs/call` body: the action, and the surface it was given on and how. The
59/// caller is the server's; a declared surface or origin only says where the person was.
60///
61/// # Example
62///
63/// ```rust
64/// use adk_surface::web::verbs::VerbCallRequest;
65///
66/// let request: VerbCallRequest = serde_json::from_value(serde_json::json!({
67/// "origin": { "kind": "pointer" },
68/// "intent": { "verb": "snooze", "objects": [{ "kind": "comingUp", "id": "agenda-7f3" }],
69/// "args": { "to": "2026-10-26T19:00:00+03:00" } },
70/// }))
71/// .unwrap();
72/// assert_eq!(request.surface, adk_surface::SurfaceKind::Web);
73/// ```
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
75#[serde(rename_all = "camelCase")]
76pub struct VerbCallRequest {
77 /// The surface; defaults to the web home.
78 #[serde(default = "web")]
79 pub surface: SurfaceKind,
80 /// How the input was given.
81 pub origin: Origin,
82 /// The action.
83 pub intent: VerbIntent,
84}
85
86fn web() -> SurfaceKind {
87 SurfaceKind::Web
88}
89
90/// The screen actions' routes, relative to `/api` (spec 3.3 §2 item 7): mount with
91/// `ServerBuilder::add_api_routes` beside [`router`](super::router). Building them names
92/// [`Served::Verbs`](crate::Served::Verbs) on the gate's engine, so the web home reads them.
93///
94/// # Example
95///
96/// ```rust,no_run
97/// use adk_surface::verbs::VerbGate;
98///
99/// # fn example(gate: VerbGate, builder: adk_server::ServerBuilder) {
100/// let builder = builder.add_api_routes(adk_surface::web::verbs::router(gate));
101/// # let _ = builder;
102/// # }
103/// ```
104pub fn router(gate: VerbGate) -> Router {
105 gate.engine().serve(crate::Served::Verbs);
106 Router::new()
107 .route(paths::VERBS, get(verbs))
108 .route(paths::CALL, post(call))
109 .route(paths::OPENAPI, get(openapi_document))
110 .with_state(gate)
111}
112
113fn failed(error: VerbError) -> Response {
114 problem(&adk_core::AdkError::from(error))
115}
116
117/// A terminal paired from another machine cannot take screen actions (owner question 27).
118fn remote_terminal(context: &Context, surface: SurfaceKind) -> bool {
119 match context {
120 Some(Extension(Some(context))) => {
121 device_of(context).is_some()
122 && super::device_kind(context) != Some("phone")
123 && super::device_kind(context) != Some("tray")
124 && surface != SurfaceKind::Chat
125 }
126 _ => false,
127 }
128}
129
130async fn verbs(
131 State(gate): State<VerbGate>,
132 context: Context,
133 Query(query): Query<SurfaceQuery>,
134) -> Response {
135 let surface = query.surface.unwrap_or(SurfaceKind::Web);
136 let views = gate.registry().views();
137 if remote_terminal(&context, surface) {
138 return Json(VerbsResponse { verbs: views, coming_up: Vec::new() }).into_response();
139 }
140 let caller = match caller(context, surface, None) {
141 Ok(caller) => caller,
142 Err(Unauthenticated) => return unauthenticated(),
143 };
144 match gate.coming_up(&caller).await {
145 Ok(coming_up) => Json(VerbsResponse { verbs: views, coming_up }).into_response(),
146 // Chat and the tray list nothing to act on.
147 Err(VerbError::NotHere(_)) => {
148 Json(VerbsResponse { verbs: views, coming_up: Vec::new() }).into_response()
149 }
150 Err(error) => failed(error),
151 }
152}
153
154async fn call(
155 State(gate): State<VerbGate>,
156 context: Context,
157 Json(request): Json<VerbCallRequest>,
158) -> Response {
159 // Spoken actions come from the voice surface's own transcript, agents' through their
160 // tools, chat's never (spec 3.3 §5.6, §7.2).
161 if matches!(request.origin, Origin::Voice | Origin::Agent { .. } | Origin::Chat { .. })
162 || matches!(request.surface, SurfaceKind::Voice | SurfaceKind::Chat)
163 {
164 return failed(VerbError::invalid(
165 "a spoken action reaches the home through the voice surface, an agent's through its \
166 own tool, and chat takes none: this API takes a person's click, tap or key",
167 ));
168 }
169 if remote_terminal(&context, request.surface) {
170 return failed(VerbError::NotHere(words::NOT_FROM_A_REMOTE_TERMINAL.to_string()));
171 }
172 let caller = match caller(context, request.surface, Some(request.origin)) {
173 Ok(caller) => caller,
174 Err(Unauthenticated) => return unauthenticated(),
175 };
176 match gate.call(&caller, request.intent).await {
177 Ok(done) => Json(done).into_response(),
178 Err(error) => failed(error),
179 }
180}
181
182async fn openapi_document() -> Response {
183 Json(super::openapi::verbs::openapi()).into_response()
184}
185
186/// The OpenAPI 3.1 document of [`router`], its schemas generated from the Rust types
187/// (spec 3.3 §6).
188///
189/// # Example
190///
191/// ```rust
192/// let document = adk_surface::web::verbs::openapi();
193/// assert!(document["components"]["schemas"]["ComingUpItem"].is_object());
194/// ```
195pub fn openapi() -> serde_json::Value {
196 super::openapi::verbs::openapi()
197}
198
199/// TypeScript declarations of every schema in [`openapi`], for the web home's screen actions.
200///
201/// # Example
202///
203/// ```rust
204/// assert!(adk_surface::web::verbs::typescript().contains("export interface VerbsResponse {"));
205/// ```
206pub fn typescript() -> String {
207 super::openapi::verbs::typescript()
208}