bobby-browser-client 0.17.0

Typed HTTP client and /v1 wire types for the Bobby Browser runtime
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
//! Command outcomes, evidence, and accessibility snapshot nodes.

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{AttemptId, CommandId, PageId};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ControlActionEvidence {
    pub operation: crate::FormControlOperation,
    pub target: crate::FormControlTarget,
    pub state: crate::FormControlState,
    pub validity: crate::FormControlValidity,
    pub node_replaced: bool,
    /// Controls that appeared because of this action (conditional fields,
    /// e.g. a billing-cycle select revealed by a plan choice). Read this
    /// before re-snapshotting: the targets are passable to `control_action`
    /// verbatim.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub revealed_controls: Vec<crate::forms::RevealedControl>,
}

/// Semantic target for accessibility-based commands (role + accessible name).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AccessibilityTarget {
    pub role: String,
    pub accessible_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ordinal: Option<usize>,
    /// Frame hops from the main frame to the document holding this node;
    /// empty for main-frame nodes. Segments are the same role/name/ordinal
    /// shape `FormControlTarget.frame_path` resolves, so the target can be
    /// passed verbatim to `control_action`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub frame_path: Vec<crate::forms::SemanticTargetSegment>,
}

/// Where the retained page context says a described control is.
///
/// Must stay in `types`: the crate-boundary guard requires every wire-advertised
/// shape to be a `types::` one so the schema parity guard covers it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContextAnswer {
    pub target: AccessibilityTarget,
    pub confidence: f32,
    /// Whether the answer was observed live this session (stamped with the
    /// page's generation) or remembered from a prior session's persisted
    /// context. Additive; absent means a live generation-0 answer.
    #[serde(default)]
    pub observed_at: ContextObservedAt,
    /// How the underlying record entered the graph. Absent for live answers
    /// (always direct observation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<ContextAnswerSource>,
}

impl ContextAnswer {
    /// Retained and live context answers both originate from page observations.
    pub fn page_derived(&self) -> bool {
        true
    }
}

impl Default for ContextObservedAt {
    fn default() -> Self {
        Self::Generation { generation: 0 }
    }
}

/// Provenance of a [`ContextAnswer`]: live-observed under a page generation,
/// or remembered from the persisted per-profile context store.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ContextObservedAt {
    Generation { generation: u64 },
    Persisted,
}

/// How a remembered control record entered the graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum ContextAnswerSource {
    Observed,
    VisionPromoted,
}

/// The remembered form structure around a located control (`context_neighbors`).
/// Structure only: roles, names, ordinals, and per-intent counters — never
/// values, page text, or timestamps finer than a day.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContextNeighbors {
    pub answer: ContextAnswer,
    /// Key of the enclosing form within the remembered page.
    pub form: String,
    /// Pattern of the remembered page the form belongs to.
    pub page_pattern: String,
    pub controls: Vec<ContextNeighborControl>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContextNeighborControl {
    pub role: String,
    pub accessible_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ordinal: Option<usize>,
    /// Per-intent-kind counters, keyed by intent kind.
    pub intents: std::collections::BTreeMap<String, ContextNeighborStats>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContextNeighborStats {
    pub success_count: u64,
    pub failure_count: u64,
    /// Days since the Unix epoch of the last verified success.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_verified_day: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<ContextAnswerSource>,
}

/// One remembered site's structure: page pattern → form key → controls.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContextSiteView {
    pub site_key: String,
    pub pages: std::collections::BTreeMap<
        String,
        std::collections::BTreeMap<String, Vec<ContextNeighborControl>>,
    >,
}

/// Machine-readable reason returned when retained context has no answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum ContextMissReason {
    #[serde(rename = "notRemembered")]
    NotRemembered,
}

/// Repair step returned with a retained-context miss.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum ContextNextStep {
    #[serde(rename = "a11y_snapshot")]
    A11ySnapshot,
}

/// Response from `GET /v1/context/ask`.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ContextAskResponse {
    pub answer: Option<ContextAnswer>,
    pub hit: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<ContextMissReason>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_step: Option<ContextNextStep>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ContextAskResponseWire {
    answer: Option<ContextAnswer>,
    hit: bool,
    #[serde(default)]
    reason: Option<ContextMissReason>,
    #[serde(default)]
    next_step: Option<ContextNextStep>,
    #[serde(default)]
    page_derived: Option<bool>,
}

