merry-tools 0.1.3

Workspace file, search, patch, web fetch, and document tools for the Merry agent runtime.
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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Process-spawning abstraction for session-scoped headless Chrome/Chromium.
//!
//! Routing browser launches through [`ProcessRunnerBrowserLauncher`] ensures
//! headless Chromium obeys the host's configured [`ProcessRunner`] /
//! [`BackgroundProcessControl`] boundary (including disabled or callback-driven
//! host runners) instead of bypassing it with raw OS process spawns.

use merry_runtime::{
    BackgroundProcessControl, BackgroundProcessId, BackgroundProcessState, ProcessActionIntent,
    ProcessEnvPolicy, ProcessExitStatus, ProcessRunner, ProcessRunnerContext,
};
use std::{
    fmt, future::Future, path::PathBuf, pin::Pin, process::Stdio, sync::Arc, time::Duration,
};
use tokio::{
    io::{AsyncBufReadExt, BufReader},
    process::{Child, ChildStderr, Command},
};

const BROWSER_STDOUT_LIMIT_BYTES: usize = 16 * 1024;
const BROWSER_STDERR_LIMIT_BYTES: usize = 64 * 1024;
const DEVTOOLS_POLL_INTERVAL: Duration = Duration::from_millis(25);

/// Validated launch specification for a headless Chrome/Chromium child process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowserLaunchSpec {
    /// Path to the discovered or configured Chrome/Chromium executable.
    pub executable: PathBuf,
    /// Ordered command-line arguments passed to the browser executable.
    pub args: Vec<String>,
    /// Ephemeral isolated `--user-data-dir` profile directory owned by the session.
    pub profile_dir: Option<PathBuf>,
}

/// Boxed async future used across object-safe browser launcher boundaries.
pub type BrowserLauncherFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Owned handle to a running headless browser child process.
pub trait BrowserProcessHandle: Send {
    /// Waits up to `timeout` for Chrome to print its DevTools `ws://` URL on stderr.
    fn wait_for_devtools_ws_url(
        &mut self,
        timeout: Duration,
    ) -> BrowserLauncherFuture<'_, Result<String, String>>;

    /// Terminates the running browser process cleanly.
    fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()>;
}

/// Process-spawning boundary consumed by [`super::BrowserSessionManager`].
pub trait BrowserProcessLauncher: fmt::Debug + Send + Sync {
    /// Launches a headless browser process for `spec`.
    fn launch(
        &self,
        spec: BrowserLaunchSpec,
    ) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>>;
}

/// [`BrowserProcessLauncher`] backed by Merry's runtime [`ProcessRunner`] and
/// [`BackgroundProcessControl`] contract.
pub struct ProcessRunnerBrowserLauncher {
    runner: Arc<dyn ProcessRunner>,
}

impl fmt::Debug for ProcessRunnerBrowserLauncher {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ProcessRunnerBrowserLauncher")
            .finish_non_exhaustive()
    }
}

impl ProcessRunnerBrowserLauncher {
    /// Wraps a Merry [`ProcessRunner`] so headless browser launches obey the
    /// configured host process boundary.
    #[must_use]
    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
        Self { runner }
    }
}

impl BrowserProcessLauncher for ProcessRunnerBrowserLauncher {
    fn launch(
        &self,
        spec: BrowserLaunchSpec,
    ) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>> {
        Box::pin(async move {
            let executable = spec.executable.to_str().ok_or_else(|| {
                format!(
                    "Chrome/Chromium executable path is not valid UTF-8: {}",
                    spec.executable.display()
                )
            })?;
            let mut argv = Vec::with_capacity(spec.args.len() + 1);
            argv.push(executable.to_owned());
            argv.extend(spec.args);

            let intent = ProcessActionIntent::new(
                argv,
                None,
                ProcessEnvPolicy::Empty,
                None,
                BROWSER_STDOUT_LIMIT_BYTES,
                BROWSER_STDERR_LIMIT_BYTES,
            )
            .map_err(|error| format!("invalid browser launch arguments: {error}"))?
            .with_background(true)
            .with_display_name(Some("headless-browser".to_owned()));

            let output = self
                .runner
                .run(intent, ProcessRunnerContext::default())
                .await
                .map_err(|error| {
                    format!("failed spawning Chrome/Chromium through process backend: {error}")
                })?;

            let initial_stderr = output.stderr_text().to_owned();
            if output.status() != ProcessExitStatus::Running {
                return Err(format!(
                    "Chrome/Chromium did not stay running ({:?}): {}",
                    output.status(),
                    summarize_stderr_lines(&initial_stderr)
                ));
            }
            let Some(bg_id) = output.background_process_id().cloned() else {
                return Err(
                    "configured process backend did not return a background process id for Chrome/Chromium"
                        .to_owned(),
                );
            };
            let Some(control) = self.runner.background_control() else {
                return Err(
                    "configured process backend does not expose background process control for Chrome/Chromium"
                        .to_owned(),
                );
            };

            Ok(Box::new(ProcessRunnerBrowserHandle {
                bg_id,
                control,
                initial_stderr,
                stopped: false,
            }) as Box<dyn BrowserProcessHandle>)
        })
    }
}

