chrome-agent 0.6.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
use std::time::Duration;

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

use crate::cdp::client::CdpClient;
use crate::cdp::types::EvaluateResult;

/// A captured network entry.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkEntry {
    pub url: String,
    /// Resource classification, not an HTTP verb. Live mode stores the CDP
    /// `ResourceType` (`Document`/`XHR`/`Script`/…); retroactive mode stores the
    /// Resource Timing `initiatorType` (`xmlhttprequest`/`script`/`img`/…).
    /// Neither CDP `responseReceived` nor the Resource Timing API exposes the
    /// real HTTP method, so this is deliberately the resource type in both modes.
    pub resource_type: String,
    pub status: u16,
    pub content_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    pub size: u64,
    pub duration_ms: u64,
}

// Content types eligible for body capture.
const CAPTURABLE_TYPES: &[&str] = &["json", "text", "javascript", "xml"];

fn is_capturable_type(ct: &str) -> bool {
    let lower = ct.to_ascii_lowercase();
    CAPTURABLE_TYPES.iter().any(|t| lower.contains(t))
}

/// Retroactive mode: uses the Performance/Resource Timing API to list resources
/// already loaded on the current page. Works without `Network.enable` (stealth-safe).
pub async fn run_retroactive(
    client: &CdpClient,
    filter: Option<&str>,
    limit: usize,
) -> Result<Vec<NetworkEntry>, crate::BoxError> {
    let js = r"
        JSON.stringify(
            performance.getEntriesByType('resource').map(e => ({
                url: e.name,
                type: e.initiatorType,
                duration: Math.round(e.duration),
                size: e.transferSize || 0,
            }))
        )
    ";

    let result: EvaluateResult = client
        .call(
            "Runtime.evaluate",
            json!({
                "expression": js,
                "returnByValue": true,
                "awaitPromise": false,
            }),
        )
        .await?;

    if let Some(exc) = &result.exception_details {
        return Err(format!(
            "Performance API error: {}",
            exc.exception
                .as_ref()
                .and_then(|e| e.description.as_deref())
                .unwrap_or(&exc.text)
        )
        .into());
    }

    let raw = result
        .result
        .value
        .as_ref()
        .and_then(|v| v.as_str())
        .unwrap_or("[]");

    let entries: Vec<Value> = serde_json::from_str(raw)?;

    let filter_lower = filter.map(str::to_ascii_lowercase);

    let results: Vec<NetworkEntry> = entries
        .into_iter()
        .filter_map(|e| {
            let url = e.get("url")?.as_str()?.to_string();
            if let Some(ref f) = filter_lower
                && !url.to_ascii_lowercase().contains(f.as_str()) {
                    return None;
                }
            let initiator = e.get("type").and_then(Value::as_str).unwrap_or("other");
            let duration = e.get("duration").and_then(Value::as_u64).unwrap_or(0);
            let size = e.get("size").and_then(Value::as_u64).unwrap_or(0);

            // Map initiator type to a readable content type hint
            let content_type = match initiator {
                "xmlhttprequest" | "fetch" => "xhr/fetch".to_string(),
                "script" => "script".to_string(),
                "css" | "link" => "stylesheet".to_string(),
                "img" => "image".to_string(),
                "font" => "font".to_string(),
                other => other.to_string(),
            };

            Some(NetworkEntry {
                url,
                resource_type: initiator.to_string(), // Resource Timing exposes initiatorType, not the HTTP method
                status: 0,                             // Resource Timing API doesn't expose status
                content_type,
                body: None,
                size,
                duration_ms: duration,
            })
        })
        .take(limit)
        .collect();

    Ok(results)
}

