adk-surface 3.0.0

Agent surfaces for ADK-Rust: one engine that turns a kernel's sessions, decisions and activity into plain words for every surface, and the surfaces that show them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
//! The OpenAPI document of the web API, generated from the Rust types, and the TypeScript
//! types generated from it (spec 3.3 §6). `scripts/check-surface-api.sh` writes both under
//! `adk-surface/web/src/generated/` and CI fails when they drift from the Rust source.
//!
//! **One document in every build.** Every surface's wire types and paths — the phone's, voice's,
//! the tray's — compile under `web`, never under that surface's own feature (`mobile`,
//! `voice`), so this document is the same in every `web` build, including adk-cli's default
//! one. `tests/api_contract.rs` and `scripts/check-surface-api.sh` check it with
//! `--features web` alone.

use std::collections::BTreeMap;
use std::fmt::Write as _;

use schemars::JsonSchema;
use schemars::generate::{Contract, SchemaGenerator, SchemaSettings};
use serde_json::{Map, Value, json};

use super::phone::{
    AgentConfirmOptionsRequest, AnswerRequest, ConfirmOptions, ConfirmOptionsRequest,
    ConfirmRequest, DeliveriesResponse, PasskeyOptions, PasskeyRegistration, PhoneDevicesResponse,
    PhoneInfo, PushReceivedRequest, PushSubscriptionRequest, QrRequest, StopRequest,
};
use super::{
    AgentsResponse, CommandRequest, DecisionsResponse, QueuedResponse, SurfaceQuery,
    TakeOverRequest, ThreadResponse, paths,
};
use crate::engine::{CommandOutcome, FeedFrame};
use crate::model::{Briefing, DecisionCard, FeedEntry, StatusLine};
use crate::voice::{
    VoiceClientMessage, VoiceModels, VoiceTicket, VoiceTicketRequest, VoiceUpdate,
    paths as voice_paths,
};

// The website's document (spec 3.5 §8.2): its own, so this one is the same in every `web` build.
#[cfg(feature = "website")]
pub(super) mod website;
// The screen actions' document (spec 3.3 §2 item 7): its own, for the same reason.
#[cfg(feature = "verb-ui")]
pub(super) mod verbs;
// The Runs tab's document (spec 3.3 §12): its own, for the same reason.
#[cfg(feature = "workflow")]
pub(super) mod workflow;

fn generator(contract: Contract) -> SchemaGenerator {
    SchemaSettings::draft2020_12()
        .with(|settings| {
            settings.definitions_path = "/components/schemas".into();
            settings.meta_schema = None;
            settings.contract = contract;
        })
        .into_generator()
}

fn schema_ref<T: JsonSchema>(generator: &mut SchemaGenerator) -> Value {
    generator.subschema_for::<T>().to_value()
}

fn answer(description: &str, schema: Value) -> Value {
    json!({
        "description": description,
        "content": { "application/json": { "schema": schema } },
    })
}

fn problem() -> Value {
    json!({
        "description": "A problem document with the engine's `surface.*` code, or the source's",
        "content": { "application/problem+json": { "schema": { "type": "object" } } },
    })
}

fn errors(mut responses: Map<String, Value>) -> Value {
    for status in ["401", "403", "404"] {
        responses.insert(status.to_string(), problem());
    }
    Value::Object(responses)
}

fn read(summary: &str, parameters: Value, ok: Value) -> Value {
    let mut responses = Map::new();
    responses.insert("200".into(), ok);
    json!({ "get": { "summary": summary, "parameters": parameters, "responses": errors(responses) } })
}

fn query(name: &str, description: &str, schema: Value) -> Value {
    json!({ "name": name, "in": "query", "required": false, "description": description, "schema": schema })
}

/// A `POST` (or `PUT`, `DELETE`) route with a JSON body when `body` is set.
fn write(
    method: &str,
    summary: &str,
    parameters: Value,
    body: Option<Value>,
    ok: (&str, Value),
) -> Value {
    let mut operation = Map::new();
    operation.insert("summary".into(), json!(summary));
    operation.insert("parameters".into(), parameters);
    if let Some(body) = body {
        operation.insert(
            "requestBody".into(),
            json!({ "required": true, "content": { "application/json": { "schema": body } } }),
        );
    }
    let mut responses = Map::new();
    responses.insert(ok.0.into(), ok.1);
    responses.insert("400".into(), problem());
    operation.insert("responses".into(), errors(responses));
    let mut route = Map::new();
    route.insert(method.into(), Value::Object(operation));
    Value::Object(route)
}

fn no_content(description: &str) -> (&'static str, Value) {
    ("204", json!({ "description": description }))
}

fn path_param(name: &str) -> Value {
    json!({ "name": name, "in": "path", "required": true, "schema": { "type": "string" } })
}