struct ProcessRunnerBrowserHandle {
    bg_id: BackgroundProcessId,
    control: Arc<dyn BackgroundProcessControl>,
    initial_stderr: String,
    stopped: bool,
}

impl ProcessRunnerBrowserHandle {
    fn stop_now(&mut self) {
        if !self.stopped {
            self.stopped = true;
            let _ = self.control.stop(&self.bg_id);
        }
    }

    async fn stop_async(&mut self) {
        if self.stopped {
            return;
        }
        self.stopped = true;
        let control = Arc::clone(&self.control);
        let bg_id = self.bg_id.clone();
        let _ = tokio::task::spawn_blocking(move || {
            let _ = control.stop(&bg_id);
        })
        .await;
    }
}

impl Drop for ProcessRunnerBrowserHandle {
    fn drop(&mut self) {
        self.stop_now();
    }
}

impl BrowserProcessHandle for ProcessRunnerBrowserHandle {
    fn wait_for_devtools_ws_url(
        &mut self,
        timeout: Duration,
    ) -> BrowserLauncherFuture<'_, Result<String, String>> {
        Box::pin(async move {
            if let Some(url) = extract_devtools_ws_url(&self.initial_stderr) {
                return Ok(url);
            }
            let deadline = tokio::time::Instant::now() + timeout;
            let mut last_stderr = self.initial_stderr.clone();
            loop {
                match self.control.read(&self.bg_id) {
                    Ok(output) => {
                        if let Some(url) = extract_devtools_ws_url(output.stderr()) {
                            return Ok(url);
                        }
                        if !output.stderr().is_empty() {
                            last_stderr = output.stderr().to_owned();
                        }
                        if !matches!(
                            output.summary().state(),
                            BackgroundProcessState::Running { .. }
                        ) {
                            self.stopped = true;
                            return Err(format!(
                                "Chrome exited without reporting DevTools WebSocket URL: {}",
                                summarize_stderr_lines(&last_stderr)
                            ));
                        }
                    }
                    Err(error) => {
                        self.stopped = true;
                        return Err(format!(
                            "Chrome background process disappeared before reporting DevTools URL: {}",
                            error.message()
                        ));
                    }
                }
                let now = tokio::time::Instant::now();
                if now >= deadline {
                    self.stop_async().await;
                    return Err("timed out waiting for Chrome DevTools listening port".to_owned());
                }
                let sleep_for = deadline
                    .saturating_duration_since(now)
                    .min(DEVTOOLS_POLL_INTERVAL);
                tokio::time::sleep(sleep_for).await;
            }
        })
    }

    fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()> {
        Box::pin(async move {
            self.stop_async().await;
        })
    }
}

/// Default direct OS [`BrowserProcessLauncher`] used when no [`ProcessRunner`]
/// was injected into [`super::BrowserConfig`].
#[derive(Debug, Default)]
pub(super) struct LocalBrowserProcessLauncher;

impl BrowserProcessLauncher for LocalBrowserProcessLauncher {
    fn launch(
        &self,
        spec: BrowserLaunchSpec,
    ) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>> {
        Box::pin(async move {
            let mut cmd = Command::new(&spec.executable);
            cmd.args(&spec.args)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::piped())
                .kill_on_drop(true);

            let child = cmd.spawn().map_err(|error| {
                format!(
                    "failed spawning Chrome/Chromium ({}): {error}",
                    spec.executable.display()
                )
            })?;
            child_browser_process_handle(child)
        })
    }
}

