bobby-browser-client 0.6.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
//! 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,
}

/// 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>,
}

/// 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,
}

/// 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>,
    #[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>,
    },
}

#[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>,
    },
    Element {
        selector: String,
        text: Option<String>,
    },
    Upload {
        selector: String,
        paths: Vec<String>,
    },
    Page {
        page_id: PageId,
        url: String,
        title: String,
    },
    Pages {
        pages: Vec<PageEvidence>,
    },
    Popup {
        opener_page_id: PageId,
        page_id: PageId,
        url: String,
        title: String,
    },
    Download {
        filename: String,
        path: String,
        bytes: u64,
        sha256: 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>,
    },
    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,
    },
    ControlAction {
        action: ControlActionEvidence,
    },
    StructuredExtraction {
        page_id: PageId,
        value: serde_json::Value,
        truncated: bool,
    },
    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,
}

#[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 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, .. } => {
                *path = format!("artifact://sha256/{sha256}");
            }
            Self::BrowserExecution { .. } => {}
            Self::IntentExecution { .. } => {}
            Self::Extraction { .. } => {}
            _ => {}
        }
        safe
    }
}

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")]
pub enum ExecutionPath {
    DirectHttp,
    Chromium,
    ChromiumFallback,
}

#[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,
}

#[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,
}

#[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),
    #[error("internal error: {0}")]
    Internal(String),
}