Skip to main content

codetether_agent/cli/browserctl/
run.rs

1use super::{BrowserCtlArgs, BrowserCtlCommand, offline, request};
2use crate::tool::{Tool, browserctl::BrowserCtlTool};
3use anyhow::{Result, bail};
4use serde_json::Value;
5
6pub async fn execute(args: BrowserCtlArgs) -> Result<()> {
7    if let BrowserCtlCommand::Offline { cmd } = &args.command {
8        return offline::execute(cmd, args.json);
9    }
10    let tool = BrowserCtlTool::new();
11    if request::needs_attach(&args.command) {
12        call(&tool, request::attach(&args)).await?;
13    }
14    let result = call(&tool, request::command(&args)).await?;
15    print_output(&result.output, args.json);
16    Ok(())
17}
18
19async fn call(tool: &BrowserCtlTool, payload: Value) -> Result<crate::tool::ToolResult> {
20    let result = tool.execute(payload).await?;
21    if !result.success {
22        bail!("{}", result.output);
23    }
24    Ok(result)
25}
26
27fn print_output(output: &str, json: bool) {
28    println!("{}", format_output(output, json));
29}
30
31pub(super) fn format_output(output: &str, json: bool) -> String {
32    let Ok(value) = serde_json::from_str::<Value>(output) else {
33        return output.to_string();
34    };
35    if json {
36        serde_json::to_string(&value).unwrap_or_else(|_| output.to_string())
37    } else {
38        serde_json::to_string_pretty(&value).unwrap_or_else(|_| output.to_string())
39    }
40}