/// Live capture mode: enables `Network` domain, subscribes to `responseReceived`
/// events, and collects responses for the specified duration.
pub async fn run_live(
    client: &CdpClient,
    filter: Option<&str>,
    capture_body: bool,
    limit: usize,
    timeout_secs: u64,
) -> Result<Vec<NetworkEntry>, crate::BoxError> {
    // Enable Network domain (required for live capture)
    client.enable("Network").await?;

    let mut rx = client.events();
    let deadline = tokio::time::Instant::now() + Duration::from_secs(timeout_secs);
    let filter_lower = filter.map(str::to_ascii_lowercase);

    let mut entries: Vec<NetworkEntry> = Vec::new();

    loop {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() || entries.len() >= limit {
            break;
        }

        let event = tokio::time::timeout(remaining, async {
            loop {
                match rx.recv().await {
                    Ok(ev) => return Ok(ev),
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => {
                        return Err("Event channel closed".to_string());
                    }
                }
            }
        })
        .await;

        let event = match event {
            Ok(Ok(ev)) => ev,
            Ok(Err(e)) => return Err(e.into()),
            Err(_) => break, // timeout
        };

        if event.method != "Network.responseReceived" {
            continue;
        }

        let Some(response) = event.params.get("response") else { continue };

        let url = response
            .get("url")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();

        // Apply filter
        if let Some(ref f) = filter_lower
            && !url.to_ascii_lowercase().contains(f.as_str()) {
                continue;
            }

        let status = response
            .get("status")
            .and_then(Value::as_u64)
            .unwrap_or(0) as u16;
        let content_type = response
            .get("mimeType")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let resource_type = event
            .params
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or("Other")
            .to_string();
        let request_id = event
            .params
            .get("requestId")
            .and_then(Value::as_str)
            .unwrap_or("");
        let encoded_length = response
            .get("encodedDataLength")
            .and_then(Value::as_u64)
            .unwrap_or(0);

        // Optionally fetch body for text-like content types
        let body = if capture_body && is_capturable_type(&content_type) && !request_id.is_empty() {
            fetch_response_body(client, request_id).await
        } else {
            None
        };

        entries.push(NetworkEntry {
            url,
            resource_type,
            status,
            content_type,
            body,
            size: encoded_length,
            duration_ms: 0, // timing not directly available from responseReceived
        });

        if entries.len() >= limit {
            break;
        }
    }

    Ok(entries)
}

/// Format network entries as a human-readable table.
pub fn format_text(entries: &[NetworkEntry]) -> String {
    if entries.is_empty() {
        return "No network entries captured.".to_string();
    }
    let mut out = format!(
        "{:<70} {:>6} {:<14} {:>8} {:>6}\n{}\n",
        "URL", "STATUS", "TYPE", "SIZE", "MS",
        "-".repeat(110)
    );
    for e in entries {
        let url_display = crate::truncate::truncate_str(&e.url, 67, "...");
        let status_str = if e.status == 0 { "-".to_string() } else { e.status.to_string() };
        let size_str = if e.size == 0 {
            "-".to_string()
        } else if e.size >= 1024 {
            format!("{}K", e.size / 1024)
        } else {
            format!("{}B", e.size)
        };
        out += &format!(
            "{:<70} {:>6} {:<14} {:>8} {:>6}\n",
            url_display, status_str, e.content_type, size_str, e.duration_ms
        );
        if let Some(ref b) = e.body {
            let preview = crate::truncate::truncate_str(b, 200, "...");
            out += &format!("  body: {preview}\n");
        }
    }
    out += &format!("\n{} entries", entries.len());
    out
}

/// Fetch a response body via `Network.getResponseBody`. Returns `None` on failure
/// (body may not be available if request was evicted from memory).
async fn fetch_response_body(client: &CdpClient, request_id: &str) -> Option<String> {
    let result: Value = client
        .call(
            "Network.getResponseBody",
            json!({ "requestId": request_id }),
        )
        .await
        .ok()?;

    let body = result.get("body")?.as_str()?;
    Some(crate::truncate::truncate_str(body, 2000, "...(truncated)").into_owned())
}

/// Params for `Fetch.enable` that pause every request matching `pattern` at the
/// request stage. Extracted so tests can assert the exact wire shape.
fn fetch_enable_params(pattern: &str) -> Value {
    json!({
        "patterns": [{"urlPattern": pattern, "requestStage": "Request"}]
    })
}

/// Params for `Fetch.failRequest` that abort a paused request. Extracted so
/// tests can assert the exact wire shape.
fn fail_request_params(request_id: &str) -> Value {
    json!({
        "requestId": request_id,
        "reason": "BlockedByClient",
    })
}