/// Wraps an already-spawned headless browser [`Child`] whose stderr is piped
/// into a [`BrowserProcessHandle`] owned exclusively by [`super::BrowserSessionManager`].
pub fn child_browser_process_handle(
    mut child: Child,
) -> Result<Box<dyn BrowserProcessHandle>, String> {
    let stderr = child
        .stderr
        .take()
        .ok_or_else(|| "Chrome/Chromium stderr pipe unavailable".to_owned())?;

    Ok(Box::new(LocalBrowserProcessHandle {
        child,
        stderr: Some(stderr),
    }) as Box<dyn BrowserProcessHandle>)
}

struct LocalBrowserProcessHandle {
    child: Child,
    stderr: Option<ChildStderr>,
}

impl Drop for LocalBrowserProcessHandle {
    fn drop(&mut self) {
        let _ = self.child.start_kill();
    }
}

impl BrowserProcessHandle for LocalBrowserProcessHandle {
    fn wait_for_devtools_ws_url(
        &mut self,
        timeout: Duration,
    ) -> BrowserLauncherFuture<'_, Result<String, String>> {
        Box::pin(async move {
            let Some(stderr) = self.stderr.take() else {
                return Err("Chrome/Chromium stderr pipe already consumed".to_owned());
            };
            let result = read_devtools_ws_url_from_pipe(stderr, timeout).await;
            if result.is_err() {
                let _ = self.child.start_kill();
            }
            result
        })
    }

    fn shutdown(&mut self) -> BrowserLauncherFuture<'_, ()> {
        Box::pin(async move {
            let _ = self.child.start_kill();
            let _ = tokio::time::timeout(Duration::from_secs(2), self.child.wait()).await;
        })
    }
}

async fn read_devtools_ws_url_from_pipe(
    stderr: ChildStderr,
    timeout: Duration,
) -> Result<String, String> {
    let mut lines = BufReader::new(stderr).lines();
    let deadline = tokio::time::Instant::now() + timeout;
    let mut recent_lines = Vec::new();
    while tokio::time::Instant::now() < deadline {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        match tokio::time::timeout(remaining, lines.next_line()).await {
            Ok(Ok(Some(line))) => {
                if let Some(url) = extract_devtools_ws_url(&line) {
                    return Ok(url);
                }
                if recent_lines.len() < 20 {
                    recent_lines.push(line);
                }
            }
            Ok(Ok(None)) => break,
            Ok(Err(error)) => return Err(format!("error reading Chrome stderr: {error}")),
            Err(_) => {
                return Err("timed out waiting for Chrome DevTools listening port".to_owned());
            }
        }
    }
    Err(format!(
        "Chrome exited without reporting DevTools WebSocket URL: {}",
        recent_lines.join(" | ")
    ))
}

fn extract_devtools_ws_url(text: &str) -> Option<String> {
    for line in text.lines() {
        if let Some(pos) = line.find("ws://") {
            let ws_part = line[pos..].trim();
            if !ws_part.is_empty() {
                return Some(ws_part.to_owned());
            }
        }
    }
    None
}

fn summarize_stderr_lines(text: &str) -> String {
    text.lines().take(20).collect::<Vec<_>>().join(" | ")
}

#[cfg(test)]
mod tests {
    use super::*;
    use merry_runtime::{
        BackgroundProcessLookupError, BackgroundProcessOutput, BackgroundProcessStop,
        BackgroundProcessSummary, ProcessRunnerError, ProcessRunnerFuture, ProcessRunnerOutput,
    };
    use std::sync::Mutex;

    struct FakeBackgroundControl {
        stderr_reads: Mutex<Vec<String>>,
        stopped_ids: Mutex<Vec<BackgroundProcessId>>,
    }

    impl BackgroundProcessControl for FakeBackgroundControl {
        fn list(&self) -> Vec<BackgroundProcessSummary> {
            Vec::new()
        }

        fn read(
            &self,
            id: &BackgroundProcessId,
        ) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError> {
            let mut reads = self.stderr_reads.lock().expect("reads lock");
            let stderr = if reads.len() > 1 {
                reads.remove(0)
            } else {
                reads.first().cloned().unwrap_or_default()
            };
            let summary = BackgroundProcessSummary::new(
                id.clone(),
                "chromium",
                None,
                BackgroundProcessState::Running { pid: 4242 },
            );
            Ok(BackgroundProcessOutput::new(
                summary, "", stderr, false, false,
            ))
        }

