kovence-cli 1.0.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,722 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { spawn } = require("node:child_process");
6
+ const { resolvePaths } = require("../config/paths");
7
+
8
+ let _testBrowserDriver = null;
9
+
10
+ const session = {
11
+ browser: null,
12
+ context: null,
13
+ page: null,
14
+ consoleLogs: [],
15
+ pageErrors: [],
16
+ networkErrors: [],
17
+ cursor: { console: 0, pageError: 0, networkError: 0 },
18
+ idleTimer: null,
19
+ runtimeDir: "",
20
+ };
21
+
22
+ const IDLE_TIMEOUT_MS = 5 * 60 * 1000;
23
+
24
+ /**
25
+ * Inject a mock Playwright-compatible driver during automated tests.
26
+ */
27
+ function setBrowserDriverForTests(driver) {
28
+ _testBrowserDriver = driver || null;
29
+ }
30
+
31
+ /**
32
+ * Resolve the isolated global runtime directory for on-demand Playwright installation.
33
+ */
34
+ function getBrowserRuntimeDir(paths = null) {
35
+ const globalDir = paths?.globalDir || resolvePaths().globalDir;
36
+ const runtimeDir = path.join(globalDir, "browser");
37
+ const browsersPath = path.join(runtimeDir, "ms-playwright");
38
+ return { runtimeDir, browsersPath };
39
+ }
40
+
41
+ /**
42
+ * Search common OS install locations and PATH for an existing Chrome/Chromium/Edge binary.
43
+ */
44
+ function findSystemChromiumExecutable() {
45
+ const envCandidates = [process.env.KOVENCE_CHROME_PATH, process.env.CHROME_PATH].filter(Boolean);
46
+ for (const p of envCandidates) {
47
+ if (fs.existsSync(p)) return p;
48
+ }
49
+
50
+ const candidates = [];
51
+ if (process.platform === "darwin") {
52
+ candidates.push(
53
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
54
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
55
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
56
+ );
57
+ } else if (process.platform === "win32") {
58
+ const roots = [process.env.PROGRAMFILES, process.env["PROGRAMFILES(X86)"], process.env.LOCALAPPDATA].filter(
59
+ Boolean
60
+ );
61
+ for (const root of roots) {
62
+ candidates.push(
63
+ path.join(root, "Google", "Chrome", "Application", "chrome.exe"),
64
+ path.join(root, "Chromium", "Application", "chrome.exe"),
65
+ path.join(root, "Microsoft", "Edge", "Application", "msedge.exe")
66
+ );
67
+ }
68
+ } else {
69
+ const bins = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"];
70
+ const pathDirs = String(process.env.PATH || "")
71
+ .split(path.delimiter)
72
+ .filter(Boolean);
73
+ for (const dir of pathDirs) {
74
+ for (const b of bins) {
75
+ candidates.push(path.join(dir, b));
76
+ }
77
+ }
78
+ candidates.push(
79
+ "/usr/bin/google-chrome",
80
+ "/usr/bin/google-chrome-stable",
81
+ "/usr/bin/chromium",
82
+ "/usr/bin/chromium-browser",
83
+ "/snap/bin/chromium",
84
+ "/usr/bin/microsoft-edge"
85
+ );
86
+ }
87
+
88
+ for (const p of candidates) {
89
+ try {
90
+ if (p && fs.existsSync(p)) return p;
91
+ } catch {
92
+ // Skip unreadable candidates
93
+ }
94
+ }
95
+ return "";
96
+ }
97
+
98
+ /**
99
+ * Resolve playwright-core or playwright from isolated runtime dir or local Node resolution.
100
+ */
101
+ function resolvePlaywright(runtimeDir) {
102
+ if (_testBrowserDriver) {
103
+ return {
104
+ driver: _testBrowserDriver,
105
+ source: "test-mock",
106
+ modulePath: "(mock)",
107
+ };
108
+ }
109
+
110
+ const isolatedCandidates = [
111
+ path.join(runtimeDir, "node_modules", "playwright-core"),
112
+ path.join(runtimeDir, "node_modules", "playwright"),
113
+ ];
114
+ for (const modPath of isolatedCandidates) {
115
+ if (fs.existsSync(modPath)) {
116
+ try {
117
+ const mod = require(modPath);
118
+ return { driver: mod, source: "isolated", modulePath: modPath };
119
+ } catch {
120
+ // Continue to next candidate
121
+ }
122
+ }
123
+ }
124
+
125
+ for (const pkgName of ["playwright-core", "playwright"]) {
126
+ try {
127
+ const resolvedPath = require.resolve(pkgName);
128
+ const mod = require(resolvedPath);
129
+ return { driver: mod, source: "node", modulePath: resolvedPath };
130
+ } catch {
131
+ // Not installed
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+
137
+ function getBundledChromiumExecutable(driver, browsersPath) {
138
+ if (!driver || !driver.chromium || typeof driver.chromium.executablePath !== "function") return "";
139
+ const prev = process.env.PLAYWRIGHT_BROWSERS_PATH;
140
+ try {
141
+ if (browsersPath) process.env.PLAYWRIGHT_BROWSERS_PATH = browsersPath;
142
+ const p = driver.chromium.executablePath();
143
+ return p && fs.existsSync(p) ? p : "";
144
+ } catch {
145
+ return "";
146
+ } finally {
147
+ if (prev === undefined) delete process.env.PLAYWRIGHT_BROWSERS_PATH;
148
+ else process.env.PLAYWRIGHT_BROWSERS_PATH = prev;
149
+ }
150
+ }
151
+
152
+ function runCommandAsync(cmd, args, { cwd, env, signal, onOutput } = {}) {
153
+ return new Promise((resolve, reject) => {
154
+ if (signal?.aborted) {
155
+ reject(signal.reason || new Error("Aborted"));
156
+ return;
157
+ }
158
+ const child = spawn(cmd, args, {
159
+ cwd,
160
+ env,
161
+ shell: process.platform === "win32",
162
+ stdio: ["ignore", "pipe", "pipe"],
163
+ });
164
+
165
+ let stderr = "";
166
+ let settled = false;
167
+
168
+ const onAbort = () => {
169
+ if (settled) return;
170
+ settled = true;
171
+ try {
172
+ child.kill("SIGTERM");
173
+ } catch {}
174
+ reject(signal.reason || new Error("Browser runtime installation aborted."));
175
+ };
176
+
177
+ signal?.addEventListener("abort", onAbort, { once: true });
178
+
179
+ child.stdout?.on("data", (d) => {
180
+ onOutput?.(String(d));
181
+ });
182
+ child.stderr?.on("data", (d) => {
183
+ const s = String(d);
184
+ stderr += s;
185
+ if (stderr.length > 8000) stderr = stderr.slice(-8000);
186
+ onOutput?.(s);
187
+ });
188
+ child.on("error", (err) => {
189
+ signal?.removeEventListener("abort", onAbort);
190
+ if (settled) return;
191
+ settled = true;
192
+ reject(err);
193
+ });
194
+ child.on("close", (code) => {
195
+ signal?.removeEventListener("abort", onAbort);
196
+ if (settled) return;
197
+ settled = true;
198
+ if (code === 0) resolve();
199
+ else reject(new Error(`${cmd} ${args.join(" ")} exited with code ${code}: ${stderr.trim().slice(-500)}`));
200
+ });
201
+ });
202
+ }
203
+
204
+ /**
205
+ * Get current Playwright & browser availability without modifying disk.
206
+ */
207
+ function getBrowserStatus({ paths = null } = {}) {
208
+ const { runtimeDir, browsersPath } = getBrowserRuntimeDir(paths);
209
+ const resolved = resolvePlaywright(runtimeDir);
210
+ const systemExe = findSystemChromiumExecutable();
211
+ const bundledExe = resolved ? getBundledChromiumExecutable(resolved.driver, browsersPath) : "";
212
+ return {
213
+ playwrightInstalled: Boolean(resolved),
214
+ source: resolved?.source || "none",
215
+ modulePath: resolved?.modulePath || "",
216
+ runtimeDir,
217
+ browsersPath,
218
+ systemExecutable: systemExe,
219
+ bundledExecutable: bundledExe,
220
+ executablePath: systemExe || bundledExe || "",
221
+ ready: Boolean(resolved && (resolved.source === "test-mock" || systemExe || bundledExe)),
222
+ sessionOpen: Boolean(session.browser && session.page),
223
+ activeUrl: session.page && typeof session.page.url === "function" ? session.page.url() : "",
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Ensure playwright-core (isolated in globalDir/browser) and a Chromium binary are available on demand.
229
+ */
230
+ async function ensurePlaywrightInstalled({
231
+ paths = null,
232
+ ctx = null,
233
+ onOutput = null,
234
+ installBrowserBinary = false,
235
+ } = {}) {
236
+ const { runtimeDir, browsersPath } = getBrowserRuntimeDir(paths);
237
+ let resolved = resolvePlaywright(runtimeDir);
238
+ if (resolved?.source === "test-mock") {
239
+ return {
240
+ installed: true,
241
+ alreadyInstalled: true,
242
+ driver: resolved.driver,
243
+ runtimeDir,
244
+ browsersPath,
245
+ executablePath: "(mock)",
246
+ source: "test-mock",
247
+ };
248
+ }
249
+
250
+ let systemExe = findSystemChromiumExecutable();
251
+ let bundledExe = resolved ? getBundledChromiumExecutable(resolved.driver, browsersPath) : "";
252
+ if (resolved && (systemExe || bundledExe) && !installBrowserBinary) {
253
+ return {
254
+ installed: true,
255
+ alreadyInstalled: true,
256
+ driver: resolved.driver,
257
+ runtimeDir,
258
+ browsersPath,
259
+ executablePath: systemExe || bundledExe,
260
+ source: resolved.source,
261
+ };
262
+ }
263
+
264
+ if (ctx?.signal?.aborted) {
265
+ throw ctx.signal.reason || new Error("Aborted");
266
+ }
267
+
268
+ fs.mkdirSync(runtimeDir, { recursive: true });
269
+ const pkgPath = path.join(runtimeDir, "package.json");
270
+ if (!fs.existsSync(pkgPath)) {
271
+ fs.writeFileSync(
272
+ pkgPath,
273
+ JSON.stringify({ name: "kovence-browser-runtime", private: true, version: "1.0.0" }, null, 2) + "\n",
274
+ "utf8"
275
+ );
276
+ }
277
+
278
+ const logMsg = (msg) => {
279
+ ctx?.log?.("meta", msg);
280
+ onOutput?.(`${msg}\n`);
281
+ };
282
+
283
+ if (!resolved) {
284
+ ctx?.setBusy?.("Installing playwright-core (on-demand)...");
285
+ logMsg(`Installing playwright-core into ${runtimeDir} (one-time setup)...`);
286
+ await runCommandAsync(
287
+ "npm",
288
+ ["install", "--prefix", runtimeDir, "--no-save", "--no-audit", "--no-fund", "playwright-core"],
289
+ {
290
+ cwd: runtimeDir,
291
+ env: { ...process.env, PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" },
292
+ signal: ctx?.signal,
293
+ onOutput,
294
+ }
295
+ );
296
+ resolved = resolvePlaywright(runtimeDir);
297
+ if (!resolved) {
298
+ throw new Error(`Installed playwright-core into ${runtimeDir}, but failed to load it.`);
299
+ }
300
+ }
301
+
302
+ systemExe = findSystemChromiumExecutable();
303
+ bundledExe = getBundledChromiumExecutable(resolved.driver, browsersPath);
304
+
305
+ if (installBrowserBinary || (!systemExe && !bundledExe)) {
306
+ ctx?.setBusy?.("Downloading headless Chromium browser...");
307
+ logMsg(`No usable system Chromium found; installing Playwright Chromium into ${browsersPath}...`);
308
+ await runCommandAsync("npx", ["--prefix", runtimeDir, "playwright-core", "install", "chromium"], {
309
+ cwd: runtimeDir,
310
+ env: { ...process.env, PLAYWRIGHT_BROWSERS_PATH: browsersPath },
311
+ signal: ctx?.signal,
312
+ onOutput,
313
+ });
314
+ bundledExe = getBundledChromiumExecutable(resolved.driver, browsersPath);
315
+ }
316
+
317
+ return {
318
+ installed: true,
319
+ alreadyInstalled: false,
320
+ driver: resolved.driver,
321
+ runtimeDir,
322
+ browsersPath,
323
+ executablePath: systemExe || bundledExe || "",
324
+ source: resolved.source,
325
+ };
326
+ }
327
+
328
+ function resetIdleTimer() {
329
+ if (session.idleTimer) clearTimeout(session.idleTimer);
330
+ session.idleTimer = setTimeout(() => {
331
+ closeBrowserSession().catch(() => {});
332
+ }, IDLE_TIMEOUT_MS);
333
+ if (typeof session.idleTimer.unref === "function") session.idleTimer.unref();
334
+ }
335
+
336
+ async function closeBrowserSession() {
337
+ if (session.idleTimer) {
338
+ clearTimeout(session.idleTimer);
339
+ session.idleTimer = null;
340
+ }
341
+ const browser = session.browser;
342
+ session.browser = null;
343
+ session.context = null;
344
+ session.page = null;
345
+ session.consoleLogs = [];
346
+ session.pageErrors = [];
347
+ session.networkErrors = [];
348
+ session.cursor = { console: 0, pageError: 0, networkError: 0 };
349
+ session.runtimeDir = "";
350
+ if (browser && typeof browser.close === "function") {
351
+ try {
352
+ await browser.close();
353
+ } catch {}
354
+ }
355
+ }
356
+
357
+ function attachPageListeners(page) {
358
+ if (!page || typeof page.on !== "function") return;
359
+ page.on("console", (msg) => {
360
+ try {
361
+ const type = typeof msg.type === "function" ? msg.type() : String(msg?.type || "log");
362
+ const text = typeof msg.text === "function" ? msg.text() : String(msg?.text || "");
363
+ session.consoleLogs.push({ type, text, ts: Date.now() });
364
+ if (session.consoleLogs.length > 200) session.consoleLogs.shift();
365
+ } catch {}
366
+ });
367
+ page.on("pageerror", (err) => {
368
+ const text = err?.message || String(err);
369
+ session.pageErrors.push({ text, ts: Date.now() });
370
+ if (session.pageErrors.length > 100) session.pageErrors.shift();
371
+ });
372
+ page.on("requestfailed", (req) => {
373
+ try {
374
+ const url = typeof req.url === "function" ? req.url() : String(req?.url || "");
375
+ const errText =
376
+ (typeof req.failure === "function" ? req.failure()?.errorText : req?.failureText) || "request failed";
377
+ session.networkErrors.push({ status: 0, url, text: errText, ts: Date.now() });
378
+ if (session.networkErrors.length > 100) session.networkErrors.shift();
379
+ } catch {}
380
+ });
381
+ page.on("response", (res) => {
382
+ try {
383
+ const status = typeof res.status === "function" ? res.status() : Number(res?.status || 0);
384
+ if (status >= 400) {
385
+ const url = typeof res.url === "function" ? res.url() : String(res?.url || "");
386
+ session.networkErrors.push({ status, url, text: `HTTP ${status}`, ts: Date.now() });
387
+ if (session.networkErrors.length > 100) session.networkErrors.shift();
388
+ }
389
+ } catch {}
390
+ });
391
+ }
392
+
393
+ async function ensureActivePage({ paths = null, ctx = null, width = 1280, height = 800, device = "desktop" } = {}) {
394
+ const setup = await ensurePlaywrightInstalled({ paths, ctx, onOutput: ctx?.onToolOutput });
395
+ const viewport =
396
+ device === "mobile"
397
+ ? { width: Number(width) || 390, height: Number(height) || 844 }
398
+ : { width: Number(width) || 1280, height: Number(height) || 800 };
399
+
400
+ if (session.browser && session.page) {
401
+ if (typeof session.page.isClosed !== "function" || !session.page.isClosed()) {
402
+ if (typeof session.page.setViewportSize === "function") {
403
+ await session.page.setViewportSize(viewport);
404
+ }
405
+ resetIdleTimer();
406
+ return { page: session.page, setup };
407
+ }
408
+ }
409
+
410
+ await closeBrowserSession();
411
+ const launchOpts = { headless: true };
412
+ if (setup.executablePath && setup.executablePath !== "(mock)") {
413
+ launchOpts.executablePath = setup.executablePath;
414
+ }
415
+
416
+ const prevBrowsersPath = process.env.PLAYWRIGHT_BROWSERS_PATH;
417
+ if (setup.browsersPath) process.env.PLAYWRIGHT_BROWSERS_PATH = setup.browsersPath;
418
+ let browser;
419
+ try {
420
+ browser = await setup.driver.chromium.launch(launchOpts);
421
+ } finally {
422
+ if (prevBrowsersPath === undefined) delete process.env.PLAYWRIGHT_BROWSERS_PATH;
423
+ else process.env.PLAYWRIGHT_BROWSERS_PATH = prevBrowsersPath;
424
+ }
425
+
426
+ const context =
427
+ typeof browser.newContext === "function"
428
+ ? await browser.newContext({ viewport })
429
+ : { newPage: () => browser.newPage({ viewport }) };
430
+ const page = await context.newPage();
431
+
432
+ session.browser = browser;
433
+ session.context = context;
434
+ session.page = page;
435
+ session.runtimeDir = setup.runtimeDir;
436
+ attachPageListeners(page);
437
+ resetIdleTimer();
438
+ return { page, setup };
439
+ }
440
+
441
+ function normalizeUrl(rawUrl) {
442
+ const u = String(rawUrl || "").trim();
443
+ if (!u) return "";
444
+ if (/^(https?:|file:|about:|data:)/i.test(u)) return u;
445
+ return `http://${u}`;
446
+ }
447
+
448
+ function resolveScreenshotPath(outputPath, workspaceRoot) {
449
+ const root = path.resolve(workspaceRoot || process.cwd());
450
+ if (outputPath) {
451
+ const target = path.resolve(root, String(outputPath));
452
+ const rel = path.relative(root, target);
453
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
454
+ throw new Error(`Screenshot output_path '${outputPath}' escapes workspace root.`);
455
+ }
456
+ return { abs: target, rel: rel.replace(/\\/g, "/") };
457
+ }
458
+ const dir = path.join(root, ".kovence", "screenshots");
459
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
460
+ const abs = path.join(dir, `screenshot-${stamp}.png`);
461
+ const rel = path.relative(root, abs).replace(/\\/g, "/");
462
+ return { abs, rel };
463
+ }
464
+
465
+ function consumeRecentTelemetry() {
466
+ const newConsole = session.consoleLogs.slice(session.cursor.console);
467
+ const newPageErrors = session.pageErrors.slice(session.cursor.pageError);
468
+ const newNetErrors = session.networkErrors.slice(session.cursor.networkError);
469
+ session.cursor.console = session.consoleLogs.length;
470
+ session.cursor.pageError = session.pageErrors.length;
471
+ session.cursor.networkError = session.networkErrors.length;
472
+ return { newConsole, newPageErrors, newNetErrors };
473
+ }
474
+
475
+ async function inspectPageDom(page) {
476
+ if (!page || typeof page.evaluate !== "function") return null;
477
+ try {
478
+ return await page.evaluate(() => {
479
+ /* global window, document */
480
+ const title = document.title || "";
481
+ const url = window.location?.href || "";
482
+ const headings = [...document.querySelectorAll("h1, h2, h3")]
483
+ .slice(0, 12)
484
+ .map((el) => `${el.tagName.toLowerCase()}: ${(el.textContent || "").trim().slice(0, 100)}`)
485
+ .filter((x) => !x.endsWith(": "));
486
+ const interactive = [...document.querySelectorAll("a, button, input, select, textarea")]
487
+ .slice(0, 20)
488
+ .map((el) => {
489
+ const tag = el.tagName.toLowerCase();
490
+ const label = (
491
+ el.getAttribute("aria-label") ||
492
+ el.textContent ||
493
+ el.getAttribute("placeholder") ||
494
+ el.getAttribute("name") ||
495
+ ""
496
+ )
497
+ .trim()
498
+ .replace(/\s+/g, " ")
499
+ .slice(0, 60);
500
+ const idPart = el.id ? `#${el.id}` : "";
501
+ return `${tag}${idPart}${label ? `("${label}")` : ""}`;
502
+ });
503
+ const textPreview = String(document.body?.innerText || "")
504
+ .replace(/\s+/g, " ")
505
+ .trim()
506
+ .slice(0, 800);
507
+ return { title, url, headings, interactive, textPreview };
508
+ });
509
+ } catch {
510
+ return null;
511
+ }
512
+ }
513
+
514
+ async function captureAndFormatReport({
515
+ page,
516
+ actionLabel,
517
+ fullPage = false,
518
+ outputPath = "",
519
+ workspaceRoot = process.cwd(),
520
+ ctx = null,
521
+ takeScreenshot = true,
522
+ }) {
523
+ const lines = [];
524
+ const currentUrl = typeof page.url === "function" ? page.url() : "";
525
+ const title = typeof page.title === "function" ? await page.title() : "";
526
+ lines.push(`[Browser ${actionLabel}] URL: ${currentUrl || "(unknown)"}${title ? ` | Title: ${title}` : ""}`);
527
+
528
+ if (takeScreenshot && typeof page.screenshot === "function") {
529
+ const { abs, rel } = resolveScreenshotPath(outputPath, workspaceRoot);
530
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
531
+ const rawShot = await page.screenshot({ path: abs, fullPage: Boolean(fullPage) });
532
+ let buf = Buffer.isBuffer(rawShot) ? rawShot : null;
533
+ if (!buf && fs.existsSync(abs)) {
534
+ buf = fs.readFileSync(abs);
535
+ } else if (buf && !fs.existsSync(abs)) {
536
+ fs.writeFileSync(abs, buf);
537
+ }
538
+ if (buf && buf.length > 0) {
539
+ ctx?.attachToolImage?.({
540
+ mediaType: "image/png",
541
+ data: buf.toString("base64"),
542
+ path: rel,
543
+ });
544
+ lines.push(`Screenshot saved: ${rel} (${buf.length} bytes, attached for visual inspection)`);
545
+ }
546
+ }
547
+
548
+ const dom = await inspectPageDom(page);
549
+ if (dom) {
550
+ if (dom.headings?.length) lines.push(`Headings: ${dom.headings.join(" | ")}`);
551
+ if (dom.interactive?.length) lines.push(`Interactive elements: ${dom.interactive.join(", ")}`);
552
+ if (dom.textPreview) lines.push(`Visible text preview: ${dom.textPreview}`);
553
+ }
554
+
555
+ const { newConsole, newPageErrors, newNetErrors } = consumeRecentTelemetry();
556
+ const consoleErrs = newConsole.filter((c) => c.type === "error" || c.type === "warning");
557
+ if (consoleErrs.length) {
558
+ lines.push(`Console diagnostics (${consoleErrs.length}):`);
559
+ for (const c of consoleErrs.slice(-15)) lines.push(` [${c.type}] ${c.text}`);
560
+ }
561
+ if (newPageErrors.length) {
562
+ lines.push(`Uncaught page errors (${newPageErrors.length}):`);
563
+ for (const e of newPageErrors.slice(-15)) lines.push(` [pageerror] ${e.text}`);
564
+ }
565
+ if (newNetErrors.length) {
566
+ lines.push(`Network failures (${newNetErrors.length}):`);
567
+ for (const n of newNetErrors.slice(-15)) lines.push(` [${n.status || "ERR"}] ${n.text} ${n.url}`);
568
+ }
569
+ if (!consoleErrs.length && !newPageErrors.length && !newNetErrors.length) {
570
+ lines.push("Console/Page/Network errors: none.");
571
+ }
572
+ return lines.join("\n");
573
+ }
574
+
575
+ /**
576
+ * Execute the `browser` tool actions cleanly with on-demand Playwright installation.
577
+ */
578
+ async function runBrowserTool(args = {}, ctx = {}) {
579
+ const action = String(args?.action || "open").toLowerCase();
580
+ const paths = ctx?.paths || null;
581
+ const workspaceRoot = ctx?.workspaceRoot || ctx?.cwd || process.cwd();
582
+
583
+ if (action === "status") {
584
+ const st = getBrowserStatus({ paths });
585
+ return [
586
+ `Playwright installed: ${st.playwrightInstalled ? `yes (${st.source})` : "no"}`,
587
+ `Browser executable: ${st.executablePath || "(none cached; will auto-detect or install Chromium on first use)"}`,
588
+ `Runtime dir: ${st.runtimeDir}`,
589
+ `Active session: ${st.sessionOpen ? `open (${st.activeUrl || "blank"})` : "closed"}`,
590
+ ].join("\n");
591
+ }
592
+
593
+ if (action === "install") {
594
+ const res = await ensurePlaywrightInstalled({
595
+ paths,
596
+ ctx,
597
+ onOutput: ctx?.onToolOutput,
598
+ installBrowserBinary: Boolean(args?.install_browser),
599
+ });
600
+ return `Playwright ready (${res.alreadyInstalled ? "already installed" : "installed now"}) in ${res.runtimeDir}\nBrowser executable: ${res.executablePath || "(default Playwright Chromium)"}`;
601
+ }
602
+
603
+ if (action === "close") {
604
+ await closeBrowserSession();
605
+ return "Headless browser session closed.";
606
+ }
607
+
608
+ if (action === "console") {
609
+ const allErrs = {
610
+ console: session.consoleLogs.slice(-40),
611
+ pageErrors: session.pageErrors.slice(-30),
612
+ networkErrors: session.networkErrors.slice(-30),
613
+ };
614
+ return JSON.stringify(allErrs, null, 2);
615
+ }
616
+
617
+ const { page } = await ensureActivePage({
618
+ paths,
619
+ ctx,
620
+ width: args?.width,
621
+ height: args?.height,
622
+ device: args?.device,
623
+ });
624
+
625
+ if (action === "open" || action === "screenshot") {
626
+ const targetUrl = normalizeUrl(args?.url);
627
+ if (targetUrl && typeof page.goto === "function") {
628
+ const waitUntil = args?.wait_until || "networkidle";
629
+ try {
630
+ await page.goto(targetUrl, { waitUntil, timeout: 15000 });
631
+ } catch (navErr) {
632
+ if (waitUntil === "networkidle") {
633
+ await page.goto(targetUrl, { waitUntil: "load", timeout: 15000 });
634
+ } else {
635
+ throw navErr;
636
+ }
637
+ }
638
+ }
639
+ if (args?.wait_for_selector && typeof page.waitForSelector === "function") {
640
+ await page.waitForSelector(String(args.wait_for_selector), { timeout: 10000 });
641
+ }
642
+ if (Number.isFinite(args?.wait_ms) && args.wait_ms > 0) {
643
+ await new Promise((r) => setTimeout(r, Math.min(10000, Number(args.wait_ms))));
644
+ }
645
+ return captureAndFormatReport({
646
+ page,
647
+ actionLabel: action,
648
+ fullPage: Boolean(args?.full_page),
649
+ outputPath: args?.output_path,
650
+ workspaceRoot,
651
+ ctx,
652
+ takeScreenshot: args?.screenshot !== false,
653
+ });
654
+ }
655
+
656
+ if (action === "click") {
657
+ if (!args?.selector) throw new Error("browser(click) requires 'selector'.");
658
+ await page.click(String(args.selector), { timeout: 10000 });
659
+ if (Number.isFinite(args?.wait_ms) && args.wait_ms > 0) {
660
+ await new Promise((r) => setTimeout(r, Math.min(5000, Number(args.wait_ms))));
661
+ }
662
+ return captureAndFormatReport({
663
+ page,
664
+ actionLabel: `click(${args.selector})`,
665
+ fullPage: Boolean(args?.full_page),
666
+ outputPath: args?.output_path,
667
+ workspaceRoot,
668
+ ctx,
669
+ takeScreenshot: args?.screenshot !== false,
670
+ });
671
+ }
672
+
673
+ if (action === "type") {
674
+ if (!args?.selector) throw new Error("browser(type) requires 'selector'.");
675
+ await page.fill(String(args.selector), String(args?.text ?? ""), { timeout: 10000 });
676
+ if (args?.press_enter && page.keyboard?.press) {
677
+ await page.keyboard.press("Enter");
678
+ }
679
+ if (Number.isFinite(args?.wait_ms) && args.wait_ms > 0) {
680
+ await new Promise((r) => setTimeout(r, Math.min(5000, Number(args.wait_ms))));
681
+ }
682
+ return captureAndFormatReport({
683
+ page,
684
+ actionLabel: `type(${args.selector})`,
685
+ fullPage: Boolean(args?.full_page),
686
+ outputPath: args?.output_path,
687
+ workspaceRoot,
688
+ ctx,
689
+ takeScreenshot: args?.screenshot !== false,
690
+ });
691
+ }
692
+
693
+ if (action === "evaluate") {
694
+ if (!args?.script) throw new Error("browser(evaluate) requires 'script'.");
695
+ const fn = new Function(`return (${String(args.script)})`);
696
+ const evalRes = await page.evaluate(fn);
697
+ const { newConsole, newPageErrors, newNetErrors } = consumeRecentTelemetry();
698
+ return JSON.stringify(
699
+ {
700
+ result: evalRes,
701
+ consoleDiagnostics: newConsole.filter((c) => c.type === "error" || c.type === "warning").slice(-10),
702
+ pageErrors: newPageErrors.slice(-10),
703
+ networkErrors: newNetErrors.slice(-10),
704
+ },
705
+ null,
706
+ 2
707
+ );
708
+ }
709
+
710
+ throw new Error(`Unsupported browser action '${action}'.`);
711
+ }
712
+
713
+ module.exports = {
714
+ getBrowserRuntimeDir,
715
+ findSystemChromiumExecutable,
716
+ resolvePlaywright,
717
+ getBrowserStatus,
718
+ ensurePlaywrightInstalled,
719
+ closeBrowserSession,
720
+ runBrowserTool,
721
+ setBrowserDriverForTests,
722
+ };