chrome-agent 0.15.0

Browser automation for AI agents. Single binary, zero deps, CDP direct to Chrome.
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
//! Rust shapes for the slice of the Chrome `DevTools` Protocol this tool speaks.
//!
//! **There is no `dead_code` allow in this module, and a field added here that nothing reads is
//! a build failure.** That is the end of a two-step correction worth writing down, because both
//! steps were justified and only the second was right.
//!
//! It began with one `#[allow(dead_code)]` on `pub mod types;`, justified as "CDP fields kept for
//! serde deserialization completeness". That was wrong on every count. Serde ignores unknown
//! fields by default, so a field this tool does not read costs nothing to omit and buys nothing
//! to keep; `MouseButton` is `Serialize` only, so no reading of "completeness" reaches it at all;
//! and for the fields that were neither `Option` nor `#[serde(default)]` — four on `BoxModel`,
//! three on `ExceptionDetails`, one each on `AXValue` and `NavigateResult` — keeping them
//! TIGHTENED what Chrome must send. `serde_proof` below pins both halves of that.
//!
//! The step in between replaced the blanket with 28 per-item allows, each carrying its reason in
//! one of three families. That made the audit possible, which is what it was for, and it did not
//! survive the audit: **`pinned` was false** (the four `BoxModel` fields were named by one
//! `#[cfg(test)]` struct literal in `snapshot.rs` and read by no assertion in it — an
//! initializer, not a dependency); **`shape` was documentation written in struct syntax**, and a
//! comment says the same thing without asking the compiler to carry it or letting it go stale
//! unnoticed; **`envelope` was speculative**, a `sessionId` kept against the day this tool drives
//! several sessions per connection, which is the kind of claim about the unmeasured future this
//! repository refuses everywhere else.
//!
//! So the protocol's unread fields are now documented on the type that would carry them, in
//! prose, where they cost nothing to compile and cannot pretend to be used. What each struct
//! declares is what something reads.

use serde::{Deserialize, Serialize};
use serde_json::Value;

// ---------------------------------------------------------------------------
// Generic CDP wire protocol
// ---------------------------------------------------------------------------

/// Outgoing CDP request envelope.
#[derive(Debug, Serialize)]
pub struct CdpRequest {
    pub id: u64,
    pub method: &'static str,
    pub params: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
}

/// Incoming CDP message — either a response to a request or an async event.
///
/// `untagged` makes every field below load-bearing in one direction nobody expects: when a
/// message fails BOTH variants it is not a message with a missing field, it is a message with
/// no home, and `dispatch_loop` used to drop it silently. A response carries `id` and no
/// `method`, an event carries `method` and no `id`, so the discriminating fields never
/// mis-assign; the only way to fall out of the enum entirely is an optional field arriving with
/// a JSON type the struct did not declare. Every optional field here is therefore either
/// `Value` (which accepts anything) or a type CDP genuinely pins. See
/// `client::resolve_unreadable`, which now answers the waiting caller instead of leaving it to
/// time out.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum CdpMessage {
    Response(CdpResponse),
    Event(CdpEvent),
}

/// Response to a request we sent (matched by `id`).
#[derive(Debug, Deserialize)]
pub struct CdpResponse {
    pub id: u64,
    #[serde(default)]
    pub result: Option<Value>,
    #[serde(default)]
    pub error: Option<CdpError>,
}

/// Protocol-level error attached to a response.
///
/// CDP also sends a free-form `data` beside `code`/`message`. It is not declared here, and that
/// is the safest of the three options rather than the laziest. It was once `Option<String>`, and
/// an object arriving there would have failed `CdpResponse`, then — `CdpMessage` being
/// `untagged` — failed `CdpEvent` too, so the message would have been dropped: an error Chrome
/// answered in milliseconds reaching the caller half a minute later as a timeout. `Option<Value>`
/// closed that hole; declaring nothing closes it further, because serde ignores what it was not
/// told about whatever JSON type arrives. `client::call_within` and `Display` report `code` and
/// `message`, which is every reader this type has ever had; `client::resolve_unreadable` covers
/// the class of message we cannot parse at all.
#[derive(Debug, Deserialize)]
pub struct CdpError {
    pub code: i64,
    pub message: String,
}

/// Async event pushed by Chrome.
#[derive(Debug, Clone, Deserialize)]
pub struct CdpEvent {
    pub method: String,
    #[serde(default)]
    pub params: Value,
}

