gthings 0.3.2

CLI binary for gthings — browser-automated web research toolkit
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
mod follow_commands;
mod pdf_commands;
mod search_commands;

use clap::Parser;
use gthings_common::trace::TraceWriter;
use std::time::SystemTime;

#[derive(clap::Parser)]
#[command(
    name = "gthings",
    version,
    about = "Browser automation and web research toolkit"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,

    /// Output as JSON Lines
    #[arg(global = true, long)]
    json: bool,

    /// Log level
    #[arg(global = true, long, default_value = "info")]
    log_level: String,

    /// Trace file path — write structured JSONL telemetry for every command
    #[arg(global = true, long)]
    trace: Option<String>,
}

#[derive(clap::Subcommand)]
enum Command {
    /// Search the web
    Search(SearchArgs),
    /// Follow/extract page content
    Follow(FollowArgs),
    /// PDF text extraction
    Pdf(PdfArgs),
    /// Browser lifecycle management
    #[command(name = "browser", hide = true)]
    Browser(BrowserArgs),
}

#[derive(clap::Args)]
struct BrowserArgs {
    #[command(subcommand)]
    command: BrowserCommand,
}

#[derive(clap::Subcommand)]
enum BrowserCommand {
    /// Start the persistent browser (auto-started on first use)
    Start,
    /// Stop the persistent browser
    Stop,
    /// Show browser status
    Status,
}

#[derive(clap::Args)]
struct SearchArgs {
    #[command(subcommand)]
    command: SearchCommand,
}

#[derive(clap::Subcommand)]
enum SearchCommand {
    /// Single Google search
    Query {
        query: String,
        #[arg(long, default_value = "10")]
        count: usize,
    },
    /// Batch search multiple queries
    Batch {
        queries: Vec<String>,
        #[arg(long, default_value = "5")]
        count: usize,
    },
    /// Two-phase: search then follow top results
    Harvest {
        queries: Vec<String>,
        #[arg(long, default_value = "5")]
        count: usize,
        #[arg(long)]
        max: Option<usize>,
        /// Max concurrent search tabs (default: from env or 3)
        #[arg(long)]
        concurrency: Option<usize>,
        /// Max concurrent follow tabs (default: from env or 3)
        #[arg(long, name = "follow-concurrency")]
        follow_concurrency: Option<usize>,
    },
}

#[derive(clap::Args)]
struct FollowArgs {
    #[command(subcommand)]
    command: FollowCommand,
}

#[derive(clap::Subcommand)]
enum FollowCommand {
    /// Single URL extraction
    Url {
        url: String,
        #[arg(long, default_value = "article,main,[role=main]")]
        selector: String,
        #[arg(long, default_value = "0")]
        offset: usize,
        #[arg(long, default_value = "15000")]
        max: usize,
    },
    /// Batch multi-page extraction
    Batch {
        urls: Vec<String>,
        #[arg(long, default_value = "article,main,[role=main]")]
        selector: String,
        #[arg(long, default_value = "0")]
        offset: usize,
        #[arg(long, default_value = "15000")]
        max: usize,
    },
}

#[derive(clap::Args)]
struct PdfArgs {
    #[command(subcommand)]
    command: PdfCommand,
}

#[derive(clap::Subcommand)]
enum PdfCommand {
    /// Extract text from PDF at URL
    Url { url: String },
    /// Extract text from local PDF file
    File { path: std::path::PathBuf },
}

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    let cli = Cli::parse();

    let filter = tracing_subscriber::EnvFilter::try_new(&cli.log_level)
        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
    tracing_subscriber::fmt().with_env_filter(filter).init();

    let config = gthings_common::config::GthingsConfig::from_env();

    let session_id = format!(
        "ses_{:x}",
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );

    // Initialize TraceWriter if --trace is provided
    let mut trace_writer = cli
        .trace
        .as_ref()
        .and_then(|path| TraceWriter::new(path).ok());

    let cmd_start = std::time::Instant::now();
    let (tool_name, tool_args) = command_metadata(&cli.command);

    // Get a borrow to pass through to handlers
    let trace = trace_writer.as_mut();

    let result = match &cli.command {
        Command::Search(args) => match &args.command {
            SearchCommand::Query { query, count } => {
                search_commands::handle_search_query(&config, query, *count, cli.json, trace).await
            }
            SearchCommand::Batch { queries, count } => {
                search_commands::handle_search_batch(&config, queries, *count, cli.json, trace)
                    .await
            }
            SearchCommand::Harvest {
                queries,
                count,
                max,
                concurrency,
                follow_concurrency,
            } => {
                search_commands::handle_search_harvest(
                    &config,
                    queries,
                    *count,
                    *max,
                    *concurrency,
                    *follow_concurrency,
                    cli.json,
                    trace,
                )
                .await
            }
        },
        Command::Follow(args) => match &args.command {
            FollowCommand::Url {
                url,
                selector,
                offset,
                max,
            } => {
                follow_commands::handle_follow_url(
                    &config, url, selector, *offset, *max, cli.json, trace,
                )
                .await
            }
            FollowCommand::Batch {
                urls,
                selector,
                offset,
                max,
            } => {
                follow_commands::handle_follow_batch(
                    &config, urls, selector, *offset, *max, cli.json, trace,
                )
                .await
            }
        },
        Command::Pdf(args) => match &args.command {
            PdfCommand::Url { url } => pdf_commands::handle_pdf_url(&config, url, cli.json).await,
            PdfCommand::File { path } => {
                pdf_commands::handle_pdf_file(&config, path, cli.json).await
            }
        },
        Command::Browser(args) => match &args.command {
            BrowserCommand::Start => handle_browser_start(cli.json).await,
            BrowserCommand::Stop => handle_browser_stop(cli.json).await,
            BrowserCommand::Status => handle_browser_status(cli.json).await,
        },
    };

    let cmd_duration_ms = cmd_start.elapsed().as_millis() as u64;
    let exit_code = if result.is_ok() { 0 } else { 1 };

    let error_msg = if exit_code != 0 {
        result.as_ref().err().map(|e| e.to_string())
    } else {
        None
    };
    if let Some(ref mut t) = trace_writer {
        t.step(
            &session_id,
            0,
            tool_name,
            "command",
            None,
            cmd_duration_ms,
            Some(tool_args),
            Some(serde_json::json!({"exit": exit_code})),
            error_msg.as_deref(),
        );
    }

    result
}

