Skip to main content

agent_first_http/cli/cmd/
cdp.rs

1//! `afhttp cdp` subcommand. Raw CDP method invocation.
2
3use serde::Serialize;
4
5use crate::cli::output;
6use crate::sdk::Client;
7use crate::shared::error::{Error, ErrorCode};
8use crate::shared::ids::TabId;
9use crate::shared::time::parse_duration;
10
11#[derive(Serialize)]
12struct CdpResult {
13    result: serde_json::Value,
14}
15
16#[derive(Debug)]
17pub struct Args {
18    pub method: String,
19    pub endpoint: String,
20    pub token: Option<String>,
21    pub tab: String,
22    pub params: Option<String>,
23    pub wait: Option<String>,
24}
25
26pub async fn run(args: Args) -> Result<(), Error> {
27    let mut client = Client::connect(&args.endpoint)?;
28    if let Some(t) = args.token.as_deref() {
29        client = client.with_token(t);
30    }
31    let params = if let Some(raw) = args.params {
32        if raw == "@-" {
33            use std::io::Read;
34            let mut buf = String::new();
35            std::io::stdin()
36                .read_to_string(&mut buf)
37                .map_err(|e| Error::new(ErrorCode::IoError, format!("read stdin: {e}")))?;
38            serde_json::from_str(&buf).map_err(|e| {
39                Error::new(
40                    ErrorCode::InvalidArgument,
41                    format!("--params @-: invalid JSON: {e}"),
42                )
43            })?
44        } else {
45            serde_json::from_str(&raw).map_err(|e| {
46                Error::new(
47                    ErrorCode::InvalidArgument,
48                    format!("--params: invalid JSON: {e}"),
49                )
50            })?
51        }
52    } else {
53        serde_json::Value::Object(Default::default())
54    };
55    let mut req = client
56        .cdp(args.method)
57        .tab(TabId::new(args.tab))
58        .params(params);
59    if let Some(spec) = args.wait {
60        let (ev, timeout) = spec.rsplit_once(':').ok_or_else(|| {
61            Error::new(
62                ErrorCode::InvalidArgument,
63                "--wait-event: expected <event>:<timeout>",
64            )
65        })?;
66        let d = parse_duration(timeout)?;
67        req = req.wait_for(ev, d);
68    }
69    let value = req.send().await?;
70    output::emit("cdp", &CdpResult { result: value })
71}