// ---------------------------------------------------------------------------
// Target domain
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateTargetParams {
    pub url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub height: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_window: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub background: Option<bool>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateTargetResult {
    pub target_id: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTargetsResult {
    pub target_infos: Vec<TargetInfo>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetInfo {
    pub target_id: String,
    #[serde(rename = "type")]
    pub target_type: String,
    pub title: String,
    pub url: String,
}

// ---------------------------------------------------------------------------
// Page domain
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NavigateParams {
    pub url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub referrer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transition_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frame_id: Option<String>,
}

/// `Page.navigate`'s answer. Deliberately only `errorText`: document identity comes from
/// `Page.getFrameTree` afterwards (`diff::Identity` reads `(frameId, loaderId)` there), which
/// answers for a document arrived at by any route and not only by a `goto` this tool sent.
/// `frameId` was declared here and required, so a Chrome that omitted it would have failed the
/// navigation this tool had just performed.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NavigateResult {
    #[serde(default)]
    pub error_text: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureScreenshotParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub clip: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_surface: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_beyond_viewport: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub optimize_for_speed: Option<bool>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureScreenshotResult {
    pub data: String,
}

// ---------------------------------------------------------------------------
// Runtime domain
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EvaluateResult {
    pub result: RemoteObject,
    #[serde(default)]
    pub exception_details: Option<ExceptionDetails>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoteObject {
    #[serde(rename = "type")]
    pub remote_type: String,
    #[serde(default)]
    pub value: Option<Value>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub object_id: Option<String>,
}

/// A throw, as the eight readers of `exception_details` use it: they report
/// `exception.description` and fall back to `text`.
///
/// CDP also sends `exceptionId`, `lineNumber`, `columnNumber`, `scriptId`, `url` and
/// `executionContextId`. None is declared, and the three that were declared were *required* —
/// every script this tool evaluates is one it wrote itself and injected as a single expression,
/// so a line and column point into a string in this repository rather than at anything the
/// caller can open, and requiring them of Chrome to then not read them was a constraint bought
/// for nothing.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionDetails {
    pub text: String,
    #[serde(default)]
    pub exception: Option<RemoteObject>,
}

// ---------------------------------------------------------------------------
// DOM domain
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolveNodeParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_id: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backend_node_id: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub object_group: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_context_id: Option<u64>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolveNodeResult {
    pub object: RemoteObject,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetBoxModelResult {
    pub model: BoxModel,
}

/// CDP box model. Each quad is an array of 8 floats: [x1,y1, x2,y2, x3,y3, x4,y4].
///
/// `content` is what `content_center` aims at and `border` is what `geometry` clips a screenshot
/// to. `padding`, `margin`, `width` and `height` are not declared, and this is the one struct
/// where dropping a field LOOSENS rather than merely tidies: none of the six was `Option` or
/// `#[serde(default)]`, so each was a field Chrome had to send for `DOM.getBoxModel` to parse at
/// all. Keeping an unread required field is the opposite of leniency — a constraint this tool
/// imposed for nothing.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BoxModel {
    pub content: Quad,
    pub border: Quad,
}

/// A quad is 4 (x, y) points = 8 floats.
pub type Quad = Vec<f64>;

// ---------------------------------------------------------------------------
// Input domain
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DispatchMouseEventParams {
    #[serde(rename = "type")]
    pub event_type: MouseEventType,
    pub x: f64,
    pub y: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub button: Option<MouseButton>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buttons: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modifiers: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub click_count: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delta_x: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delta_y: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pointer_type: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum MouseEventType {
    MousePressed,
    MouseReleased,
    MouseMoved,
}

/// The mouse button this tool sends. CDP defines six; one is wired.
///
/// It used to declare all six — `None`, `Left`, `Middle`, `Right`, `Back`, `Forward` — and
/// construct exactly one of them, at the eight sites that dispatch pointer input (`element.rs`
/// ×4 for click and dblclick, `element_controls.rs` ×4 for drag). Nothing else in the repository
/// mentions a right click: no command, no flag, no test, no line of documentation. So this enum
/// was the only place that said anything at all about the subject, and what it said was untrue —
/// a reader of the type concluded a right click existed somewhere, and there is nowhere for it
/// to exist. The five went, and the absence became a fact of the type rather than a discovery
/// made by grepping.
///
/// Two things make the removal cheap. Nothing deserializes `MouseButton` (`Serialize` only), so
/// no message Chrome sends can stop fitting; and the value only ever leaves in
/// `DispatchMouseEventParams::button`, so removing a variant narrows what this tool can emit and
/// changes nothing it accepts. `None` went with the rest and was redundant besides: a move with
/// no button held is already spelled `button: None` in Rust, which omits the field entirely
/// (`skip_serializing_if`) and lets CDP apply its own `"none"` default — `element_controls`'s
/// drag does exactly that between press and release.
///
/// **What this costs, stated:** adding a right click later means adding a variant back. That is
/// one line, and it will be the smallest part of the work — there is no verb, no CLI surface and
/// no `hit_test` story for a context menu today, and whoever writes them will not be slowed by
/// this. `types.rs` is a hand-picked subset of CDP, not a mirror of it (there are no `Network.*`
/// types here either), so carrying a complete enum inside an incomplete module bought fidelity
/// nowhere and asserted a capability in the one spot a reader would look for it.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum MouseButton {
    Left,
}

// ---------------------------------------------------------------------------
// Accessibility domain
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFullAXTreeResult {
    pub nodes: Vec<AXNode>,
}

/// One accessibility node, reduced to what `snapshot_render` renders and what the traversal
/// needs to walk. `description` and `frameId` are not declared: the render strips to role, name
/// and value precisely to keep a tree an agent can read, and frame scoping is done on the way
/// out — `snapshot` passes `frameId` as a REQUEST parameter, so the tree that comes back is
/// already the frame's.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AXNode {
    pub node_id: String,
    #[serde(default)]
    pub ignored: bool,
    #[serde(default)]
    pub role: Option<AXValue>,
    #[serde(default)]
    pub name: Option<AXValue>,
    #[serde(default)]
    pub value: Option<AXValue>,
    #[serde(default)]
    pub properties: Option<Vec<AXProperty>>,
    #[serde(default)]
    pub child_ids: Option<Vec<String>>,
    #[serde(default, rename = "backendDOMNodeId")]
    pub backend_dom_node_id: Option<i64>,
    #[serde(default)]
    pub parent_id: Option<String>,
}

/// A tagged accessibility value.
///
/// CDP sends a `type` (`"string"`, `"boolean"`, `"idrefList"`, `"computedString"`…) and, for
/// relations, `relatedNodes`. Neither is declared. Every reader here goes through
/// `AXNode::role_name`/`name_value` or `AXProperty`, all of which ask `value.as_str()`/`as_bool()`
/// and get `None` when the type is not the one they wanted — so the tag is checked by the read
/// rather than before it, and `type` was *required*, which made a value Chrome sent untagged an
/// unparseable tree rather than a `None`.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AXValue {
    #[serde(default)]
    pub value: Option<Value>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AXProperty {
    pub name: String,
    pub value: AXValue,
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

impl BoxModel {
    /// Return the center (x, y) of the content quad.
    pub fn content_center(&self) -> (f64, f64) {
        // content quad is [x1,y1, x2,y2, x3,y3, x4,y4]
        if self.content.len() < 8 {
            return (0.0, 0.0);
        }
        let cx = (self.content[0] + self.content[2] + self.content[4] + self.content[6]) / 4.0;
        let cy = (self.content[1] + self.content[3] + self.content[5] + self.content[7]) / 4.0;
        (cx, cy)
    }
}

impl AXNode {
    /// Extract the human-readable role string, if present.
    pub fn role_name(&self) -> Option<&str> {
        self.role.as_ref()?.value.as_ref()?.as_str()
    }

    /// Extract the human-readable name string, if present.
    pub fn name_value(&self) -> Option<&str> {
        self.name.as_ref()?.value.as_ref()?.as_str()
    }
}

impl std::fmt::Display for CdpError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "CDP error {}: {}", self.code, self.message)
    }
}