// Browser lifecycle handlers

/// Path to the browser state file.
fn browser_state_path() -> std::path::PathBuf {
    let home = std::env::var("HOME")
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|_| std::path::PathBuf::from("/tmp"));
    home.join(".gthings").join("browser.json")
}

/// Start the persistent browser.
async fn handle_browser_start(json: bool) -> Result<(), anyhow::Error> {
    let browser = gthings_cdp::Browser::launch()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to start browser: {e}"))?;
    let _conn = browser
        .connect()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to connect: {e}"))?;
    let pid = browser.pid().await.unwrap_or(0);
    if json {
        println!(
            "{}",
            serde_json::json!({
                "status": "started",
                "pid": pid,
                "ws_url": browser.ws_url(),
            })
        );
    } else {
        println!("Browser started (pid={})", pid);
        println!("WebSocket URL: {}", browser.ws_url());
    }
    Ok(())
}

/// Stop the persistent browser.
async fn handle_browser_stop(json: bool) -> Result<(), anyhow::Error> {
    let state_path = browser_state_path();
    if !state_path.exists() {
        if json {
            println!("{}", serde_json::json!({"status": "not_running"}));
        } else {
            println!("No browser state found — browser is not running");
        }
        return Ok(());
    }
    let state_str = std::fs::read_to_string(&state_path)?;
    let state: serde_json::Value = serde_json::from_str(&state_str)?;
    let pid = state["pid"].as_u64().unwrap_or(0);

    if pid > 0 {
        let _ = std::process::Command::new("kill")
            .arg(pid.to_string())
            .status();
    }

    std::fs::remove_file(&state_path)?;

    if json {
        println!("{}", serde_json::json!({"status": "stopped", "pid": pid}));
    } else {
        println!("Browser stopped (pid={})", pid);
    }
    Ok(())
}

/// Show browser status.
async fn handle_browser_status(json: bool) -> Result<(), anyhow::Error> {
    let existing = gthings_cdp::Browser::find_existing().await;
    if let Some(browser) = existing {
        let pid = browser.pid().await.unwrap_or(0);
        if json {
            println!(
                "{}",
                serde_json::json!({
                    "status": "running",
                    "pid": pid,
                    "ws_url": browser.ws_url(),
                })
            );
        } else {
            println!("Browser is RUNNING (pid={})", pid);
            println!("WebSocket URL: {}", browser.ws_url());
        }
    } else {
        if json {
            println!("{}", serde_json::json!({"status": "stopped"}));
        } else {
            println!("Browser is NOT running");
        }
    }
    Ok(())
}

/// Extract command metadata for telemetry.
fn command_metadata(cmd: &Command) -> (&'static str, serde_json::Value) {
    match cmd {
        Command::Search(args) => match &args.command {
            SearchCommand::Query { query, count } => (
                "search",
                serde_json::json!({"query": query, "count": count}),
            ),
            SearchCommand::Batch { queries, count } => (
                "search_batch",
                serde_json::json!({"queries_count": queries.len(), "count": count}),
            ),
            SearchCommand::Harvest {
                queries,
                count,
                max,
                concurrency,
                follow_concurrency,
            } => (
                "search_harvest",
                serde_json::json!({
                    "queries_count": queries.len(),
                    "count": count,
                    "max": max,
                    "concurrency": concurrency,
                    "follow_concurrency": follow_concurrency,
                }),
            ),
        },
        Command::Follow(args) => match &args.command {
            FollowCommand::Url {
                url,
                selector,
                offset: _,
                max,
            } => (
                "follow",
                serde_json::json!({"url": url, "selector": selector, "max": max}),
            ),
            FollowCommand::Batch {
                urls,
                selector: _,
                offset: _,
                max,
            } => (
                "follow_batch",
                serde_json::json!({"urls_count": urls.len(), "max": max}),
            ),
        },
        Command::Pdf(args) => match &args.command {
            PdfCommand::Url { url } => ("pdf_url", serde_json::json!({"url": url})),
            PdfCommand::File { path } => (
                "pdf_file",
                serde_json::json!({"path": format!("{}", path.display())}),
            ),
        },
        Command::Browser(args) => match &args.command {
            BrowserCommand::Start => ("browser_start", serde_json::json!({})),
            BrowserCommand::Stop => ("browser_stop", serde_json::json!({})),
            BrowserCommand::Status => ("browser_status", serde_json::json!({})),
        },
    }
}