/// The OpenAPI 3.1 document of [`router`](super::router), its schemas generated from the
/// Rust types (spec 3.3 §6). Paths are under `/api`.
///
/// # Example
///
/// ```rust
/// let document = adk_surface::web::openapi();
/// assert_eq!(document["openapi"], "3.1.0");
/// assert!(document["components"]["schemas"]["DecisionCard"].is_object());
/// ```
pub fn openapi() -> Value {
    let mut out = generator(Contract::Serialize);
    let decisions = schema_ref::<DecisionsResponse>(&mut out);
    let card = schema_ref::<DecisionCard>(&mut out);
    let thread = schema_ref::<ThreadResponse>(&mut out);
    let agents = schema_ref::<AgentsResponse>(&mut out);
    let status = schema_ref::<StatusLine>(&mut out);
    let briefing = schema_ref::<Briefing>(&mut out);
    let outcome = schema_ref::<CommandOutcome>(&mut out);
    let frame = schema_ref::<FeedFrame>(&mut out);
    let entry = schema_ref::<FeedEntry>(&mut out);
    let queued = schema_ref::<QueuedResponse>(&mut out);
    let phone = schema_ref::<PhoneInfo>(&mut out);
    let deliveries = schema_ref::<DeliveriesResponse>(&mut out);
    let passkey_options = schema_ref::<PasskeyOptions>(&mut out);
    let confirm_options = schema_ref::<ConfirmOptions>(&mut out);
    let phone_devices = schema_ref::<PhoneDevicesResponse>(&mut out);
    let voice_models = schema_ref::<VoiceModels>(&mut out);
    let voice_ticket = schema_ref::<VoiceTicket>(&mut out);
    let voice_update = schema_ref::<VoiceUpdate>(&mut out);
    let agent_detail = schema_ref::<crate::agents::AgentDetail>(&mut out);
    let agent_threads = schema_ref::<crate::agents::AgentThreads>(&mut out);
    let answer_summary = schema_ref::<crate::answers::AnswerSummary>(&mut out);
    let agent_choices = schema_ref::<crate::agents::AgentChoices>(&mut out);
    let agent_preview = schema_ref::<crate::agents::AgentPreview>(&mut out);
    let genui_capabilities = schema_ref::<super::genui::GenuiCapabilities>(&mut out);
    let genui_forms = schema_ref::<super::genui::FormsResponse>(&mut out);
    let genui_catalogs = schema_ref::<super::genui::CatalogDocuments>(&mut out);
    let app_open = schema_ref::<super::genui::AppOpen>(&mut out);
    let app_answer = schema_ref::<super::genui::AppAnswer>(&mut out);
    let viewer = schema_ref::<crate::viewer::ViewerView>(&mut out);
    let saved_example = schema_ref::<crate::viewer::SavedExample>(&mut out);
    let cameras_view = schema_ref::<crate::camera::CamerasView>(&mut out);
    let camera_view = schema_ref::<crate::camera::CameraView>(&mut out);
    let stage_view = schema_ref::<crate::camera::StageView>(&mut out);
    let zone_saved = schema_ref::<crate::camera::ZoneSaved>(&mut out);
    let card_raised = schema_ref::<crate::camera::CardRaised>(&mut out);
    let frame_taken = schema_ref::<crate::camera::FrameTaken>(&mut out);
    let mut schemas = out.take_definitions(true);

    let mut input = generator(Contract::Deserialize);
    let request = schema_ref::<CommandRequest>(&mut input);
    let take_over = schema_ref::<TakeOverRequest>(&mut input);
    let answer_body = schema_ref::<AnswerRequest>(&mut input);
    let stop_body = schema_ref::<StopRequest>(&mut input);
    let confirm_options_body = schema_ref::<ConfirmOptionsRequest>(&mut input);
    let confirm_body = schema_ref::<ConfirmRequest>(&mut input);
    let agent_confirm_options_body = schema_ref::<AgentConfirmOptionsRequest>(&mut input);
    let push_body = schema_ref::<PushSubscriptionRequest>(&mut input);
    let received_body = schema_ref::<PushReceivedRequest>(&mut input);
    let registration_body = schema_ref::<PasskeyRegistration>(&mut input);
    let qr_body = schema_ref::<QrRequest>(&mut input);
    let voice_request = schema_ref::<VoiceTicketRequest>(&mut input);
    let voice_message = schema_ref::<VoiceClientMessage>(&mut input);
    let preview_body = schema_ref::<crate::agents::AgentPreviewRequest>(&mut input);
    let app_request = schema_ref::<super::genui::AppRequest>(&mut input);
    let app_message = schema_ref::<super::genui::AppMessageRequest>(&mut input);
    let example_body = schema_ref::<crate::viewer::LabelledExample>(&mut input);
    let zone_body = schema_ref::<crate::camera::ZoneChange>(&mut input);
    let card_body = schema_ref::<crate::camera::RaiseCard>(&mut input);
    let freeze_body = schema_ref::<crate::camera::FreezeFrame>(&mut input);
    let surface_query = input.subschema_for::<SurfaceQuery>().to_value();
    for (name, schema) in input.take_definitions(true) {
        schemas.entry(name).or_insert(schema);
    }
    let surface = surface_query["properties"]["surface"].clone();

    let mut routes = BTreeMap::new();
    let with = |path: &str| format!("/api{path}");
    routes.insert(
        with(paths::DECISIONS),
        read(
            "The caller's open decisions as cards (spec 3.3 §7.1)",
            json!([
                query("surface", "The surface the answers are computed for", surface.clone()),
                query("session", "Only this session's decisions", json!({ "type": "string" })),
            ]),
            answer("Open decisions, oldest first", decisions),
        ),
    );
    routes.insert(
        with(paths::DECISION),
        read(
            "One decision: waiting, or decided with who, where and when",
            json!([
                path_param("id"),
                query("surface", "The surface the answers are computed for", surface.clone())
            ]),
            answer("The decision", card),
        ),
    );
    routes.insert(
        with(paths::EVIDENCE),
        json!({ "get": {
            "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",
            "parameters": [
                path_param("id"),
                { "name": "index", "in": "path", "required": true, "description": "The image's place in the card's `media.images`", "schema": { "type": "integer", "minimum": 0 } },
                query("surface", "The surface asking", surface.clone()),
            ],
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), json!({
                    "description": "The image",
                    "content": {
                        "image/png": { "schema": { "type": "string", "format": "binary" } },
                        "image/jpeg": { "schema": { "type": "string", "format": "binary" } },
                        "image/webp": { "schema": { "type": "string", "format": "binary" } }
                    }
                }));
                ok
            }),
        } }),
    );
    let image_param = json!({
        "name": "image", "in": "path", "required": true,
        "description": "A `sha256:` digest, or the name of an image the session holds",
        "schema": { "type": "string" },
    });
    routes.insert(
        with(paths::VISION_VIEW),
        read(
            "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",
            json!([
                path_param("session"),
                image_param.clone(),
                query("surface", "The surface asking", surface.clone()),
                query("answer", "The answer to show, by its call; the newest otherwise", json!({ "type": "string" })),
                query("compare", "A second answer to show beside it", json!({ "type": "string" })),
            ]),
            answer("The viewer", viewer),
        ),
    );
    routes.insert(
        with(paths::VISION_IMAGE),
        json!({ "get": {
            "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",
            "parameters": [path_param("session"), image_param, query("surface", "The surface asking", surface.clone())],
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), json!({
                    "description": "The image",
                    "content": {
                        "image/png": { "schema": { "type": "string", "format": "binary" } },
                        "image/jpeg": { "schema": { "type": "string", "format": "binary" } },
                        "image/webp": { "schema": { "type": "string", "format": "binary" } }
                    }
                }));
                ok
            }),
        } }),
    );
    routes.insert(
        with(paths::VISION_REGIONS),
        read(
            "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",
            json!([
                path_param("session"),
                path_param("answer"),
                query("surface", "The surface asking", surface.clone()),
                query("with", "A second answer, exported beside it", json!({ "type": "string" })),
            ]),
            answer("The RegionSet, or an array of two", json!({ "type": ["object", "array"] })),
        ),
    );
    routes.insert(
        with(paths::VISION_EXAMPLES),
        write(
            "post",
            "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",
            json!([path_param("session")]),
            Some(example_body),
            ("200", answer("Where it was saved", saved_example)),
        ),
    );
    // The live camera surface (spec 3.7 §8.2): only the cameras of the caller's own sessions.
    routes.insert(
        with(paths::CAMERAS),
        read(
            "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",
            json!([query("surface", "The surface asking", surface.clone())]),
            answer("The cameras", cameras_view),
        ),
    );
    let camera_param = json!({
        "name": "camera", "in": "path", "required": true,
        "description": "The camera's id, such as `line-2`",
        "schema": { "type": "string" },
    });
    routes.insert(
        with(paths::CAMERA),
        read(
            "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",
            json!([camera_param.clone(), query("surface", "The surface asking", surface.clone())]),
            answer("The camera", camera_view.clone()),
        ),
    );
    routes.insert(
        with(paths::CAMERA_FRAME),
        json!({ "get": {
            "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",
            "parameters": [
                camera_param.clone(),
                { "name": "frame", "in": "path", "required": true, "description": "The frame's `sha256:` digest", "schema": { "type": "string" } },
                query("surface", "The surface asking", surface.clone()),
            ],
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), json!({
                    "description": "The frame",
                    "content": {
                        "image/jpeg": { "schema": { "type": "string", "format": "binary" } },
                        "image/png": { "schema": { "type": "string", "format": "binary" } }
                    }
                }));
                ok
            }),
        } }),
    );
    routes.insert(
        with(paths::CAMERA_FEED),
        json!({ "get": {
            "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",
            "parameters": [camera_param.clone(), query("surface", "The surface asking", surface.clone())],
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), json!({
                    "description": "`text/event-stream`; a `frame` event's data is a StageView",
                    "content": { "text/event-stream": { "schema": stage_view.clone() } },
                }));
                ok
            }),
        } }),
    );
    routes.insert(
        with(paths::CAMERA_FRAMES),
        json!({ "post": {
            "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",
            "parameters": [camera_param.clone(), query("surface", "The surface asking", surface.clone())],
            "requestBody": {
                "required": true,
                "content": {
                    "image/jpeg": { "schema": { "type": "string", "format": "binary" } },
                    "image/png": { "schema": { "type": "string", "format": "binary" } },
                    "image/webp": { "schema": { "type": "string", "format": "binary" } }
                }
            },
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), answer("What became of the frame", frame_taken));
                ok.insert("400".into(), problem());
                ok.insert("413".into(), problem());
                ok.insert("429".into(), problem());
                ok
            }),
        } }),
    );
    for (path, summary) in [
        (
            paths::CAMERA_ON,
            "Switch a camera on (board choice C2); recorded first. A paired phone needs the decide scope",
        ),
        (
            paths::CAMERA_OFF,
            "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",
        ),
        (paths::CAMERA_STOP, "End a camera's stream (board choice C2); recorded"),
        (paths::CAMERA_RETRY, "Try a lost camera again now (board choice C6); recorded"),
    ] {
        routes.insert(
            with(path),
            write(
                "post",
                summary,
                json!([
                    camera_param.clone(),
                    query("surface", "The surface asking", surface.clone())
                ]),
                None,
                ("200", answer("The camera now", camera_view.clone())),
            ),
        );
    }
    routes.insert(
        with(paths::CAMERA_ZONE),
        write(
            "put",
            "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",
            json!([camera_param.clone(), path_param("zone")]),
            Some(zone_body),
            ("200", answer("The zone now", zone_saved)),
        ),
    );
    routes.insert(
        with(paths::CAMERA_FREEZE),
        write(
            "post",
            "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",
            json!([camera_param.clone(), query("surface", "The surface asking", surface.clone())]),
            Some(freeze_body),
            ("200", answer("The frozen frame's picture", stage_view.clone())),
        ),
    );
    routes.insert(
        with(paths::CAMERA_CARDS),
        write(
            "post",
            "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",
            json!([camera_param, query("surface", "The surface asking", surface.clone())]),
            Some(card_body),
            ("200", answer("The evidence kept and what sending the card did", card_raised)),
        ),
    );
    routes.insert(
        with(paths::THREAD),
        read(
            "The session's entries, numbered by their position in the session store",
            json!([path_param("session")]),
            answer("The thread", thread),
        ),
    );
    routes.insert(
        with(paths::FEED),
        json!({ "get": {
            "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",
            "parameters": [
                path_param("session"),
                query("after", "Resume after this seq when no Last-Event-ID header is sent", json!({ "type": "integer", "minimum": 0 })),
                { "name": "Last-Event-ID", "in": "header", "required": false, "schema": { "type": "string" } },
            ],
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), json!({
                    "description": "`text/event-stream` of FeedFrame payloads; an `entry` event's data is a FeedEntry",
                    "content": { "text/event-stream": { "schema": frame, "x-entry": entry } },
                }));
                ok
            }),
        } }),
    );
    routes.insert(
        with(paths::QUEUED),
        read(
            "What the caller typed while a decision of the session was open, sent once it is answered (spec 3.3 §7.4 rule 2)",
            json!([path_param("session")]),
            answer("The queued input, oldest first", queued),
        ),
    );
    routes.insert(
        with(paths::AGENTS),
        read("The caller's agents (spec 3.3 §8.1)", json!([]), answer("The roster", agents)),
    );
    // Agents a person adds (spec 3.3 §5.7); every change goes through `POST /surface/commands`.
    routes.insert(
        with(paths::AGENT),
        read(
            "One agent the caller added: its definition, version and how it was added",
            json!([path_param("id")]),
            answer("The agent", agent_detail),
        ),
    );
    routes.insert(
        with(paths::ANSWERS),
        read(
            "How the caller answered since a time (spec 3.3 §5.1 \"How you answered\")",
            json!([query(
                "since",
                "Since when; default the last 7 days",
                json!({ "type": "string", "format": "date-time" })
            )]),
            answer("Each answer counted", answer_summary),
        ),
    );
    routes.insert(
        with(paths::AGENT_THREADS),
        read(
            "The caller's threads with one agent, newest first (spec 3.3 §5.1 \"Thread history\")",
            json!([path_param("id")]),
            answer("The threads", agent_threads),
        ),
    );
    routes.insert(
        with(paths::AGENT_CHOICES),
        read(
            "What the caller may choose for an agent: the models whose key the kernel has, the packs, the areas and the colours",
            json!([]),
            answer("The choices", agent_choices),
        ),
    );
    routes.insert(
        with(paths::AGENT_PREVIEW),
        write(
            "post",
            "Here is what Finance can do: the abilities, the risk and the digest a change applies with; closed to paired devices",
            json!([]),
            Some(preview_body),
            ("200", answer("The preview", agent_preview)),
        ),
    );
    routes.insert(
        with(paths::STATUS),
        read(
            "The status line: mode, spend against the daily limit, quiet time, decisions",
            json!([query(
                "session",
                "The session whose mode to show",
                json!({ "type": "string" })
            )]),
            answer("The status line", status),
        ),
    );
    routes.insert(
        with(paths::BRIEFING),
        read(
            "While you were away (spec 3.3 §5.1)",
            json!([query(
                "since",
                "Since when; default the last 24 hours",
                json!({ "type": "string", "format": "date-time" })
            )]),
            answer("The briefing", briefing),
        ),
    );
    routes.insert(
        with(paths::COMMANDS),
        json!({ "post": {
            "summary": "A command, with the surface and how it was given (spec 3.3 §6, §7.2, §7.4, §11)",
            "requestBody": { "required": true, "content": { "application/json": { "schema": request } } },
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), answer("What the command did", outcome.clone()));
                ok.insert("422".into(), problem());
                ok
            }),
        } }),
    );
    routes.insert(
        with(paths::TAKE_OVER),
        json!({ "post": {
            "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",
            "parameters": [path_param("id")],
            "requestBody": { "required": true, "content": { "application/json": { "schema": take_over } } },
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), answer("answered, alreadyDecided or changed", outcome.clone()));
                ok.insert("422".into(), problem());
                ok
            }),
        } }),
    );
    // Paired devices and the phone (spec 3.3 §5.4, §8.2, §10 K2).
    let outcome_of = |description: &str| ("200", answer(description, outcome.clone()));
    routes.insert(
        with(paths::ANSWER),
        write(
            "post",
            "A paired device's answer at the version it saw, as its kind's surface (spec 3.3 §7.2, §10 K2)",
            json!([path_param("id")]),
            Some(answer_body),
            outcome_of("answered, alreadyDecided or changed"),
        ),
    );
    routes.insert(
        with(paths::STOP),
        write(
            "post",
            "Stop all from a paired device (spec 3.3 §11 S-I10); every other caller sends a stopAll command",
            json!([]),
            Some(stop_body),
            outcome_of("stopped"),
        ),
    );
    routes.insert(
        with(paths::CONFIRM_OPTIONS),
        write(
            "post",
            "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)",
            json!([path_param("id")]),
            Some(confirm_options_body),
            ("200", answer("The options for navigator.credentials.get", confirm_options.clone())),
        ),
    );
    routes.insert(
        with(paths::CONFIRM),
        write(
            "post",
            "The passkey's assertion for the bound answer, which is then decided with presence; feature mobile (spec 3.3 §8.2)",
            json!([path_param("id")]),
            Some(confirm_body.clone()),
            outcome_of("answered, alreadyDecided or changed"),
        ),
    );
    routes.insert(
        with(paths::AGENT_CONFIRM_OPTIONS),
        write(
            "post",
            "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)",
            json!([]),
            Some(agent_confirm_options_body),
            ("200", answer("The options for navigator.credentials.get", confirm_options.clone())),
        ),
    );
    routes.insert(
        with(paths::AGENT_CONFIRM),
        write(
            "post",
            "The passkey's assertion for the bound agent change, which is then made with presence; feature mobile (spec 3.3 §7.2)",
            json!([]),
            Some(confirm_body.clone()),
            outcome_of("agentAdded, agentChanged or agentOutOfDate"),
        ),
    );
    routes.insert(
        with(paths::PHONE),
        read(
            "What the phone needs to subscribe and to confirm it is you; feature mobile (spec 3.3 §5.4)",
            json!([]),
            answer("The phone's settings", phone),
        ),
    );
    let mut push = write(
        "put",
        "The phone's push subscription: https, on a browser's push service; feature mobile (spec 3.3 §5.4)",
        json!([]),
        Some(push_body),
        no_content("Subscribed"),
    );
    push["delete"] = write(
        "delete",
        "Stops the phone's wake-ups",
        json!([]),
        None,
        no_content("Removed"),
    )["delete"]
        .take();
    routes.insert(with(paths::PHONE_PUSH), push);
    routes.insert(
        with(paths::PHONE_PUSH_RECEIVED),
        write(
            "post",
            "The phone received a wake-up; its latency is recorded",
            json!([]),
            Some(received_body),
            no_content("Recorded"),
        ),
    );
    routes.insert(
        with(paths::PHONE_PUSH_DELIVERIES),
        read(
            "The latest acknowledged wake-ups, for the operator",
            json!([]),
            answer("Deliveries, oldest first", deliveries),
        ),
    );
    routes.insert(
        with(paths::PHONE_PASSKEY_OPTIONS),
        write(
            "post",
            "Starts setting up a passkey: a phone within 10 minutes of pairing, or the person at the web home (spec 3.3 §8.2)",
            json!([]),
            None,
            ("200", answer("The options for navigator.credentials.create", passkey_options)),
        ),
    );
    routes.insert(
        with(paths::PHONE_PASSKEY),
        write(
            "post",
            "Finishes setting up a passkey",
            json!([]),
            Some(registration_body),
            no_content("Set up"),
        ),
    );
    routes.insert(
        with(paths::PHONE_PASSKEY_ONE),
        write(
            "delete",
            "Removes one of the caller's computer passkeys",
            json!([path_param("id")]),
            None,
            no_content("Removed"),
        ),
    );
    routes.insert(
        with(paths::PHONE_QR),
        write(
            "post",
            "A pairing link into this home as a QR code, for the operator",
            json!([]),
            Some(qr_body),
            (
                "200",
                json!({ "description": "The QR code", "content": { "image/svg+xml": { "schema": { "type": "string" } } } }),
            ),
        ),
    );
    routes.insert(
        with(paths::PHONE_DEVICES),
        read(
            "Each paired device's passkey and push, and the caller's computer passkeys, for the operator",
            json!([]),
            answer("The devices", phone_devices),
        ),
    );
    // Voice (spec 3.3 §5.6): its types are in every build's document; the routes are served
    // with the `voice` feature.
    routes.insert(
        with(voice_paths::VOICE),
        read(
            "The agent and the models voice can talk on, the default first (spec 3.3 §5.6); served with the `voice` feature",
            json!([]),
            answer("The voice models", voice_models),
        ),
    );
    routes.insert(
        with(voice_paths::SESSIONS),
        json!({ "post": {
            "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)",
            "requestBody": { "required": true, "content": { "application/json": { "schema": voice_request } } },
            "responses": errors({
                let mut ok = Map::new();
                ok.insert("200".into(), json!({
                    "description": "The ticket",
                    "content": { "application/json": { "schema": voice_ticket } },
                    "x-socket": { "up": voice_message, "down": voice_update },
                }));
                ok
            }),
        } }),
    );
    // Agent-drawn UI (spec 3.3 §6.1 `genui`): its types are in every build's document; the
    // routes are served with the `genui` feature. A drawn form is sent with `submitDrawn`.
    routes.insert(
        with(super::genui::paths::CAPABILITIES),
        read(
            "What this home claims of A2UI, AG-UI and MCP Apps, and the catalogs it renders; served with the `genui` feature",
            json!([]),
            answer("The claims", genui_capabilities),
        ),
    );
    routes.insert(
        with(super::genui::paths::CATALOGS),
        read(
            "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",
            json!([query("version", "The A2UI version of the documents: 1.0 (the default) or v0.9.1", json!({ "type": "string" }))]),
            answer("The catalog documents", genui_catalogs),
        ),
    );
    routes.insert(
        with(super::genui::paths::FORMS),
        read(
            "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",
            json!([path_param("session")]),
            answer("The forms sent", genui_forms),
        ),
    );
    // Apps from MCP servers (spec 3.3 §6.1 `genui-apps`): served with that feature.
    let app_params = json!([path_param("session"), path_param("call")]);
    routes.insert(
        with(super::genui::paths::APP),
        read(
            "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",
            json!([
                path_param("session"),
                path_param("call"),
                query("surface", "The surface opening it; only the web home frames apps", surface.clone()),
            ]),
            answer("The app", app_open),
        ),
    );
    routes.insert(
        with(super::genui::paths::APP_REQUESTS),
        write(
            "post",
            "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",
            app_params.clone(),
            Some(app_request),
            ("200", answer("The JSON-RPC answer for the app, and what to show the person", app_answer)),
        ),
    );
    routes.insert(
        with(super::genui::paths::APP_MESSAGE),
        write(
            "post",
            "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",
            app_params,
            Some(app_message),
            ("200", answer("What the send did", outcome.clone())),
        ),
    );
    routes.insert(
        with(paths::OPENAPI),
        json!({ "get": { "summary": "This document", "responses": { "200": { "description": "The OpenAPI document" } } } }),
    );

    let mut schemas = Value::Object(schemas);
    clean_descriptions(&mut schemas);
    sorted(json!({
        "openapi": "3.1.0",
        "info": {
            "title": "adk-surface",
            "version": env!("CARGO_PKG_VERSION"),
            "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.",
        },
        "paths": routes,
        "components": { "schemas": schemas },
    }))
}