        fn stop(
            &self,
            id: &BackgroundProcessId,
        ) -> Result<BackgroundProcessStop, BackgroundProcessLookupError> {
            self.stopped_ids.lock().expect("stop lock").push(id.clone());
            let summary = BackgroundProcessSummary::new(
                id.clone(),
                "chromium",
                None,
                BackgroundProcessState::Killed,
            );
            Ok(BackgroundProcessStop::new(summary, true))
        }
    }

    struct FakeBrowserRunner {
        control: Arc<FakeBackgroundControl>,
        captured_intents: Mutex<Vec<ProcessActionIntent>>,
        fail_launch: bool,
    }

    impl ProcessRunner for FakeBrowserRunner {
        fn run<'a>(
            &'a self,
            intent: ProcessActionIntent,
            _context: ProcessRunnerContext,
        ) -> ProcessRunnerFuture<'a> {
            Box::pin(async move {
                self.captured_intents
                    .lock()
                    .expect("intents lock")
                    .push(intent);
                if self.fail_launch {
                    return Err(ProcessRunnerError::infrastructure(
                        "process execution disabled",
                    ));
                }
                let bg_id = BackgroundProcessId::new("bg-chrome-1").expect("valid id");
                let intent_ref = self.captured_intents.lock().expect("intents lock");
                let output = ProcessRunnerOutput::new(
                    &intent_ref[intent_ref.len() - 1],
                    ProcessExitStatus::Running,
                    "",
                    false,
                    "",
                    false,
                )
                .expect("valid process output")
                .with_background_process_id(bg_id);
                Ok(output)
            })
        }

        fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
            Some(Arc::clone(&self.control) as Arc<dyn BackgroundProcessControl>)
        }
    }

    #[tokio::test]
    async fn process_runner_launcher_routes_chromium_through_runner_and_stops_on_shutdown() {
        let control = Arc::new(FakeBackgroundControl {
            stderr_reads: Mutex::new(vec![
                "starting headless chrome\n".to_owned(),
                "DevTools listening on ws://127.0.0.1:9222/devtools/browser/test-id\n".to_owned(),
            ]),
            stopped_ids: Mutex::new(Vec::new()),
        });
        let runner = Arc::new(FakeBrowserRunner {
            control: Arc::clone(&control),
            captured_intents: Mutex::new(Vec::new()),
            fail_launch: false,
        });
        let launcher =
            ProcessRunnerBrowserLauncher::new(Arc::clone(&runner) as Arc<dyn ProcessRunner>);

        let mut handle = launcher
            .launch(BrowserLaunchSpec {
                executable: PathBuf::from("/usr/bin/chromium"),
                args: vec!["--headless=new".to_owned(), "about:blank".to_owned()],
                profile_dir: None,
            })
            .await
            .expect("launch through process runner should succeed");

        let ws_url = handle
            .wait_for_devtools_ws_url(Duration::from_secs(2))
            .await
            .expect("should parse DevTools URL from background stderr");
        assert_eq!(ws_url, "ws://127.0.0.1:9222/devtools/browser/test-id");

        {
            let intents = runner.captured_intents.lock().expect("intents lock");
            assert_eq!(intents.len(), 1);
            assert!(intents[0].background());
            assert_eq!(
                intents[0].argv(),
                ["/usr/bin/chromium", "--headless=new", "about:blank"]
            );
        }

        handle.shutdown().await;
        let stopped = control.stopped_ids.lock().expect("stopped lock");
        assert_eq!(stopped.len(), 1);
        assert_eq!(stopped[0].as_str(), "bg-chrome-1");
    }

    #[tokio::test]
    async fn process_runner_launcher_fails_closed_when_runner_rejects_spawn() {
        let control = Arc::new(FakeBackgroundControl {
            stderr_reads: Mutex::new(Vec::new()),
            stopped_ids: Mutex::new(Vec::new()),
        });
        let runner = Arc::new(FakeBrowserRunner {
            control,
            captured_intents: Mutex::new(Vec::new()),
            fail_launch: true,
        });
        let launcher = ProcessRunnerBrowserLauncher::new(runner);

        let err = launcher
            .launch(BrowserLaunchSpec {
                executable: PathBuf::from("/usr/bin/chromium"),
                args: vec!["--headless=new".to_owned()],
                profile_dir: None,
            })
            .await
            .err()
            .expect("disabled runner must fail closed");
        assert!(err.contains("process execution disabled"));
    }
}