/// Block requests matching a URL pattern using the Fetch domain.
pub async fn run_route_abort(
    client: &CdpClient,
    pattern: &str,
    timeout_secs: u64,
) -> Result<Vec<String>, crate::BoxError> {
    client.send("Fetch.enable", fetch_enable_params(pattern)).await?;

    // Subscribe ONCE, before the loop. Re-subscribing each iteration (as a fresh
    // `wait_for_event` call would) drops any `Fetch.requestPaused` events emitted
    // during the `Fetch.failRequest` round-trip, leaking blocked requests.
    let mut rx = client.events();
    let mut blocked = Vec::new();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);

    while std::time::Instant::now() < deadline {
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        if remaining.is_zero() {
            break;
        }
        let event = tokio::time::timeout(remaining, async {
            loop {
                match rx.recv().await {
                    Ok(ev) if ev.method == "Fetch.requestPaused" => return Some(ev),
                    Ok(_)
                    | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => return None,
                }
            }
        })
        .await;

        match event {
            Ok(Some(ev)) => {
                let request_id = ev.params.get("requestId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let url = ev.params.get("request")
                    .and_then(|r| r.get("url"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let _ = client
                    .send("Fetch.failRequest", fail_request_params(request_id))
                    .await;
                if !url.is_empty() {
                    blocked.push(url);
                }
            }
            // event channel closed, or timeout elapsed
            Ok(None) | Err(_) => break,
        }
    }

    let _ = client.send("Fetch.disable", serde_json::json!({})).await;
    Ok(blocked)
}

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

    #[test]
    fn bug_url_truncation_utf8_safe() {
        // Bug: &e.url[..67] panics on URLs with multi-byte chars
        let entry = NetworkEntry {
            url: "https://example.com/café/résumé/über/naïve/длинный".to_string(),
            resource_type: "Document".to_string(),
            status: 200,
            content_type: "text/html".to_string(),
            size: 1000,
            duration_ms: 50,
            body: None,
        };
        // This should not panic
        let text = format_text(&[entry]);
        assert!(!text.is_empty());
    }

    #[test]
    fn route_abort_params_structure() {
        // Assert the params the actual abort code path produces, not a literal
        // rebuilt in the test body.
        let params = fetch_enable_params("*tracking*");
        let patterns = params.get("patterns").unwrap().as_array().unwrap();
        assert_eq!(patterns.len(), 1);
        assert_eq!(patterns[0]["urlPattern"], "*tracking*");
        assert_eq!(patterns[0]["requestStage"], "Request");

        let fail = fail_request_params("req-42");
        assert_eq!(fail["requestId"], "req-42");
        assert_eq!(fail["reason"], "BlockedByClient");
    }

    #[test]
    fn bug_body_truncation_utf8_safe() {
        // Bug: &body[..2000] panics on bodies with multi-byte chars
        let entry = NetworkEntry {
            url: "https://example.com".to_string(),
            resource_type: "XHR".to_string(),
            status: 200,
            content_type: "application/json".to_string(),
            size: 5000,
            duration_ms: 50,
            body: Some("é".repeat(3000)),  // each é is 2 bytes
        };
        let text = format_text(&[entry]);
        assert!(!text.is_empty());
    }

    #[test]
    fn entry_serializes_resource_type_not_method() {
        // Regression: the field used to be `method` but held a CDP ResourceType
        // (Document/XHR/Script) in live mode and a hardcoded "GET" in retroactive
        // mode — mislabeled and inconsistent. It must now serialize as
        // `resourceType` and never as `method`.
        let entry = NetworkEntry {
            url: "https://example.com/api".to_string(),
            resource_type: "XHR".to_string(),
            status: 200,
            content_type: "application/json".to_string(),
            size: 10,
            duration_ms: 5,
            body: None,
        };
        let v = serde_json::to_value(&entry).unwrap();
        assert_eq!(v["resourceType"], "XHR");
        assert!(v.get("method").is_none(), "must not emit a `method` key");
    }

    #[test]
    fn bug_body_preview_utf8_safe() {
        // Bug: &b[..200] panics on bodies with multi-byte chars
        let entry = NetworkEntry {
            url: "https://example.com".to_string(),
            resource_type: "XHR".to_string(),
            status: 200,
            content_type: "application/json".to_string(),
            size: 500,
            duration_ms: 50,
            body: Some("日本語テスト".repeat(100)),  // multi-byte Japanese
        };
        let text = format_text(&[entry]);
        assert!(!text.is_empty());
    }
}