/// `value` with every object's keys in sorted order, as `serde_json`'s default map keeps
/// them: the same document, and the same TypeScript, whether or not a crate in the build
/// turns on `serde_json/preserve_order`, which keeps keys in insertion order.
fn sorted(value: Value) -> Value {
    match value {
        Value::Object(map) => {
            let mut entries: Vec<(String, Value)> = map.into_iter().collect();
            entries.sort_by(|(a, _), (b, _)| a.cmp(b));
            Value::Object(entries.into_iter().map(|(key, child)| (key, sorted(child))).collect())
        }
        Value::Array(items) => Value::Array(items.into_iter().map(sorted).collect()),
        other => other,
    }
}

/// Keeps each description's prose: no rustdoc sections, no intra-doc link targets.
fn clean_descriptions(value: &mut Value) {
    match value {
        Value::Object(map) => {
            for (key, child) in map.iter_mut() {
                match (key.as_str(), child) {
                    ("description", Value::String(text)) => *text = prose(text),
                    (_, child) => clean_descriptions(child),
                }
            }
        }
        Value::Array(items) => items.iter_mut().for_each(clean_descriptions),
        _ => {}
    }
}

/// `text` up to its first rustdoc heading, with `[`X`](path)` and `[`X`]` as `` `X` ``.
fn prose(text: &str) -> String {
    let body = text.split("\n# ").next().unwrap_or(text).trim_end();
    let mut out = String::with_capacity(body.len());
    let mut chars = body.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '[' && chars.peek() == Some(&'`') {
            let mut inner = String::new();
            for next in chars.by_ref() {
                if next == ']' {
                    break;
                }
                inner.push(next);
            }
            if chars.peek() == Some(&'(') {
                for next in chars.by_ref() {
                    if next == ')' {
                        break;
                    }
                }
            }
            out.push_str(&inner);
        } else {
            out.push(c);
        }
    }
    out
}