impl<'de> Deserialize<'de> for ContextAskResponse {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let wire = ContextAskResponseWire::deserialize(deserializer)?;
        if wire.page_derived == Some(false) {
            return Err(serde::de::Error::custom("pageDerived must be true"));
        }
        Ok(Self {
            answer: wire.answer,
            hit: wire.hit,
            reason: wire.reason,
            next_step: wire.next_step,
        })
    }
}

impl ContextAskResponse {
    pub fn page_derived(&self) -> bool {
        true
    }
}

/// Response from `GET /v1/context/neighbors`.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ContextNeighborsResponse {
    pub neighbors: Option<ContextNeighbors>,
    pub hit: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<ContextMissReason>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_step: Option<ContextNextStep>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ContextNeighborsResponseWire {
    neighbors: Option<ContextNeighbors>,
    hit: bool,
    #[serde(default)]
    reason: Option<ContextMissReason>,
    #[serde(default)]
    next_step: Option<ContextNextStep>,
    #[serde(default)]
    page_derived: Option<bool>,
}

impl<'de> Deserialize<'de> for ContextNeighborsResponse {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let wire = ContextNeighborsResponseWire::deserialize(deserializer)?;
        if wire.page_derived == Some(false) {
            return Err(serde::de::Error::custom("pageDerived must be true"));
        }
        Ok(Self {
            neighbors: wire.neighbors,
            hit: wire.hit,
            reason: wire.reason,
            next_step: wire.next_step,
        })
    }
}

impl ContextNeighborsResponse {
    pub fn page_derived(&self) -> bool {
        true
    }
}

/// Response from `GET /v1/context/site/{key}`.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ContextSiteResponse {
    pub site: Option<ContextSiteView>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ContextSiteResponseWire {
    site: Option<ContextSiteView>,
    #[serde(default)]
    page_derived: Option<bool>,
}

impl<'de> Deserialize<'de> for ContextSiteResponse {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let wire = ContextSiteResponseWire::deserialize(deserializer)?;
        if wire.page_derived == Some(false) {
            return Err(serde::de::Error::custom("pageDerived must be true"));
        }
        Ok(Self { site: wire.site })
    }
}

impl ContextSiteResponse {
    pub fn page_derived(&self) -> bool {
        true
    }
}

/// One node in an `accessibilitySnapshot` result tree.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AccessibilityNode {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<AccessibilityTarget>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub required: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub read_only: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub invalid: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checked: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub autocomplete: Option<String>,
    /// Link destination, when the engine reports one for this node. Lets an
    /// agent feed `download_url` (or navigate) without an HTML round-trip.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value_min: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value_max: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<AccessibilityNode>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(
    tag = "status",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum CommandOutcome {
    Completed {
        command_id: CommandId,
        evidence: Vec<Evidence>,
    },
    RetryableFailure {
        command_id: CommandId,
        error: CommandError,
    },
    NeedsReconciliation {
        command_id: CommandId,
        error: CommandError,
        evidence: Vec<Evidence>,
    },
    PolicyDenied {
        command_id: CommandId,
        error: CommandError,
    },
    ResourceExhausted {
        command_id: CommandId,
        error: CommandError,
        retry_after_ms: u64,
    },
    Restarted {
        command_id: CommandId,
        prior_attempt_id: AttemptId,
        attempt_id: AttemptId,
        reason: String,
        #[serde(default)]
        evidence: Vec<Evidence>,
    },
    Failed {
        command_id: CommandId,
        error: CommandError,
        #[serde(default)]
        evidence: Vec<Evidence>,
    },
}

