1use std::collections::BTreeMap;
12use std::fmt::Write as _;
13
14use schemars::JsonSchema;
15use schemars::generate::{Contract, SchemaGenerator, SchemaSettings};
16use serde_json::{Map, Value, json};
17
18use super::phone::{
19 AgentConfirmOptionsRequest, AnswerRequest, ConfirmOptions, ConfirmOptionsRequest,
20 ConfirmRequest, DeliveriesResponse, PasskeyOptions, PasskeyRegistration, PhoneDevicesResponse,
21 PhoneInfo, PushReceivedRequest, PushSubscriptionRequest, QrRequest, StopRequest,
22};
23use super::{
24 AgentsResponse, CommandRequest, DecisionsResponse, QueuedResponse, SurfaceQuery,
25 TakeOverRequest, ThreadResponse, paths,
26};
27use crate::engine::{CommandOutcome, FeedFrame};
28use crate::model::{Briefing, DecisionCard, FeedEntry, StatusLine};
29use crate::voice::{
30 VoiceClientMessage, VoiceModels, VoiceTicket, VoiceTicketRequest, VoiceUpdate,
31 paths as voice_paths,
32};
33
34#[cfg(feature = "website")]
36pub(super) mod website;
37#[cfg(feature = "verb-ui")]
39pub(super) mod verbs;
40#[cfg(feature = "workflow")]
42pub(super) mod workflow;
43
44fn generator(contract: Contract) -> SchemaGenerator {
45 SchemaSettings::draft2020_12()
46 .with(|settings| {
47 settings.definitions_path = "/components/schemas".into();
48 settings.meta_schema = None;
49 settings.contract = contract;
50 })
51 .into_generator()
52}
53
54fn schema_ref<T: JsonSchema>(generator: &mut SchemaGenerator) -> Value {
55 generator.subschema_for::<T>().to_value()
56}
57
58fn answer(description: &str, schema: Value) -> Value {
59 json!({
60 "description": description,
61 "content": { "application/json": { "schema": schema } },
62 })
63}
64
65fn problem() -> Value {
66 json!({
67 "description": "A problem document with the engine's `surface.*` code, or the source's",
68 "content": { "application/problem+json": { "schema": { "type": "object" } } },
69 })
70}
71
72fn errors(mut responses: Map<String, Value>) -> Value {
73 for status in ["401", "403", "404"] {
74 responses.insert(status.to_string(), problem());
75 }
76 Value::Object(responses)
77}
78
79fn read(summary: &str, parameters: Value, ok: Value) -> Value {
80 let mut responses = Map::new();
81 responses.insert("200".into(), ok);
82 json!({ "get": { "summary": summary, "parameters": parameters, "responses": errors(responses) } })
83}
84
85fn query(name: &str, description: &str, schema: Value) -> Value {
86 json!({ "name": name, "in": "query", "required": false, "description": description, "schema": schema })
87}
88
89fn write(
91 method: &str,
92 summary: &str,
93 parameters: Value,
94 body: Option<Value>,
95 ok: (&str, Value),
96) -> Value {
97 let mut operation = Map::new();
98 operation.insert("summary".into(), json!(summary));
99 operation.insert("parameters".into(), parameters);
100 if let Some(body) = body {
101 operation.insert(
102 "requestBody".into(),
103 json!({ "required": true, "content": { "application/json": { "schema": body } } }),
104 );
105 }
106 let mut responses = Map::new();
107 responses.insert(ok.0.into(), ok.1);
108 responses.insert("400".into(), problem());
109 operation.insert("responses".into(), errors(responses));
110 let mut route = Map::new();
111 route.insert(method.into(), Value::Object(operation));
112 Value::Object(route)
113}
114
115fn no_content(description: &str) -> (&'static str, Value) {
116 ("204", json!({ "description": description }))
117}
118
119fn path_param(name: &str) -> Value {
120 json!({ "name": name, "in": "path", "required": true, "schema": { "type": "string" } })
121}
122
123pub fn openapi() -> Value {
134 let mut out = generator(Contract::Serialize);
135 let decisions = schema_ref::<DecisionsResponse>(&mut out);
136 let card = schema_ref::<DecisionCard>(&mut out);
137 let thread = schema_ref::<ThreadResponse>(&mut out);
138 let agents = schema_ref::<AgentsResponse>(&mut out);
139 let status = schema_ref::<StatusLine>(&mut out);
140 let briefing = schema_ref::<Briefing>(&mut out);
141 let outcome = schema_ref::<CommandOutcome>(&mut out);
142 let frame = schema_ref::<FeedFrame>(&mut out);
143 let entry = schema_ref::<FeedEntry>(&mut out);
144 let queued = schema_ref::<QueuedResponse>(&mut out);
145 let phone = schema_ref::<PhoneInfo>(&mut out);
146 let deliveries = schema_ref::<DeliveriesResponse>(&mut out);
147 let passkey_options = schema_ref::<PasskeyOptions>(&mut out);
148 let confirm_options = schema_ref::<ConfirmOptions>(&mut out);
149 let phone_devices = schema_ref::<PhoneDevicesResponse>(&mut out);
150 let voice_models = schema_ref::<VoiceModels>(&mut out);
151 let voice_ticket = schema_ref::<VoiceTicket>(&mut out);
152 let voice_update = schema_ref::<VoiceUpdate>(&mut out);
153 let agent_detail = schema_ref::<crate::agents::AgentDetail>(&mut out);
154 let agent_threads = schema_ref::<crate::agents::AgentThreads>(&mut out);
155 let answer_summary = schema_ref::<crate::answers::AnswerSummary>(&mut out);
156 let agent_choices = schema_ref::<crate::agents::AgentChoices>(&mut out);
157 let agent_preview = schema_ref::<crate::agents::AgentPreview>(&mut out);
158 let genui_capabilities = schema_ref::<super::genui::GenuiCapabilities>(&mut out);
159 let genui_forms = schema_ref::<super::genui::FormsResponse>(&mut out);
160 let genui_catalogs = schema_ref::<super::genui::CatalogDocuments>(&mut out);
161 let app_open = schema_ref::<super::genui::AppOpen>(&mut out);
162 let app_answer = schema_ref::<super::genui::AppAnswer>(&mut out);
163 let viewer = schema_ref::<crate::viewer::ViewerView>(&mut out);
164 let saved_example = schema_ref::<crate::viewer::SavedExample>(&mut out);
165 let cameras_view = schema_ref::<crate::camera::CamerasView>(&mut out);
166 let camera_view = schema_ref::<crate::camera::CameraView>(&mut out);
167 let stage_view = schema_ref::<crate::camera::StageView>(&mut out);
168 let zone_saved = schema_ref::<crate::camera::ZoneSaved>(&mut out);
169 let card_raised = schema_ref::<crate::camera::CardRaised>(&mut out);
170 let frame_taken = schema_ref::<crate::camera::FrameTaken>(&mut out);
171 let mut schemas = out.take_definitions(true);
172
173 let mut input = generator(Contract::Deserialize);
174 let request = schema_ref::<CommandRequest>(&mut input);
175 let take_over = schema_ref::<TakeOverRequest>(&mut input);
176 let answer_body = schema_ref::<AnswerRequest>(&mut input);
177 let stop_body = schema_ref::<StopRequest>(&mut input);
178 let confirm_options_body = schema_ref::<ConfirmOptionsRequest>(&mut input);
179 let confirm_body = schema_ref::<ConfirmRequest>(&mut input);
180 let agent_confirm_options_body = schema_ref::<AgentConfirmOptionsRequest>(&mut input);
181 let push_body = schema_ref::<PushSubscriptionRequest>(&mut input);
182 let received_body = schema_ref::<PushReceivedRequest>(&mut input);
183 let registration_body = schema_ref::<PasskeyRegistration>(&mut input);
184 let qr_body = schema_ref::<QrRequest>(&mut input);
185 let voice_request = schema_ref::<VoiceTicketRequest>(&mut input);
186 let voice_message = schema_ref::<VoiceClientMessage>(&mut input);
187 let preview_body = schema_ref::<crate::agents::AgentPreviewRequest>(&mut input);
188 let app_request = schema_ref::<super::genui::AppRequest>(&mut input);
189 let app_message = schema_ref::<super::genui::AppMessageRequest>(&mut input);
190 let example_body = schema_ref::<crate::viewer::LabelledExample>(&mut input);
191 let zone_body = schema_ref::<crate::camera::ZoneChange>(&mut input);
192 let card_body = schema_ref::<crate::camera::RaiseCard>(&mut input);
193 let freeze_body = schema_ref::<crate::camera::FreezeFrame>(&mut input);
194 let surface_query = input.subschema_for::<SurfaceQuery>().to_value();
195 for (name, schema) in input.take_definitions(true) {
196 schemas.entry(name).or_insert(schema);
197 }
198 let surface = surface_query["properties"]["surface"].clone();
199
200 let mut routes = BTreeMap::new();
201 let with = |path: &str| format!("/api{path}");
202 routes.insert(
203 with(paths::DECISIONS),
204 read(
205 "The caller's open decisions as cards (spec 3.3 §7.1)",
206 json!([
207 query("surface", "The surface the answers are computed for", surface.clone()),
208 query("session", "Only this session's decisions", json!({ "type": "string" })),
209 ]),
210 answer("Open decisions, oldest first", decisions),
211 ),
212 );
213 routes.insert(
214 with(paths::DECISION),
215 read(
216 "One decision: waiting, or decided with who, where and when",
217 json!([
218 path_param("id"),
219 query("surface", "The surface the answers are computed for", surface.clone())
220 ]),
221 answer("The decision", card),
222 ),
223 );
224 routes.insert(
225 with(paths::EVIDENCE),
226 json!({ "get": {
227 "summary": "One image a decision holds as evidence (spec 3.7 §8.2): the exact bytes whose digest the card shows, for a viewer who may see the decision; never cached",
228 "parameters": [
229 path_param("id"),
230 { "name": "index", "in": "path", "required": true, "description": "The image's place in the card's `media.images`", "schema": { "type": "integer", "minimum": 0 } },
231 query("surface", "The surface asking", surface.clone()),
232 ],
233 "responses": errors({
234 let mut ok = Map::new();
235 ok.insert("200".into(), json!({
236 "description": "The image",
237 "content": {
238 "image/png": { "schema": { "type": "string", "format": "binary" } },
239 "image/jpeg": { "schema": { "type": "string", "format": "binary" } },
240 "image/webp": { "schema": { "type": "string", "format": "binary" } }
241 }
242 }));
243 ok
244 }),
245 } }),
246 );
247 let image_param = json!({
248 "name": "image", "in": "path", "required": true,
249 "description": "A `sha256:` digest, or the name of an image the session holds",
250 "schema": { "type": "string" },
251 });
252 routes.insert(
253 with(paths::VISION_VIEW),
254 read(
255 "The annotated viewer of one image of a session (spec 3.7 §8.2, X12): every answer the vision tools gave for it, with each region's backend, frame and transform chain; for the session's owner",
256 json!([
257 path_param("session"),
258 image_param.clone(),
259 query("surface", "The surface asking", surface.clone()),
260 query("answer", "The answer to show, by its call; the newest otherwise", json!({ "type": "string" })),
261 query("compare", "A second answer to show beside it", json!({ "type": "string" })),
262 ]),
263 answer("The viewer", viewer),
264 ),
265 );
266 routes.insert(
267 with(paths::VISION_IMAGE),
268 json!({ "get": {
269 "summary": "One image of a session (spec 3.7 §8.3): the exact bytes whose digest the viewer shows, for the session's owner; never cached",
270 "parameters": [path_param("session"), image_param, query("surface", "The surface asking", surface.clone())],
271 "responses": errors({
272 let mut ok = Map::new();
273 ok.insert("200".into(), json!({
274 "description": "The image",
275 "content": {
276 "image/png": { "schema": { "type": "string", "format": "binary" } },
277 "image/jpeg": { "schema": { "type": "string", "format": "binary" } },
278 "image/webp": { "schema": { "type": "string", "format": "binary" } }
279 }
280 }));
281 ok
282 }),
283 } }),
284 );
285 routes.insert(
286 with(paths::VISION_REGIONS),
287 read(
288 "One answer's RegionSet, as `adk-vision/schema/region-set.json` publishes it, to save as a file (board choice V14); with `with`, both answers' sets in an array",
289 json!([
290 path_param("session"),
291 path_param("answer"),
292 query("surface", "The surface asking", surface.clone()),
293 query("with", "A second answer, exported beside it", json!({ "type": "string" })),
294 ]),
295 answer("The RegionSet, or an array of two", json!({ "type": ["object", "array"] })),
296 ),
297 );
298 routes.insert(
299 with(paths::VISION_EXAMPLES),
300 write(
301 "post",
302 "Save a labelled example from an answer (board choices V11–V13): an adk-eval case pointing at the image by path and digest, the image beside its file; the run's answer is unchanged and the example recorded. Not from a paired phone",
303 json!([path_param("session")]),
304 Some(example_body),
305 ("200", answer("Where it was saved", saved_example)),
306 ),
307 );
308 routes.insert(
310 with(paths::CAMERAS),
311 read(
312 "Every camera the caller may see, as a grid (spec 3.7 §8.2, board choice C8): each with its state, switch, picture and frames today",
313 json!([query("surface", "The surface asking", surface.clone())]),
314 answer("The cameras", cameras_view),
315 ),
316 );
317 let camera_param = json!({
318 "name": "camera", "in": "path", "required": true,
319 "description": "The camera's id, such as `line-2`",
320 "schema": { "type": "string" },
321 });
322 routes.insert(
323 with(paths::CAMERA),
324 read(
325 "One camera, watched large (board choice C1): live frames with overlays, tracks, watch conditions and zones, the frame governor's state, the agent's decisions and every source",
326 json!([camera_param.clone(), query("surface", "The surface asking", surface.clone())]),
327 answer("The camera", camera_view.clone()),
328 ),
329 );
330 routes.insert(
331 with(paths::CAMERA_FRAME),
332 json!({ "get": {
333 "summary": "A frame the server holds in memory for a camera (spec 3.7 §8.2): the exact bytes whose digest the picture names; a camera switched off holds none; never cached",
334 "parameters": [
335 camera_param.clone(),
336 { "name": "frame", "in": "path", "required": true, "description": "The frame's `sha256:` digest", "schema": { "type": "string" } },
337 query("surface", "The surface asking", surface.clone()),
338 ],
339 "responses": errors({
340 let mut ok = Map::new();
341 ok.insert("200".into(), json!({
342 "description": "The frame",
343 "content": {
344 "image/jpeg": { "schema": { "type": "string", "format": "binary" } },
345 "image/png": { "schema": { "type": "string", "format": "binary" } }
346 }
347 }));
348 ok
349 }),
350 } }),
351 );
352 routes.insert(
353 with(paths::CAMERA_FEED),
354 json!({ "get": {
355 "summary": "A camera's picture after each frame that passes the server's gate, as server-sent events: `frame` carries a StageView, `changed` says to read the camera again",
356 "parameters": [camera_param.clone(), query("surface", "The surface asking", surface.clone())],
357 "responses": errors({
358 let mut ok = Map::new();
359 ok.insert("200".into(), json!({
360 "description": "`text/event-stream`; a `frame` event's data is a StageView",
361 "content": { "text/event-stream": { "schema": stage_view.clone() } },
362 }));
363 ok
364 }),
365 } }),
366 );
367 routes.insert(
368 with(paths::CAMERA_FRAMES),
369 json!({ "post": {
370 "summary": "One frame this screen's camera captured, for a camera that takes them (`actions.sendFrames`), at most 10 a second: handed to the camera's pipeline through the server's gate, or dropped with the reason while the camera is off, stopped or paused by Stop all, when the screen stops capturing. Nothing is written. A paired phone needs the decide scope",
371 "parameters": [camera_param.clone(), query("surface", "The surface asking", surface.clone())],
372 "requestBody": {
373 "required": true,
374 "content": {
375 "image/jpeg": { "schema": { "type": "string", "format": "binary" } },
376 "image/png": { "schema": { "type": "string", "format": "binary" } },
377 "image/webp": { "schema": { "type": "string", "format": "binary" } }
378 }
379 },
380 "responses": errors({
381 let mut ok = Map::new();
382 ok.insert("200".into(), answer("What became of the frame", frame_taken));
383 ok.insert("400".into(), problem());
384 ok.insert("413".into(), problem());
385 ok.insert("429".into(), problem());
386 ok
387 }),
388 } }),
389 );
390 for (path, summary) in [
391 (
392 paths::CAMERA_ON,
393 "Switch a camera on (board choice C2); recorded first. A paired phone needs the decide scope",
394 ),
395 (
396 paths::CAMERA_OFF,
397 "Switch a camera off (board choice C2): the server drops its frames from then on and forgets those it held; nothing is captured or sent. Recorded",
398 ),
399 (paths::CAMERA_STOP, "End a camera's stream (board choice C2); recorded"),
400 (paths::CAMERA_RETRY, "Try a lost camera again now (board choice C6); recorded"),
401 ] {
402 routes.insert(
403 with(path),
404 write(
405 "post",
406 summary,
407 json!([
408 camera_param.clone(),
409 query("surface", "The surface asking", surface.clone())
410 ]),
411 None,
412 ("200", answer("The camera now", camera_view.clone())),
413 ),
414 );
415 }
416 routes.insert(
417 with(paths::CAMERA_ZONE),
418 write(
419 "put",
420 "Change a zone (board choice C12): the watches that use it read the new corners from their next frame; a zone changed since the person started is refused. Recorded; not from a paired phone",
421 json!([camera_param.clone(), path_param("zone")]),
422 Some(zone_body),
423 ("200", answer("The zone now", zone_saved)),
424 ),
425 );
426 routes.insert(
427 with(paths::CAMERA_FREEZE),
428 write(
429 "post",
430 "Freeze the frame on screen for a card (board choice C11): held in memory for 15 minutes while the person writes it, forgotten when the camera is switched off; nothing is written",
431 json!([camera_param.clone(), query("surface", "The surface asking", surface.clone())]),
432 Some(freeze_body),
433 ("200", answer("The frozen frame's picture", stage_view.clone())),
434 ),
435 );
436 routes.insert(
437 with(paths::CAMERA_CARDS),
438 write(
439 "post",
440 "Raise a card from a frozen frame (board choice C11): that one frame is kept as evidence, everyone in it covered first, with the regions on it, and the card goes to the watching agent as the caller's message naming the evidence by digest. Nothing else is stored",
441 json!([camera_param, query("surface", "The surface asking", surface.clone())]),
442 Some(card_body),
443 ("200", answer("The evidence kept and what sending the card did", card_raised)),
444 ),
445 );
446 routes.insert(
447 with(paths::THREAD),
448 read(
449 "The session's entries, numbered by their position in the session store",
450 json!([path_param("session")]),
451 answer("The thread", thread),
452 ),
453 );
454 routes.insert(
455 with(paths::FEED),
456 json!({ "get": {
457 "summary": "The session's feed as server-sent events: `entry` frames carry `id` = `seq` and resume after `Last-Event-ID`; `decisions` and `reset` frames carry no id",
458 "parameters": [
459 path_param("session"),
460 query("after", "Resume after this seq when no Last-Event-ID header is sent", json!({ "type": "integer", "minimum": 0 })),
461 { "name": "Last-Event-ID", "in": "header", "required": false, "schema": { "type": "string" } },
462 ],
463 "responses": errors({
464 let mut ok = Map::new();
465 ok.insert("200".into(), json!({
466 "description": "`text/event-stream` of FeedFrame payloads; an `entry` event's data is a FeedEntry",
467 "content": { "text/event-stream": { "schema": frame, "x-entry": entry } },
468 }));
469 ok
470 }),
471 } }),
472 );
473 routes.insert(
474 with(paths::QUEUED),
475 read(
476 "What the caller typed while a decision of the session was open, sent once it is answered (spec 3.3 §7.4 rule 2)",
477 json!([path_param("session")]),
478 answer("The queued input, oldest first", queued),
479 ),
480 );
481 routes.insert(
482 with(paths::AGENTS),
483 read("The caller's agents (spec 3.3 §8.1)", json!([]), answer("The roster", agents)),
484 );
485 routes.insert(
487 with(paths::AGENT),
488 read(
489 "One agent the caller added: its definition, version and how it was added",
490 json!([path_param("id")]),
491 answer("The agent", agent_detail),
492 ),
493 );
494 routes.insert(
495 with(paths::ANSWERS),
496 read(
497 "How the caller answered since a time (spec 3.3 §5.1 \"How you answered\")",
498 json!([query(
499 "since",
500 "Since when; default the last 7 days",
501 json!({ "type": "string", "format": "date-time" })
502 )]),
503 answer("Each answer counted", answer_summary),
504 ),
505 );
506 routes.insert(
507 with(paths::AGENT_THREADS),
508 read(
509 "The caller's threads with one agent, newest first (spec 3.3 §5.1 \"Thread history\")",
510 json!([path_param("id")]),
511 answer("The threads", agent_threads),
512 ),
513 );
514 routes.insert(
515 with(paths::AGENT_CHOICES),
516 read(
517 "What the caller may choose for an agent: the models whose key the kernel has, the packs, the areas and the colours",
518 json!([]),
519 answer("The choices", agent_choices),
520 ),
521 );
522 routes.insert(
523 with(paths::AGENT_PREVIEW),
524 write(
525 "post",
526 "Here is what Finance can do: the abilities, the risk and the digest a change applies with; closed to paired devices",
527 json!([]),
528 Some(preview_body),
529 ("200", answer("The preview", agent_preview)),
530 ),
531 );
532 routes.insert(
533 with(paths::STATUS),
534 read(
535 "The status line: mode, spend against the daily limit, quiet time, decisions",
536 json!([query(
537 "session",
538 "The session whose mode to show",
539 json!({ "type": "string" })
540 )]),
541 answer("The status line", status),
542 ),
543 );
544 routes.insert(
545 with(paths::BRIEFING),
546 read(
547 "While you were away (spec 3.3 §5.1)",
548 json!([query(
549 "since",
550 "Since when; default the last 24 hours",
551 json!({ "type": "string", "format": "date-time" })
552 )]),
553 answer("The briefing", briefing),
554 ),
555 );
556 routes.insert(
557 with(paths::COMMANDS),
558 json!({ "post": {
559 "summary": "A command, with the surface and how it was given (spec 3.3 §6, §7.2, §7.4, §11)",
560 "requestBody": { "required": true, "content": { "application/json": { "schema": request } } },
561 "responses": errors({
562 let mut ok = Map::new();
563 ok.insert("200".into(), answer("What the command did", outcome.clone()));
564 ok.insert("422".into(), problem());
565 ok
566 }),
567 } }),
568 );
569 routes.insert(
570 with(paths::TAKE_OVER),
571 json!({ "post": {
572 "summary": "Take over, then Done (spec 3.3 §8.2, §10 H2): the secret the person typed goes to the one call that asked; mounted beside a harness that takes over",
573 "parameters": [path_param("id")],
574 "requestBody": { "required": true, "content": { "application/json": { "schema": take_over } } },
575 "responses": errors({
576 let mut ok = Map::new();
577 ok.insert("200".into(), answer("answered, alreadyDecided or changed", outcome.clone()));
578 ok.insert("422".into(), problem());
579 ok
580 }),
581 } }),
582 );
583 let outcome_of = |description: &str| ("200", answer(description, outcome.clone()));
585 routes.insert(
586 with(paths::ANSWER),
587 write(
588 "post",
589 "A paired device's answer at the version it saw, as its kind's surface (spec 3.3 §7.2, §10 K2)",
590 json!([path_param("id")]),
591 Some(answer_body),
592 outcome_of("answered, alreadyDecided or changed"),
593 ),
594 );
595 routes.insert(
596 with(paths::STOP),
597 write(
598 "post",
599 "Stop all from a paired device (spec 3.3 §11 S-I10); every other caller sends a stopAll command",
600 json!([]),
601 Some(stop_body),
602 outcome_of("stopped"),
603 ),
604 );
605 routes.insert(
606 with(paths::CONFIRM_OPTIONS),
607 write(
608 "post",
609 "Starts Confirm it's you for one answer, bound to the decision, its version and the edited arguments; feature mobile (spec 3.3 §8.2)",
610 json!([path_param("id")]),
611 Some(confirm_options_body),
612 ("200", answer("The options for navigator.credentials.get", confirm_options.clone())),
613 ),
614 );
615 routes.insert(
616 with(paths::CONFIRM),
617 write(
618 "post",
619 "The passkey's assertion for the bound answer, which is then decided with presence; feature mobile (spec 3.3 §8.2)",
620 json!([path_param("id")]),
621 Some(confirm_body.clone()),
622 outcome_of("answered, alreadyDecided or changed"),
623 ),
624 );
625 routes.insert(
626 with(paths::AGENT_CONFIRM_OPTIONS),
627 write(
628 "post",
629 "Starts Confirm it's you for one change that adds an agent or lets one do more at high risk, bound to exactly that command; feature mobile (spec 3.3 §7.2)",
630 json!([]),
631 Some(agent_confirm_options_body),
632 ("200", answer("The options for navigator.credentials.get", confirm_options.clone())),
633 ),
634 );
635 routes.insert(
636 with(paths::AGENT_CONFIRM),
637 write(
638 "post",
639 "The passkey's assertion for the bound agent change, which is then made with presence; feature mobile (spec 3.3 §7.2)",
640 json!([]),
641 Some(confirm_body.clone()),
642 outcome_of("agentAdded, agentChanged or agentOutOfDate"),
643 ),
644 );
645 routes.insert(
646 with(paths::PHONE),
647 read(
648 "What the phone needs to subscribe and to confirm it is you; feature mobile (spec 3.3 §5.4)",
649 json!([]),
650 answer("The phone's settings", phone),
651 ),
652 );
653 let mut push = write(
654 "put",
655 "The phone's push subscription: https, on a browser's push service; feature mobile (spec 3.3 §5.4)",
656 json!([]),
657 Some(push_body),
658 no_content("Subscribed"),
659 );
660 push["delete"] = write(
661 "delete",
662 "Stops the phone's wake-ups",
663 json!([]),
664 None,
665 no_content("Removed"),
666 )["delete"]
667 .take();
668 routes.insert(with(paths::PHONE_PUSH), push);
669 routes.insert(
670 with(paths::PHONE_PUSH_RECEIVED),
671 write(
672 "post",
673 "The phone received a wake-up; its latency is recorded",
674 json!([]),
675 Some(received_body),
676 no_content("Recorded"),
677 ),
678 );
679 routes.insert(
680 with(paths::PHONE_PUSH_DELIVERIES),
681 read(
682 "The latest acknowledged wake-ups, for the operator",
683 json!([]),
684 answer("Deliveries, oldest first", deliveries),
685 ),
686 );
687 routes.insert(
688 with(paths::PHONE_PASSKEY_OPTIONS),
689 write(
690 "post",
691 "Starts setting up a passkey: a phone within 10 minutes of pairing, or the person at the web home (spec 3.3 §8.2)",
692 json!([]),
693 None,
694 ("200", answer("The options for navigator.credentials.create", passkey_options)),
695 ),
696 );
697 routes.insert(
698 with(paths::PHONE_PASSKEY),
699 write(
700 "post",
701 "Finishes setting up a passkey",
702 json!([]),
703 Some(registration_body),
704 no_content("Set up"),
705 ),
706 );
707 routes.insert(
708 with(paths::PHONE_PASSKEY_ONE),
709 write(
710 "delete",
711 "Removes one of the caller's computer passkeys",
712 json!([path_param("id")]),
713 None,
714 no_content("Removed"),
715 ),
716 );
717 routes.insert(
718 with(paths::PHONE_QR),
719 write(
720 "post",
721 "A pairing link into this home as a QR code, for the operator",
722 json!([]),
723 Some(qr_body),
724 (
725 "200",
726 json!({ "description": "The QR code", "content": { "image/svg+xml": { "schema": { "type": "string" } } } }),
727 ),
728 ),
729 );
730 routes.insert(
731 with(paths::PHONE_DEVICES),
732 read(
733 "Each paired device's passkey and push, and the caller's computer passkeys, for the operator",
734 json!([]),
735 answer("The devices", phone_devices),
736 ),
737 );
738 routes.insert(
741 with(voice_paths::VOICE),
742 read(
743 "The agent and the models voice can talk on, the default first (spec 3.3 §5.6); served with the `voice` feature",
744 json!([]),
745 answer("The voice models", voice_models),
746 ),
747 );
748 routes.insert(
749 with(voice_paths::SESSIONS),
750 json!({ "post": {
751 "summary": "A single-use ticket, good for 30 seconds, for the voice socket `GET /voice/socket` (spec 3.3 §5.6); served with the `voice` feature. The socket's first text message is `{\"type\":\"hello\",\"ticket\":…}`; then VoiceClientMessage up and VoiceUpdate down, and binary frames tagged 0x01 (PCM16 audio), 0x02 (camera JPEG) and 0x03 (screen JPEG)",
752 "requestBody": { "required": true, "content": { "application/json": { "schema": voice_request } } },
753 "responses": errors({
754 let mut ok = Map::new();
755 ok.insert("200".into(), json!({
756 "description": "The ticket",
757 "content": { "application/json": { "schema": voice_ticket } },
758 "x-socket": { "up": voice_message, "down": voice_update },
759 }));
760 ok
761 }),
762 } }),
763 );
764 routes.insert(
767 with(super::genui::paths::CAPABILITIES),
768 read(
769 "What this home claims of A2UI, AG-UI and MCP Apps, and the catalogs it renders; served with the `genui` feature",
770 json!([]),
771 answer("The claims", genui_capabilities),
772 ),
773 );
774 routes.insert(
775 with(super::genui::paths::CATALOGS),
776 read(
777 "Every catalog this home renders, forms first, as A2UI catalog documents of one version (1.0 unless `version` names v0.9.1); served with the `genui` feature",
778 json!([query("version", "The A2UI version of the documents: 1.0 (the default) or v0.9.1", json!({ "type": "string" }))]),
779 answer("The catalog documents", genui_catalogs),
780 ),
781 );
782 routes.insert(
783 with(super::genui::paths::FORMS),
784 read(
785 "The state of each drawn form sent in the session, from its decision and its call's result (spec 3.3 §7.4 rule 5); served with the `genui` feature",
786 json!([path_param("session")]),
787 answer("The forms sent", genui_forms),
788 ),
789 );
790 let app_params = json!([path_param("session"), path_param("call")]);
792 routes.insert(
793 with(super::genui::paths::APP),
794 read(
795 "An app an MCP server's tool showed in the session: framed on the apps origin, blocked with its reason, or not shown on this surface; served with the `genui-apps` feature",
796 json!([
797 path_param("session"),
798 path_param("call"),
799 query("surface", "The surface opening it; only the web home frames apps", surface.clone()),
800 ]),
801 answer("The app", app_open),
802 ),
803 );
804 routes.insert(
805 with(super::genui::paths::APP_REQUESTS),
806 write(
807 "post",
808 "A request the app made of the home, relayed by the page: tools/call is held for the person's decision or refused, ui/message and ui/open-link become prompts the person answers; nothing an app asks approves anything. Served with the `genui-apps` feature",
809 app_params.clone(),
810 Some(app_request),
811 ("200", answer("The JSON-RPC answer for the app, and what to show the person", app_answer)),
812 ),
813 );
814 routes.insert(
815 with(super::genui::paths::APP_MESSAGE),
816 write(
817 "post",
818 "The person pressed Send it on a message the app suggested: sent as their message, inside an untrusted-content block labelled as the app's suggestion; served with the `genui-apps` feature",
819 app_params,
820 Some(app_message),
821 ("200", answer("What the send did", outcome.clone())),
822 ),
823 );
824 routes.insert(
825 with(paths::OPENAPI),
826 json!({ "get": { "summary": "This document", "responses": { "200": { "description": "The OpenAPI document" } } } }),
827 );
828
829 let mut schemas = Value::Object(schemas);
830 clean_descriptions(&mut schemas);
831 sorted(json!({
832 "openapi": "3.1.0",
833 "info": {
834 "title": "adk-surface",
835 "version": env!("CARGO_PKG_VERSION"),
836 "description": "The engine every agent surface runs on (spec 3.3 §6): decisions, threads, agents, the status line, the briefing and commands. Generated from the Rust types; do not edit.",
837 },
838 "paths": routes,
839 "components": { "schemas": schemas },
840 }))
841}
842
843fn sorted(value: Value) -> Value {
847 match value {
848 Value::Object(map) => {
849 let mut entries: Vec<(String, Value)> = map.into_iter().collect();
850 entries.sort_by(|(a, _), (b, _)| a.cmp(b));
851 Value::Object(entries.into_iter().map(|(key, child)| (key, sorted(child))).collect())
852 }
853 Value::Array(items) => Value::Array(items.into_iter().map(sorted).collect()),
854 other => other,
855 }
856}
857
858fn clean_descriptions(value: &mut Value) {
860 match value {
861 Value::Object(map) => {
862 for (key, child) in map.iter_mut() {
863 match (key.as_str(), child) {
864 ("description", Value::String(text)) => *text = prose(text),
865 (_, child) => clean_descriptions(child),
866 }
867 }
868 }
869 Value::Array(items) => items.iter_mut().for_each(clean_descriptions),
870 _ => {}
871 }
872}
873
874fn prose(text: &str) -> String {
876 let body = text.split("\n# ").next().unwrap_or(text).trim_end();
877 let mut out = String::with_capacity(body.len());
878 let mut chars = body.chars().peekable();
879 while let Some(c) = chars.next() {
880 if c == '[' && chars.peek() == Some(&'`') {
881 let mut inner = String::new();
882 for next in chars.by_ref() {
883 if next == ']' {
884 break;
885 }
886 inner.push(next);
887 }
888 if chars.peek() == Some(&'(') {
889 for next in chars.by_ref() {
890 if next == ')' {
891 break;
892 }
893 }
894 }
895 out.push_str(&inner);
896 } else {
897 out.push(c);
898 }
899 }
900 out
901}
902
903pub fn typescript() -> String {
912 let document = openapi();
913 let mut out = String::from(
914 "// Generated from the Rust types of adk-surface by `scripts/check-surface-api.sh --write`.\n\
915 // Do not edit: CI fails when this file drifts from the Rust source (spec 3.3 §6).\n",
916 );
917 let Some(schemas) = document["components"]["schemas"].as_object() else {
918 return out;
919 };
920 for (name, schema) in schemas {
921 out.push('\n');
922 if let Some(description) = schema.get("description").and_then(Value::as_str) {
923 doc_comment(&mut out, description, "");
924 }
925 match object_body(schema, "") {
926 Some(body) => {
927 let _ = writeln!(out, "export interface {name} {body}");
928 }
929 None => {
930 let _ = writeln!(out, "export type {name} = {};", ts_type(schema, ""));
931 }
932 }
933 }
934 out
935}
936
937fn doc_comment(out: &mut String, description: &str, indent: &str) {
938 let lines: Vec<&str> = description.lines().collect();
939 if lines.len() == 1 {
940 let _ = writeln!(out, "{indent}/** {} */", lines[0].replace("*/", "*\\/"));
941 return;
942 }
943 let _ = writeln!(out, "{indent}/**");
944 for line in lines {
945 let _ = writeln!(out, "{indent} * {}", line.replace("*/", "*\\/"));
946 }
947 let _ = writeln!(out, "{indent} */");
948}
949
950fn object_body(schema: &Value, indent: &str) -> Option<String> {
952 if schema.get("type").and_then(Value::as_str) != Some("object") {
953 return None;
954 }
955 let properties = schema.get("properties")?.as_object()?;
956 let required: Vec<&str> = schema
957 .get("required")
958 .and_then(Value::as_array)
959 .map(|required| required.iter().filter_map(Value::as_str).collect())
960 .unwrap_or_default();
961 let inner = format!("{indent} ");
962 let mut body = String::from("{\n");
963 for (key, property) in properties {
964 if let Some(description) = property.get("description").and_then(Value::as_str) {
965 doc_comment(&mut body, description, &inner);
966 }
967 let optional = if required.contains(&key.as_str()) { "" } else { "?" };
968 let _ = writeln!(body, "{inner}{key}{optional}: {};", ts_type(property, &inner));
969 }
970 let _ = write!(body, "{indent}}}");
971 Some(body)
972}
973
974fn ts_type(schema: &Value, indent: &str) -> String {
975 match schema {
976 Value::Bool(true) => return "unknown".to_string(),
977 Value::Bool(false) => return "never".to_string(),
978 _ => {}
979 }
980 if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
981 return reference.rsplit('/').next().unwrap_or(reference).to_string();
982 }
983 if let Some(constant) = schema.get("const") {
984 return constant.to_string();
985 }
986 if let Some(values) = schema.get("enum").and_then(Value::as_array) {
987 return values.iter().map(Value::to_string).collect::<Vec<_>>().join(" | ");
988 }
989 for key in ["oneOf", "anyOf"] {
990 if let Some(variants) = schema.get(key).and_then(Value::as_array) {
991 let mut union: Vec<String> = Vec::new();
992 for variant in variants {
993 let merged = merge_siblings(schema, variant);
994 let text = ts_type(&merged, indent);
995 if !union.contains(&text) {
996 union.push(text);
997 }
998 }
999 return union.join(" | ");
1000 }
1001 }
1002 if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
1003 return all.iter().map(|part| ts_type(part, indent)).collect::<Vec<_>>().join(" & ");
1004 }
1005 match schema.get("type") {
1006 Some(Value::Array(types)) => {
1007 let variants: Vec<String> = types
1008 .iter()
1009 .map(|kind| {
1010 let mut single = schema.clone();
1011 if let Some(object) = single.as_object_mut() {
1012 object.insert("type".into(), kind.clone());
1013 }
1014 ts_type(&single, indent)
1015 })
1016 .collect();
1017 variants.join(" | ")
1018 }
1019 Some(Value::String(kind)) => match kind.as_str() {
1020 "string" => "string".to_string(),
1021 "integer" | "number" => "number".to_string(),
1022 "boolean" => "boolean".to_string(),
1023 "null" => "null".to_string(),
1024 "array" => {
1025 let item = schema
1026 .get("items")
1027 .map_or("unknown".to_string(), |items| ts_type(items, indent));
1028 if item.contains(' ') { format!("({item})[]") } else { format!("{item}[]") }
1029 }
1030 "object" => match object_body(schema, indent) {
1031 Some(body) => body,
1032 None => match schema.get("additionalProperties") {
1033 Some(values) if values.is_object() => {
1034 format!("Record<string, {}>", ts_type(values, indent))
1035 }
1036 _ => "Record<string, unknown>".to_string(),
1037 },
1038 },
1039 _ => "unknown".to_string(),
1040 },
1041 _ => "unknown".to_string(),
1042 }
1043}
1044
1045fn merge_siblings(parent: &Value, variant: &Value) -> Value {
1048 let (Some(parent), Some(variant_map)) = (parent.as_object(), variant.as_object()) else {
1049 return variant.clone();
1050 };
1051 let mut merged = variant_map.clone();
1052 if let Some(kind) = parent.get("type")
1053 && !merged.contains_key("type")
1054 && !merged.contains_key("$ref")
1055 {
1056 merged.insert("type".into(), kind.clone());
1057 }
1058 Value::Object(merged)
1059}
1060
1061#[cfg(test)]
1062mod tests {
1063 use super::*;
1064
1065 fn keys_sorted(value: &Value) -> bool {
1067 match value {
1068 Value::Object(map) => {
1069 map.keys().zip(map.keys().skip(1)).all(|(a, b)| a <= b)
1070 && map.values().all(keys_sorted)
1071 }
1072 Value::Array(items) => items.iter().all(keys_sorted),
1073 _ => true,
1074 }
1075 }
1076
1077 #[test]
1080 fn the_document_is_the_same_in_any_key_order() {
1081 let mut forward = Map::new();
1082 let mut backward = Map::new();
1083 for key in ["b", "a", "c"] {
1084 forward.insert(key.to_string(), json!({ "z": 1, "y": [{ "q": 2, "p": 3 }] }));
1085 }
1086 for key in ["c", "a", "b"] {
1087 let mut inner = Map::new();
1088 inner.insert("y".into(), json!([{ "p": 3, "q": 2 }]));
1089 inner.insert("z".into(), json!(1));
1090 backward.insert(key.to_string(), Value::Object(inner));
1091 }
1092 let (forward, backward) = (sorted(Value::Object(forward)), sorted(Value::Object(backward)));
1093 assert_eq!(forward.to_string(), backward.to_string());
1094 assert_eq!(
1095 forward.to_string(),
1096 r#"{"a":{"y":[{"p":3,"q":2}],"z":1},"b":{"y":[{"p":3,"q":2}],"z":1},"c":{"y":[{"p":3,"q":2}],"z":1}}"#
1097 );
1098 assert!(keys_sorted(&openapi()), "the OpenAPI document's keys are sorted");
1099 }
1100}