/// TypeScript declarations of every schema in [`openapi`], for the web app (spec 3.3 §6).
///
/// # Example
///
/// ```rust
/// let ts = adk_surface::web::typescript();
/// assert!(ts.contains("export interface DecisionCard {"));
/// ```
pub fn typescript() -> String {
    let document = openapi();
    let mut out = String::from(
        "// Generated from the Rust types of adk-surface by `scripts/check-surface-api.sh --write`.\n\
         // Do not edit: CI fails when this file drifts from the Rust source (spec 3.3 §6).\n",
    );
    let Some(schemas) = document["components"]["schemas"].as_object() else {
        return out;
    };
    for (name, schema) in schemas {
        out.push('\n');
        if let Some(description) = schema.get("description").and_then(Value::as_str) {
            doc_comment(&mut out, description, "");
        }
        match object_body(schema, "") {
            Some(body) => {
                let _ = writeln!(out, "export interface {name} {body}");
            }
            None => {
                let _ = writeln!(out, "export type {name} = {};", ts_type(schema, ""));
            }
        }
    }
    out
}

fn doc_comment(out: &mut String, description: &str, indent: &str) {
    let lines: Vec<&str> = description.lines().collect();
    if lines.len() == 1 {
        let _ = writeln!(out, "{indent}/** {} */", lines[0].replace("*/", "*\\/"));
        return;
    }
    let _ = writeln!(out, "{indent}/**");
    for line in lines {
        let _ = writeln!(out, "{indent} * {}", line.replace("*/", "*\\/"));
    }
    let _ = writeln!(out, "{indent} */");
}