/// Upper bound on [`Evidence::Wait`]'s `observed` value, in characters.
///
/// A verification value -- a matched label, a URL, a ready state -- not page
/// text. Truncation is on a character boundary; a byte index can land inside a
/// multi-byte codepoint and panic, which is exactly how extraction used to die
/// on non-ASCII pages.
pub const MAX_WAIT_OBSERVED_CHARS: usize = 512;

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum SubmitSettlementOutcome {
    Settled,
    ValidationRejected,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(
    tag = "kind",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum Evidence {
    ExecutionPath {
        path: ExecutionPath,
        reason: ExecutionReason,
        state_version: u64,
        elapsed_ms: u64,
        bytes: Option<u64>,
        sha256: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        final_url: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        content_type: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        status: Option<u16>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        redirect_chain: Vec<String>,
    },
    Navigation {
        url: String,
        title: String,
    },
    Inspection {
        selector: Option<String>,
        url: String,
        title: String,
        text: String,
        html: Option<String>,
    },
    /// Result of a boundary submit that used `networkQuiet` as its
    /// postcondition. This classifies the settled page without requiring the
    /// caller to predict confirmation copy or risk a second submit.
    SubmitSettlement {
        outcome: SubmitSettlementOutcome,
    },
    Element {
        selector: String,
        text: Option<String>,
    },
    Upload {
        selector: String,
        paths: Vec<String>,
    },
    Page {
        page_id: PageId,
        url: String,
        title: String,
    },
    /// Retained page-context generation after command bookkeeping.
    PageGeneration {
        page_id: PageId,
        generation: u64,
    },
    Pages {
        pages: Vec<PageEvidence>,
    },
    Popup {
        opener_page_id: PageId,
        page_id: PageId,
        url: String,
        title: String,
    },
    /// A handle-resolved call found its bound page no longer open (a popup
    /// the handle was following, since closed) and fell back to the opener
    /// the earlier `click_and_wait_for_popup` recorded. `popup_page_id` is
    /// the page that is now gone; `opener_page_id` is the page the handle is
    /// bound to going forward. Carried on a completed read-only retry, or
    /// on the original `failed` outcome when the call was mutating.
    PopupClosed {
        popup_page_id: PageId,
        opener_page_id: PageId,
    },
    Download {
        filename: String,
        path: String,
        bytes: u64,
        sha256: String,
        /// The exact caller-supplied destination after it passed the configured
        /// downloads-root policy. Absolute input is echoed as absolute; relative
        /// input remains relative. The runtime never discovers or exposes a path
        /// the caller did not already provide.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        saved_to: Option<String>,
    },
    Configuration {
        name: String,
        value: String,
    },
    Resolution {
        target: Box<crate::TargetSpec>,
        fingerprint: Box<TargetFingerprint>,
        candidates: Vec<CandidateEvidence>,
        best_match_authorized: bool,
    },
    Wait {
        condition: crate::WaitCondition,
        elapsed_ms: u64,
        observations: u64,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        excluded_classes: Vec<String>,
        /// What the satisfying poll actually read: the element text or value,
        /// the URL, or the document ready state, depending on the condition.
        ///
        /// The wait already reads this to decide whether it is satisfied. It
        /// used to be discarded, so an agent that verified a submit had to
        /// spend a second round trip snapshotting the page to learn what it
        /// had just confirmed. Bounded by [`MAX_WAIT_OBSERVED_CHARS`] -- this
        /// is a verification value, never a page-text dump.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        observed: Option<String>,
    },
    Screenshot {
        artifact_id: String,
        media_type: String,
        width: u32,
        height: u32,
        bytes: u64,
        sha256: String,
    },
    BrowserExecution {
        engine: String,
        browser_version: String,
        profile_id: String,
        interaction_path: String,
    },
    JavaScriptResult {
        value: serde_json::Value,
        truncated: bool,
    },
    AccessibilitySnapshot {
        page_id: PageId,
        nodes: Vec<AccessibilityNode>,
        truncated: bool,
    },
    FormSnapshot {
        snapshot: crate::FormSnapshot,
    },
    FormValidation {
        issues: Vec<crate::FormValidationIssue>,
    },
    ControlAction {
        action: ControlActionEvidence,
    },
    StructuredExtraction {
        page_id: PageId,
        value: serde_json::Value,
        truncated: bool,
    },
    /// A challenge classification from `detectChallenge`: `Some` is a
    /// detected challenge, `None` is a provably clean page. `confidence` is
    /// the model's confidence in its answer either way — a caller gating a
    /// solve spend on a clean answer needs it. `prior_kind` records the site
    /// prior that enriched the prompt when one existed — transparency, never
    /// a blended answer.
    ChallengeDetection {
        confidence: f32,
        detection: Option<crate::challenges::ChallengeDetection>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        prior_kind: Option<String>,
    },
    CookieState {
        page_id: Option<PageId>,
        cookies: Vec<crate::CookieRecord>,
    },
    PdfArtifact {
        artifact_id: String,
        media_type: String,
        bytes: u64,
        sha256: String,
    },
    Dialog {
        dialog_type: String,
        message: String,
        action: String,
    },
    Emulation {
        viewport: Option<crate::ViewportSize>,
        geolocation: Option<crate::GeolocationCoordinates>,
    },
    HarArtifact {
        artifact_id: String,
        media_type: String,
        bytes: u64,
        sha256: String,
        entries: u32,
    },
    IntentExecution {
        record: ExecutionRecord,
    },
    /// Input timing the runtime synthesized rather than observed, emitted when
    /// the session opted into `executionPolicy.humanize`. Lets `intent-engine`
    /// verify an effect against the timing actually issued. Carries no typed
    /// text: action counts and durations only.
    Humanization {
        engine: String,
        actions: u32,
        synthesized_ms: u64,
    },
    /// Result of resolving one named field of an `ExtractIntent`, emitted once
    /// per field in field order. `value: None` means unresolved, with the
    /// reason in `errorCode`; the rest of the extraction still runs.
    Extraction {
        field: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        value: Option<String>,
        resolution_path: IntentResolutionPath,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        error_code: Option<ErrorCode>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum IntentResolutionPath {
    Deterministic,
    VisionFallback,
    /// Resolved from a cached proactive vision proposal.
    VisionPrefill,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ExecutionRecord {
    pub intent_kind: String,
    pub purpose: Option<String>,
    pub resolution_path: IntentResolutionPath,
    pub plan_summary: String,
    pub candidates: Vec<CandidateEvidence>,
    pub wait_elapsed_ms: Option<u64>,
    pub verification: String,
    pub artifact_ids: Vec<String>,
    pub vision_proposal_sha256: Option<String>,
}

impl Evidence {
    pub fn page_derived(&self) -> bool {
        matches!(
            self,
            Self::Inspection { .. }
                | Self::AccessibilitySnapshot { .. }
                | Self::FormSnapshot { .. }
                | Self::StructuredExtraction { .. }
        )
    }

    pub fn journal_safe(&self) -> Self {
        fn safe_url(value: &str) -> String {
            let Ok(mut url) = url::Url::parse(value) else {
                return "[redacted-invalid-url]".into();
            };
            let _ = url.set_username("");
            let _ = url.set_password(None);
            url.set_query(None);
            url.set_fragment(None);
            url.to_string()
        }
        let mut safe = self.clone();
        match &mut safe {
            Self::ExecutionPath {
                final_url,
                redirect_chain,
                ..
            } => {
                if let Some(url) = final_url {
                    *url = safe_url(url);
                }
                for url in redirect_chain {
                    *url = safe_url(url);
                }
            }
            Self::Navigation { url, .. }
            | Self::Inspection { url, .. }
            | Self::Page { url, .. }
            | Self::Popup { url, .. } => *url = safe_url(url),
            Self::Pages { pages } => {
                for page in pages {
                    page.url = safe_url(&page.url);
                }
            }
            Self::Upload { paths, .. } => {
                for (index, path) in paths.iter_mut().enumerate() {
                    *path = format!("upload://evidence/{index}");
                }
            }
            Self::Download {
                path,
                sha256,
                saved_to,
                ..
            } => {
                *path = format!("artifact://sha256/{sha256}");
                *saved_to = None;
            }
            Self::PopupClosed { .. } => {}
            Self::BrowserExecution { .. } => {}
            Self::IntentExecution { .. } => {}
            Self::Extraction { .. } => {}
            _ => {}
        }
        safe
    }
}

/// Add provenance only to page-derived evidence in a serialized outcome.
/// This keeps public Rust enum variants source-compatible while extending the
/// HTTP and MCP JSON representations.
pub fn annotate_page_derived_evidence(outcome: &mut serde_json::Value) {
    let Some(evidence) = outcome
        .get_mut("evidence")
        .and_then(serde_json::Value::as_array_mut)
    else {
        return;
    };
    for item in evidence {
        if matches!(
            item.get("kind").and_then(serde_json::Value::as_str),
            Some("inspection" | "accessibilitySnapshot" | "formSnapshot" | "structuredExtraction")
        ) {
            item["pageDerived"] = serde_json::Value::Bool(true);
        }
    }
}

impl CommandOutcome {
    pub fn journal_safe(&self) -> Self {
        let mut safe = self.clone();
        match &mut safe {
            Self::Completed { evidence, .. }
            | Self::NeedsReconciliation { evidence, .. }
            | Self::Restarted { evidence, .. }
            | Self::Failed { evidence, .. } => {
                *evidence = evidence.iter().map(Evidence::journal_safe).collect();
            }
            _ => {}
        }
        match &mut safe {
            Self::RetryableFailure { error, .. }
            | Self::NeedsReconciliation { error, .. }
            | Self::PolicyDenied { error, .. }
            | Self::ResourceExhausted { error, .. }
            | Self::Failed { error, .. } => error.message = "redacted durable diagnostic".into(),
            _ => {}
        }
        safe
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
/// Which strategy served a command: the direct-HTTP reader, or the live
/// browser. The browser variants name the *strategy*, never an engine — a
/// Firefox-companion run reports `browser`, and reporting `chromium` there
/// contradicted the `browserExecution` evidence sitting beside it. The old
/// wire names still deserialize so recorded journals keep replaying.
pub enum ExecutionPath {
    DirectHttp,
    #[serde(alias = "chromium")]
    Browser,
    #[serde(alias = "chromiumFallback")]
    BrowserFallback,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ExecutionReason {
    EligibleStaticDocument,
    EligibleExplicitDownload,
    IneligibleCommand,
    SemanticTargetRequired,
    JavascriptRequired,
    UnsupportedContentType,
    StateConflict,
    PolicyRequired,
    /// The page has mutated since load (a non-read-only command ran against
    /// it), so a whole-page read must come from the live DOM, not a refetch.
    PageMutated,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct CandidateEvidence {
    pub role: Option<String>,
    pub name: Option<String>,
    pub score: i32,
    pub reasons: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct TargetFingerprint {
    pub page_id: PageId,
    pub frame: Option<String>,
    pub role: Option<String>,
    pub name: Option<String>,
    pub stable_attributes: std::collections::BTreeMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct PageEvidence {
    pub page_id: PageId,
    pub url: String,
    pub title: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct CommandError {
    pub code: ErrorCode,
    pub message: String,
    pub layer: ErrorLayer,
    pub retryable: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ErrorCode {
    InvalidRequest,
    NotFound,
    DeadlineExceeded,
    BrowserLaunchFailed,
    BrowserCommandFailed,
    VerificationFailed,
    JournalFailed,
    ResourceExhausted,
    PolicyDenied,
    Internal,
    TargetNotFound,
    TargetAmbiguous,
    FrameNotFound,
    ShadowRootUnavailable,
    TargetDetached,
    TargetObscured,
    TargetOutOfBounds,
    WaitConditionTimedOut,
    ScreenshotCaptureFailed,
    NetworkPolicyDenied,
    HttpResponseTooLarge,
    HttpTransferFailed,
    HttpStateConflict,
    HttpEquivalenceUnproven,
    IntentCompileFailed,
    IntentActionMismatch,
    ObstructionSuspected,
    VisionAssistDenied,
    VisionAssistFailed,
    // `submitAndVerify`'s expected state already held before the submit ran,
    // so a post-act pass would prove nothing (static-copy matcher).
    ExpectedStatePreSatisfied,
    // A Boundary submit already completed within this workflow; running
    // another would double-apply the effect unless the caller explicitly
    // acknowledges the prior one (`reSubmit`).
    BoundaryAlreadyExecuted,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ErrorLayer {
    Interface,
    Broker,
    Workflow,
    Page,
    Driver,
    Browser,
    Network,
    Site,
    Journal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum CommandPhase {
    Accepted,
    Prepared,
    Executing,
    ResultPrepared,
    Verifying,
    Recovering,
    Completed,
    Failed,
}

#[derive(Debug, Error, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum RuntimeError {
    #[error("not found: {0}")]
    NotFound(String),
    #[error("invalid request: {0}")]
    InvalidRequest(String),
    /// The configured browser engine could not be reached or started. An
    /// environment fault, not a bad call: the caller's arguments were fine and
    /// resubmitting them unchanged is the right move once the engine is up.
    #[error("{0}")]
    EngineUnreachable(String),
    #[error("internal error: {0}")]
    Internal(String),
}