impl std::error::Error for CdpError {}

/// The two facts the module doc rests on, so neither can rot into a comment nobody rechecks.
///
/// They are asserted rather than asserted-about: the first says an undeclared field cannot break
/// a parse, which is why removing 28 of them was safe; the second says a declared non-`Option`
/// field is a demand this tool makes of Chrome, which is why removing nine of them was an
/// improvement and not merely tidying.
#[cfg(test)]
mod serde_proof {
    use super::*;

    /// A field we do not declare is IGNORED, whatever it holds — so no removal above can make a
    /// message Chrome really sends stop fitting.
    #[test]
    fn an_undeclared_field_cannot_break_a_parse() {
        // `sessionId` and `data` were declared until this pass; `whatever` never was. All three
        // arrive here, one of them as an object, which is the JSON type that used to drop the
        // whole message when `data` was typed `Option<String>`.
        let json = r#"{"id":7,"error":{"code":-32000,"message":"boom","data":{"detail":"x"}},
                       "sessionId":"S1","whatever":42}"#;
        let r: CdpResponse = serde_json::from_str(json).expect("undeclared fields are ignored");
        assert_eq!(r.id, 7);
        assert_eq!(r.error.expect("error parsed").code, -32000);
    }

    /// A declared field that is neither `Option` nor `#[serde(default)]` is REQUIRED. That is the
    /// cost the old "kept for deserialization completeness" had backwards, and this is the
    /// relaxation the removals bought: `DOM.getBoxModel` now parses from the two quads that are
    /// read, and a Chrome that omitted `margin` would once have failed the whole reply.
    #[test]
    fn only_what_is_read_is_demanded_of_chrome() {
        let two_quads_only = r#"{"content":[0,0,1,0,1,1,0,1],"border":[0,0,1,0,1,1,0,1]}"#;
        assert!(serde_json::from_str::<BoxModel>(two_quads_only).is_ok());

        // `content` IS read, so it stays required — the lint above is about unread fields only.
        let err = serde_json::from_str::<BoxModel>(r#"{"border":[0,0,1,0,1,1,0,1]}"#)
            .expect_err("content is read, so it is still demanded")
            .to_string();
        assert!(err.contains("content"), "expected a missing-field error naming content: {err}");

        // Same relaxation on the other three: `exceptionId`/`lineNumber`/`columnNumber` and
        // `type` were required and unread.
        assert!(serde_json::from_str::<ExceptionDetails>(r#"{"text":"ReferenceError"}"#).is_ok());
        assert!(serde_json::from_str::<AXValue>(r#"{"value":"button"}"#).is_ok());
        assert!(serde_json::from_str::<NavigateResult>("{}").is_ok());
    }
}