/// `{ a: T; b?: U }` for an object schema with properties.
fn object_body(schema: &Value, indent: &str) -> Option<String> {
    if schema.get("type").and_then(Value::as_str) != Some("object") {
        return None;
    }
    let properties = schema.get("properties")?.as_object()?;
    let required: Vec<&str> = schema
        .get("required")
        .and_then(Value::as_array)
        .map(|required| required.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    let inner = format!("{indent}  ");
    let mut body = String::from("{\n");
    for (key, property) in properties {
        if let Some(description) = property.get("description").and_then(Value::as_str) {
            doc_comment(&mut body, description, &inner);
        }
        let optional = if required.contains(&key.as_str()) { "" } else { "?" };
        let _ = writeln!(body, "{inner}{key}{optional}: {};", ts_type(property, &inner));
    }
    let _ = write!(body, "{indent}}}");
    Some(body)
}

fn ts_type(schema: &Value, indent: &str) -> String {
    match schema {
        Value::Bool(true) => return "unknown".to_string(),
        Value::Bool(false) => return "never".to_string(),
        _ => {}
    }
    if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
        return reference.rsplit('/').next().unwrap_or(reference).to_string();
    }
    if let Some(constant) = schema.get("const") {
        return constant.to_string();
    }
    if let Some(values) = schema.get("enum").and_then(Value::as_array) {
        return values.iter().map(Value::to_string).collect::<Vec<_>>().join(" | ");
    }
    for key in ["oneOf", "anyOf"] {
        if let Some(variants) = schema.get(key).and_then(Value::as_array) {
            let mut union: Vec<String> = Vec::new();
            for variant in variants {
                let merged = merge_siblings(schema, variant);
                let text = ts_type(&merged, indent);
                if !union.contains(&text) {
                    union.push(text);
                }
            }
            return union.join(" | ");
        }
    }
    if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
        return all.iter().map(|part| ts_type(part, indent)).collect::<Vec<_>>().join(" & ");
    }
    match schema.get("type") {
        Some(Value::Array(types)) => {
            let variants: Vec<String> = types
                .iter()
                .map(|kind| {
                    let mut single = schema.clone();
                    if let Some(object) = single.as_object_mut() {
                        object.insert("type".into(), kind.clone());
                    }
                    ts_type(&single, indent)
                })
                .collect();
            variants.join(" | ")
        }
        Some(Value::String(kind)) => match kind.as_str() {
            "string" => "string".to_string(),
            "integer" | "number" => "number".to_string(),
            "boolean" => "boolean".to_string(),
            "null" => "null".to_string(),
            "array" => {
                let item = schema
                    .get("items")
                    .map_or("unknown".to_string(), |items| ts_type(items, indent));
                if item.contains(' ') { format!("({item})[]") } else { format!("{item}[]") }
            }
            "object" => match object_body(schema, indent) {
                Some(body) => body,
                None => match schema.get("additionalProperties") {
                    Some(values) if values.is_object() => {
                        format!("Record<string, {}>", ts_type(values, indent))
                    }
                    _ => "Record<string, unknown>".to_string(),
                },
            },
            _ => "unknown".to_string(),
        },
        _ => "unknown".to_string(),
    }
}

/// A `oneOf` variant with the parent's object keywords it inherits (an internally tagged
/// enum's shared `type: object`).
fn merge_siblings(parent: &Value, variant: &Value) -> Value {
    let (Some(parent), Some(variant_map)) = (parent.as_object(), variant.as_object()) else {
        return variant.clone();
    };
    let mut merged = variant_map.clone();
    if let Some(kind) = parent.get("type")
        && !merged.contains_key("type")
        && !merged.contains_key("$ref")
    {
        merged.insert("type".into(), kind.clone());
    }
    Value::Object(merged)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every object of `value` lists its keys in sorted order.
    fn keys_sorted(value: &Value) -> bool {
        match value {
            Value::Object(map) => {
                map.keys().zip(map.keys().skip(1)).all(|(a, b)| a <= b)
                    && map.values().all(keys_sorted)
            }
            Value::Array(items) => items.iter().all(keys_sorted),
            _ => true,
        }
    }

    /// Keys inserted in any order give the same document: with `serde_json/preserve_order`
    /// on, a map keeps insertion order, and `sorted` puts it back.
    #[test]
    fn the_document_is_the_same_in_any_key_order() {
        let mut forward = Map::new();
        let mut backward = Map::new();
        for key in ["b", "a", "c"] {
            forward.insert(key.to_string(), json!({ "z": 1, "y": [{ "q": 2, "p": 3 }] }));
        }
        for key in ["c", "a", "b"] {
            let mut inner = Map::new();
            inner.insert("y".into(), json!([{ "p": 3, "q": 2 }]));
            inner.insert("z".into(), json!(1));
            backward.insert(key.to_string(), Value::Object(inner));
        }
        let (forward, backward) = (sorted(Value::Object(forward)), sorted(Value::Object(backward)));
        assert_eq!(forward.to_string(), backward.to_string());
        assert_eq!(
            forward.to_string(),
            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}}"#
        );
        assert!(keys_sorted(&openapi()), "the OpenAPI document's keys are sorted");
    }
}