dsh-plugin-browser4agent 0.0.0-stage → 0.1.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.
package/lib/setup.js ADDED
@@ -0,0 +1,902 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import {
4
+ accessSync,
5
+ chmodSync,
6
+ constants as fsConstants,
7
+ existsSync,
8
+ mkdirSync,
9
+ readFileSync,
10
+ renameSync,
11
+ rmSync,
12
+ writeFileSync,
13
+ } from 'node:fs';
14
+ import { arch, homedir } from 'node:os';
15
+ import { delimiter, dirname, join, resolve } from 'node:path';
16
+
17
+ export const B4A_HOST_NAME = 'browser4agent';
18
+ export const B4A_MCP_URL = 'http://127.0.0.1:39271/mcp';
19
+ export const RELEASE_BASE_URL =
20
+ 'https://github.com/mantou132/browser4agent/releases/latest/download';
21
+
22
+ export const EXTENSION_STORE_LINKS = {
23
+ chrome:
24
+ 'https://chromewebstore.google.com/detail/cddjomjjojijahpjngcfebapepdecaff',
25
+ edge: 'https://microsoftedge.microsoft.com/addons/detail/kgofhkkibnooojbchfppjblmajdcboib',
26
+ firefox:
27
+ 'https://addons.mozilla.org/firefox/addon/browser4agent@xianqiao.wang',
28
+ releases: 'https://github.com/mantou132/browser4agent/releases/latest',
29
+ repo: 'https://github.com/mantou132/browser4agent',
30
+ };
31
+
32
+ /**
33
+ * Resolve Browser4Agent's local data directory, matching `dirs::data_local_dir()/browser4agent`.
34
+ */
35
+ export function getBrowser4AgentDataDir({
36
+ platform = process.platform,
37
+ env = process.env,
38
+ home = homedir(),
39
+ } = {}) {
40
+ if (platform === 'darwin') {
41
+ return join(home, 'Library', 'Application Support', 'browser4agent');
42
+ }
43
+ if (platform === 'win32') {
44
+ const localAppData = env.LOCALAPPDATA || join(home, 'AppData', 'Local');
45
+ return join(localAppData, 'browser4agent');
46
+ }
47
+ const xdgDataHome = env.XDG_DATA_HOME || join(home, '.local', 'share');
48
+ return join(xdgDataHome, 'browser4agent');
49
+ }
50
+
51
+ export function getManagedBinaryPath({
52
+ dataDir = getBrowser4AgentDataDir(),
53
+ platform = process.platform,
54
+ } = {}) {
55
+ const exe = platform === 'win32' ? 'browser4agent.exe' : 'browser4agent';
56
+ return join(dataDir, 'bin', exe);
57
+ }
58
+
59
+ export function getReleaseAssetSpec(
60
+ platform = process.platform,
61
+ cpu = arch(),
62
+ ) {
63
+ if (platform === 'darwin' && cpu === 'arm64') {
64
+ return {
65
+ asset: 'browser4agent-aarch64-apple-darwin.tar.gz',
66
+ format: 'tar.gz',
67
+ exeName: 'browser4agent',
68
+ };
69
+ }
70
+ if (platform === 'darwin' && cpu === 'x64') {
71
+ return {
72
+ asset: 'browser4agent-x86_64-apple-darwin.tar.gz',
73
+ format: 'tar.gz',
74
+ exeName: 'browser4agent',
75
+ };
76
+ }
77
+ if (platform === 'linux' && cpu === 'x64') {
78
+ return {
79
+ asset: 'browser4agent-x86_64-unknown-linux-gnu.tar.gz',
80
+ format: 'tar.gz',
81
+ exeName: 'browser4agent',
82
+ };
83
+ }
84
+ if (platform === 'win32' && cpu === 'x64') {
85
+ return {
86
+ asset: 'browser4agent-x86_64-pc-windows-msvc.zip',
87
+ format: 'zip',
88
+ exeName: 'browser4agent.exe',
89
+ };
90
+ }
91
+ return null;
92
+ }
93
+
94
+ function isExecutableFile(filePath, platform = process.platform) {
95
+ if (!filePath || !existsSync(filePath)) return false;
96
+ if (platform === 'win32') return true;
97
+ try {
98
+ accessSync(filePath, fsConstants.X_OK);
99
+ return true;
100
+ } catch {
101
+ return false;
102
+ }
103
+ }
104
+
105
+ export function findExecutable(
106
+ name,
107
+ {
108
+ platform = process.platform,
109
+ env = process.env,
110
+ home = homedir(),
111
+ extraDirs = [],
112
+ } = {},
113
+ ) {
114
+ const candidates =
115
+ platform === 'win32'
116
+ ? [`${name}.exe`, `${name}.cmd`, `${name}.bat`, name]
117
+ : [name];
118
+ const pathDirs = (env.PATH || '').split(delimiter).filter(Boolean);
119
+ const fallbackDirs =
120
+ platform === 'win32'
121
+ ? [
122
+ join(home, 'scoop', 'shims'),
123
+ join(home, '.cargo', 'bin'),
124
+ join(home, '.local', 'bin'),
125
+ ]
126
+ : [
127
+ join(home, '.local', 'bin'),
128
+ '/opt/homebrew/bin',
129
+ '/usr/local/bin',
130
+ join(home, '.cargo', 'bin'),
131
+ ];
132
+
133
+ const seen = new Set();
134
+ for (const dir of [...extraDirs, ...pathDirs, ...fallbackDirs]) {
135
+ if (!dir || seen.has(dir)) continue;
136
+ seen.add(dir);
137
+ for (const file of candidates) {
138
+ const full = join(dir, file);
139
+ if (isExecutableFile(full, platform)) return full;
140
+ }
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /**
146
+ * Native Messaging Host manifest locations written by `browser4agent`
147
+ * (`src/native_message_setup.rs`).
148
+ */
149
+ export function getNativeHostManifestLocations({
150
+ platform = process.platform,
151
+ env = process.env,
152
+ home = homedir(),
153
+ } = {}) {
154
+ const fileName = `${B4A_HOST_NAME}.json`;
155
+ if (platform === 'darwin') {
156
+ return [
157
+ {
158
+ browser: 'Chrome',
159
+ path: join(
160
+ home,
161
+ 'Library',
162
+ 'Application Support',
163
+ 'Google',
164
+ 'Chrome',
165
+ 'NativeMessagingHosts',
166
+ fileName,
167
+ ),
168
+ },
169
+ {
170
+ browser: 'Chrome Canary',
171
+ path: join(
172
+ home,
173
+ 'Library',
174
+ 'Application Support',
175
+ 'Google',
176
+ 'Chrome Canary',
177
+ 'NativeMessagingHosts',
178
+ fileName,
179
+ ),
180
+ },
181
+ {
182
+ browser: 'Chromium',
183
+ path: join(
184
+ home,
185
+ 'Library',
186
+ 'Application Support',
187
+ 'Chromium',
188
+ 'NativeMessagingHosts',
189
+ fileName,
190
+ ),
191
+ },
192
+ {
193
+ browser: 'Edge',
194
+ path: join(
195
+ home,
196
+ 'Library',
197
+ 'Application Support',
198
+ 'Edge',
199
+ 'NativeMessagingHosts',
200
+ fileName,
201
+ ),
202
+ },
203
+ {
204
+ browser: 'Firefox',
205
+ path: join(
206
+ home,
207
+ 'Library',
208
+ 'Application Support',
209
+ 'Mozilla',
210
+ 'NativeMessagingHosts',
211
+ fileName,
212
+ ),
213
+ },
214
+ {
215
+ browser: 'Vivaldi',
216
+ path: join(
217
+ home,
218
+ 'Library',
219
+ 'Application Support',
220
+ 'Vivaldi',
221
+ 'NativeMessagingHosts',
222
+ fileName,
223
+ ),
224
+ },
225
+ ];
226
+ }
227
+ if (platform === 'linux') {
228
+ return [
229
+ {
230
+ browser: 'Chrome',
231
+ path: join(
232
+ home,
233
+ '.config',
234
+ 'google-chrome',
235
+ 'NativeMessagingHosts',
236
+ fileName,
237
+ ),
238
+ },
239
+ {
240
+ browser: 'Chrome Canary',
241
+ path: join(
242
+ home,
243
+ '.config',
244
+ 'google-chrome-canary',
245
+ 'NativeMessagingHosts',
246
+ fileName,
247
+ ),
248
+ },
249
+ {
250
+ browser: 'Chromium',
251
+ path: join(
252
+ home,
253
+ '.config',
254
+ 'chromium',
255
+ 'NativeMessagingHosts',
256
+ fileName,
257
+ ),
258
+ },
259
+ {
260
+ browser: 'Edge',
261
+ path: join(home, '.config', 'edge', 'NativeMessagingHosts', fileName),
262
+ },
263
+ {
264
+ browser: 'Firefox',
265
+ path: join(home, '.mozilla', 'native-messaging-hosts', fileName),
266
+ },
267
+ {
268
+ browser: 'Vivaldi',
269
+ path: join(
270
+ home,
271
+ '.config',
272
+ 'vivaldi',
273
+ 'NativeMessagingHosts',
274
+ fileName,
275
+ ),
276
+ },
277
+ ];
278
+ }
279
+ if (platform === 'win32') {
280
+ const localAppData = env.LOCALAPPDATA || join(home, 'AppData', 'Local');
281
+ return [
282
+ {
283
+ browser: 'Chrome / Edge',
284
+ path: join(localAppData, 'NativeMessagingHosts', 'Chrome', fileName),
285
+ },
286
+ {
287
+ browser: 'Firefox',
288
+ path: join(localAppData, 'NativeMessagingHosts', 'Firefox', fileName),
289
+ },
290
+ ];
291
+ }
292
+ return [];
293
+ }
294
+
295
+ export function readNativeHostState({
296
+ platform = process.platform,
297
+ env = process.env,
298
+ home = homedir(),
299
+ } = {}) {
300
+ const locations = getNativeHostManifestLocations({ platform, env, home });
301
+ const browsers = [];
302
+ let hostPath = null;
303
+ let totalManifests = 0;
304
+
305
+ for (const loc of locations) {
306
+ if (!existsSync(loc.path)) continue;
307
+ totalManifests += 1;
308
+ try {
309
+ const parsed = JSON.parse(readFileSync(loc.path, 'utf8'));
310
+ const binPath = typeof parsed?.path === 'string' ? parsed.path.trim() : '';
311
+ if (binPath && isExecutableFile(binPath, platform)) {
312
+ browsers.push(loc.browser);
313
+ if (!hostPath) hostPath = binPath;
314
+ }
315
+ } catch {
316
+ // Malformed manifest; treat as invalid so setup can repair it
317
+ }
318
+ }
319
+
320
+ return {
321
+ configured: browsers.length > 0,
322
+ validCount: browsers.length,
323
+ totalManifests,
324
+ browsers,
325
+ hostPath,
326
+ };
327
+ }
328
+
329
+ /**
330
+ * Find `browser4agent` executable from PATH, package manager shims, our
331
+ * managed data directory, or an existing valid Native Messaging Host manifest.
332
+ */
333
+ export function findBrowser4AgentBinary({
334
+ dataDir = getBrowser4AgentDataDir(),
335
+ platform = process.platform,
336
+ env = process.env,
337
+ home = homedir(),
338
+ extraDirs = [],
339
+ } = {}) {
340
+ const managedBinDir = join(dataDir, 'bin');
341
+ const found = findExecutable('browser4agent', {
342
+ platform,
343
+ env,
344
+ home,
345
+ extraDirs: [...extraDirs, managedBinDir],
346
+ });
347
+ if (found) return found;
348
+
349
+ const nativeHost = readNativeHostState({ platform, env, home });
350
+ if (nativeHost.hostPath && isExecutableFile(nativeHost.hostPath, platform)) {
351
+ return nativeHost.hostPath;
352
+ }
353
+
354
+ return null;
355
+ }
356
+
357
+ /**
358
+ * Check whether the DSH-discoverable Skill exists at `~/.agents/skills/browser4agent/SKILL.md`.
359
+ */
360
+ export function readSkillState({
361
+ home = homedir(),
362
+ agentsHome = null,
363
+ } = {}) {
364
+ const base = agentsHome || join(home, '.agents');
365
+ const skillPath = join(base, 'skills', 'browser4agent', 'SKILL.md');
366
+ let installed = false;
367
+ if (existsSync(skillPath)) {
368
+ try {
369
+ const content = readFileSync(skillPath, 'utf8');
370
+ installed = content.trim().length > 0;
371
+ } catch {
372
+ installed = false;
373
+ }
374
+ }
375
+ return {
376
+ installed,
377
+ path: skillPath,
378
+ };
379
+ }
380
+
381
+ export function runCommand(
382
+ cmd,
383
+ args,
384
+ { cwd, env = process.env, timeoutMs = 30_000 } = {},
385
+ ) {
386
+ return new Promise((resolvePromise, rejectPromise) => {
387
+ const child = spawn(cmd, args, {
388
+ cwd,
389
+ env,
390
+ stdio: ['ignore', 'pipe', 'pipe'],
391
+ windowsHide: true,
392
+ });
393
+ let stdout = '';
394
+ let stderr = '';
395
+ let settled = false;
396
+
397
+ const timer =
398
+ timeoutMs > 0
399
+ ? setTimeout(() => {
400
+ if (settled) return;
401
+ settled = true;
402
+ try {
403
+ child.kill('SIGTERM');
404
+ } catch {
405
+ // ignore
406
+ }
407
+ rejectPromise(
408
+ new Error(`Command timed out after ${timeoutMs}ms: ${cmd}`),
409
+ );
410
+ }, timeoutMs)
411
+ : null;
412
+
413
+ child.stdout?.on('data', (chunk) => {
414
+ stdout += chunk.toString('utf8');
415
+ });
416
+ child.stderr?.on('data', (chunk) => {
417
+ stderr += chunk.toString('utf8');
418
+ });
419
+ child.on('error', (err) => {
420
+ if (settled) return;
421
+ settled = true;
422
+ if (timer) clearTimeout(timer);
423
+ rejectPromise(err);
424
+ });
425
+ child.on('close', (code) => {
426
+ if (settled) return;
427
+ settled = true;
428
+ if (timer) clearTimeout(timer);
429
+ resolvePromise({ code: code ?? 1, stdout, stderr });
430
+ });
431
+ });
432
+ }
433
+
434
+ export async function readBinaryVersion(
435
+ binaryPath,
436
+ { runCmd = runCommand } = {},
437
+ ) {
438
+ if (!binaryPath) return null;
439
+ try {
440
+ const res = await runCmd(binaryPath, ['--version'], { timeoutMs: 4000 });
441
+ if (res.code !== 0) return null;
442
+ const text = (res.stdout || res.stderr || '').trim();
443
+ const match = text.match(/browser4agent\s+v?([^\s]+)/i) || text.match(/(\d+\.\d+\.\d+\S*)/);
444
+ return match ? match[1] : text || null;
445
+ } catch {
446
+ return null;
447
+ }
448
+ }
449
+
450
+ /**
451
+ * Download and install the prebuilt `browser4agent` binary from GitHub Releases
452
+ * into `<dataDir>/bin/browser4agent(.exe)` with SHA-256 verification.
453
+ */
454
+ export async function installBrowser4AgentBinary({
455
+ dataDir = getBrowser4AgentDataDir(),
456
+ platform = process.platform,
457
+ cpu = arch(),
458
+ releaseBaseUrl = RELEASE_BASE_URL,
459
+ fetchImpl = globalThis.fetch,
460
+ runCmd = runCommand,
461
+ } = {}) {
462
+ const spec = getReleaseAssetSpec(platform, cpu);
463
+ if (!spec) {
464
+ throw new Error(
465
+ `Unsupported platform/architecture (${platform}/${cpu}) for automatic browser4agent download. Please install browser4agent manually.`,
466
+ );
467
+ }
468
+ if (typeof fetchImpl !== 'function') {
469
+ throw new Error('Global fetch is unavailable in this Node.js runtime.');
470
+ }
471
+
472
+ const binDir = join(dataDir, 'bin');
473
+ mkdirSync(binDir, { recursive: true });
474
+
475
+ const tmpDir = join(
476
+ binDir,
477
+ `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,
478
+ );
479
+ mkdirSync(tmpDir, { recursive: true });
480
+
481
+ const archiveUrl = `${releaseBaseUrl}/${spec.asset}`;
482
+ const shaUrl = `${archiveUrl}.sha256`;
483
+
484
+ try {
485
+ const [archiveRes, shaRes] = await Promise.all([
486
+ fetchImpl(archiveUrl, {
487
+ redirect: 'follow',
488
+ signal: AbortSignal.timeout(60_000),
489
+ }),
490
+ fetchImpl(shaUrl, {
491
+ redirect: 'follow',
492
+ signal: AbortSignal.timeout(30_000),
493
+ }),
494
+ ]);
495
+
496
+ if (!archiveRes.ok) {
497
+ throw new Error(
498
+ `Failed to download ${spec.asset} (HTTP ${archiveRes.status})`,
499
+ );
500
+ }
501
+
502
+ const archiveBuf = Buffer.from(await archiveRes.arrayBuffer());
503
+
504
+ if (shaRes.ok) {
505
+ const expectedSha = (await shaRes.text()).trim().split(/\s+/)[0]?.toLowerCase();
506
+ if (expectedSha && /^[a-f0-9]{64}$/.test(expectedSha)) {
507
+ const actualSha = createHash('sha256').update(archiveBuf).digest('hex');
508
+ if (actualSha !== expectedSha) {
509
+ throw new Error(
510
+ `Checksum mismatch for ${spec.asset} (expected ${expectedSha}, got ${actualSha})`,
511
+ );
512
+ }
513
+ }
514
+ }
515
+
516
+ const archivePath = join(tmpDir, spec.asset);
517
+ const extractDir = join(tmpDir, 'extracted');
518
+ mkdirSync(extractDir, { recursive: true });
519
+ writeFileSync(archivePath, archiveBuf);
520
+
521
+ if (spec.format === 'tar.gz') {
522
+ const tarRes = await runCmd('tar', ['-xzf', archivePath, '-C', extractDir], {
523
+ timeoutMs: 30_000,
524
+ });
525
+ if (tarRes.code !== 0) {
526
+ throw new Error(
527
+ `Failed to extract ${spec.asset}: ${tarRes.stderr || tarRes.stdout}`,
528
+ );
529
+ }
530
+ } else {
531
+ let extracted = false;
532
+ try {
533
+ const tarRes = await runCmd('tar', ['-xf', archivePath, '-C', extractDir], {
534
+ timeoutMs: 30_000,
535
+ });
536
+ extracted = tarRes.code === 0;
537
+ } catch {
538
+ extracted = false;
539
+ }
540
+ if (!extracted) {
541
+ const psRes = await runCmd(
542
+ 'powershell',
543
+ [
544
+ '-NoProfile',
545
+ '-Command',
546
+ `Expand-Archive -LiteralPath '${archivePath.replace(/'/g, "''")}' -DestinationPath '${extractDir.replace(/'/g, "''")}' -Force`,
547
+ ],
548
+ { timeoutMs: 30_000 },
549
+ );
550
+ if (psRes.code !== 0) {
551
+ throw new Error(
552
+ `Failed to extract ${spec.asset}: ${psRes.stderr || psRes.stdout}`,
553
+ );
554
+ }
555
+ }
556
+ }
557
+
558
+ const extractedBin = join(extractDir, spec.exeName);
559
+ if (!existsSync(extractedBin)) {
560
+ throw new Error(
561
+ `Archive ${spec.asset} did not contain expected binary ${spec.exeName}`,
562
+ );
563
+ }
564
+
565
+ const targetPath = getManagedBinaryPath({ dataDir, platform });
566
+ const stagedPath = `${targetPath}.new-${process.pid}`;
567
+ mkdirSync(dirname(targetPath), { recursive: true });
568
+ renameSync(extractedBin, stagedPath);
569
+
570
+ if (platform !== 'win32') {
571
+ chmodSync(stagedPath, 0o755);
572
+ }
573
+ if (platform === 'darwin') {
574
+ try {
575
+ await runCmd('xattr', ['-d', 'com.apple.quarantine', stagedPath], {
576
+ timeoutMs: 5000,
577
+ });
578
+ } catch {
579
+ // Ignore if quarantine attribute is not set
580
+ }
581
+ }
582
+
583
+ if (platform === 'win32' && existsSync(targetPath)) {
584
+ try {
585
+ rmSync(targetPath, { force: true });
586
+ } catch {
587
+ // ignore; renameSync will surface if locked
588
+ }
589
+ }
590
+ renameSync(stagedPath, targetPath);
591
+
592
+ return {
593
+ binaryPath: targetPath,
594
+ downloaded: true,
595
+ };
596
+ } finally {
597
+ try {
598
+ rmSync(tmpDir, { recursive: true, force: true });
599
+ } catch {
600
+ // ignore cleanup errors
601
+ }
602
+ }
603
+ }
604
+
605
+ function parseMcpInitializeResponse(rawText) {
606
+ const trimmed = String(rawText || '').trim();
607
+ if (!trimmed) return null;
608
+
609
+ // Direct JSON response
610
+ if (trimmed.startsWith('{')) {
611
+ try {
612
+ return JSON.parse(trimmed);
613
+ } catch {
614
+ return null;
615
+ }
616
+ }
617
+
618
+ // Streamable HTTP SSE format (`data: {...}`)
619
+ const lines = trimmed.split(/\r?\n/);
620
+ for (const line of lines) {
621
+ if (!line.startsWith('data:')) continue;
622
+ const payload = line.slice(5).trim();
623
+ if (!payload) continue;
624
+ try {
625
+ const parsed = JSON.parse(payload);
626
+ if (parsed && typeof parsed === 'object') return parsed;
627
+ } catch {
628
+ // continue looking for valid JSON data event
629
+ }
630
+ }
631
+ return null;
632
+ }
633
+
634
+ /**
635
+ * Probe whether the Browser4Agent browser extension is installed, active, and
636
+ * connected via the local Native Messaging Host MCP HTTP service.
637
+ */
638
+ export async function probeExtensionConnection({
639
+ mcpUrl = B4A_MCP_URL,
640
+ binaryPath = null,
641
+ probeTabs = true,
642
+ timeoutMs = 2500,
643
+ fetchImpl = globalThis.fetch,
644
+ runCmd = runCommand,
645
+ } = {}) {
646
+ if (typeof fetchImpl !== 'function') {
647
+ return {
648
+ ready: false,
649
+ reachable: false,
650
+ tabCount: null,
651
+ reason: 'not_connected',
652
+ error: 'fetch unavailable',
653
+ };
654
+ }
655
+
656
+ let initPayload = null;
657
+ try {
658
+ const res = await fetchImpl(mcpUrl, {
659
+ method: 'POST',
660
+ headers: {
661
+ 'content-type': 'application/json',
662
+ accept: 'application/json, text/event-stream',
663
+ },
664
+ body: JSON.stringify({
665
+ jsonrpc: '2.0',
666
+ id: 1,
667
+ method: 'initialize',
668
+ params: {
669
+ protocolVersion: '2025-03-26',
670
+ capabilities: {},
671
+ clientInfo: { name: 'dsh-plugin-browser4agent', version: '0.1.0' },
672
+ },
673
+ }),
674
+ signal: AbortSignal.timeout(timeoutMs),
675
+ });
676
+
677
+ if (!res.ok) {
678
+ return {
679
+ ready: false,
680
+ reachable: false,
681
+ tabCount: null,
682
+ reason: 'invalid_response',
683
+ error: `HTTP ${res.status}`,
684
+ };
685
+ }
686
+
687
+ const text = await res.text();
688
+ initPayload = parseMcpInitializeResponse(text);
689
+ if (!initPayload?.result) {
690
+ return {
691
+ ready: false,
692
+ reachable: true,
693
+ tabCount: null,
694
+ reason: 'invalid_response',
695
+ error: 'Unexpected response from local MCP endpoint',
696
+ };
697
+ }
698
+ } catch {
699
+ return {
700
+ ready: false,
701
+ reachable: false,
702
+ tabCount: null,
703
+ reason: 'not_connected',
704
+ error: null,
705
+ };
706
+ }
707
+
708
+ if (!probeTabs || !binaryPath) {
709
+ return {
710
+ ready: true,
711
+ reachable: true,
712
+ tabCount: null,
713
+ reason: 'connected',
714
+ error: null,
715
+ };
716
+ }
717
+
718
+ try {
719
+ const res = await runCmd(binaryPath, ['--tool', 'list_tabs'], {
720
+ timeoutMs: 4500,
721
+ });
722
+ if (res.code !== 0) {
723
+ const msg = (res.stderr || res.stdout || '').trim();
724
+ return {
725
+ ready: false,
726
+ reachable: true,
727
+ tabCount: null,
728
+ reason: 'tool_error',
729
+ error: msg || `list_tabs exited with code ${res.code}`,
730
+ };
731
+ }
732
+ const parsed = JSON.parse(res.stdout);
733
+ const tabCount = Array.isArray(parsed?.tabs) ? parsed.tabs.length : null;
734
+ return {
735
+ ready: true,
736
+ reachable: true,
737
+ tabCount,
738
+ reason: 'connected',
739
+ error: null,
740
+ };
741
+ } catch (err) {
742
+ return {
743
+ ready: false,
744
+ reachable: true,
745
+ tabCount: null,
746
+ reason: 'tool_error',
747
+ error: err instanceof Error ? err.message : String(err),
748
+ };
749
+ }
750
+ }
751
+
752
+ export async function getBrowser4AgentStatus({
753
+ dataDir = getBrowser4AgentDataDir(),
754
+ platform = process.platform,
755
+ env = process.env,
756
+ home = homedir(),
757
+ agentsHome = null,
758
+ mcpUrl = B4A_MCP_URL,
759
+ probeTabs = true,
760
+ fetchImpl = globalThis.fetch,
761
+ runCmd = runCommand,
762
+ } = {}) {
763
+ const binaryPath = findBrowser4AgentBinary({ dataDir, platform, env, home });
764
+ const managedPath = getManagedBinaryPath({ dataDir, platform });
765
+ const managed = Boolean(
766
+ binaryPath && resolve(binaryPath) === resolve(managedPath),
767
+ );
768
+
769
+ const [version, extension] = await Promise.all([
770
+ readBinaryVersion(binaryPath, { runCmd }),
771
+ probeExtensionConnection({
772
+ mcpUrl,
773
+ binaryPath,
774
+ probeTabs,
775
+ fetchImpl,
776
+ runCmd,
777
+ }),
778
+ ]);
779
+
780
+ const nativeHost = readNativeHostState({ platform, env, home });
781
+ const skill = readSkillState({ home, agentsHome });
782
+
783
+ const binaryInstalled = Boolean(binaryPath);
784
+ const setupComplete = binaryInstalled && nativeHost.configured && skill.installed;
785
+ const ready = setupComplete && extension.ready;
786
+
787
+ return {
788
+ ready,
789
+ setupComplete,
790
+ binary: {
791
+ installed: binaryInstalled,
792
+ path: binaryPath,
793
+ version,
794
+ managed,
795
+ },
796
+ nativeHost,
797
+ skill,
798
+ extension,
799
+ checkedAt: new Date().toISOString(),
800
+ };
801
+ }
802
+
803
+ /**
804
+ * Automatically install `browser4agent` (if missing or `forceDownload`) and run
805
+ * `browser4agent --setup skills` non-interactively to register Native Messaging
806
+ * Host manifests and the `~/.agents/skills/browser4agent/SKILL.md` skill for DSH.
807
+ */
808
+ export async function runBrowser4AgentSetup({
809
+ dataDir = getBrowser4AgentDataDir(),
810
+ platform = process.platform,
811
+ cpu = arch(),
812
+ env = process.env,
813
+ home = homedir(),
814
+ agentsHome = null,
815
+ mcpUrl = B4A_MCP_URL,
816
+ releaseBaseUrl = RELEASE_BASE_URL,
817
+ forceDownload = false,
818
+ onStep = null,
819
+ fetchImpl = globalThis.fetch,
820
+ runCmd = runCommand,
821
+ } = {}) {
822
+ let binaryPath = forceDownload
823
+ ? null
824
+ : findBrowser4AgentBinary({ dataDir, platform, env, home });
825
+ let downloaded = false;
826
+
827
+ if (!binaryPath) {
828
+ onStep?.('downloading');
829
+ const installed = await installBrowser4AgentBinary({
830
+ dataDir,
831
+ platform,
832
+ cpu,
833
+ releaseBaseUrl,
834
+ fetchImpl,
835
+ runCmd,
836
+ });
837
+ binaryPath = installed.binaryPath;
838
+ downloaded = true;
839
+ }
840
+
841
+ onStep?.('configuring');
842
+ let setupRes = await runCmd(binaryPath, ['--setup', 'skills'], {
843
+ env,
844
+ timeoutMs: 30_000,
845
+ });
846
+
847
+ // If an older pre-existing binary on PATH doesn't support `--setup`, fall back
848
+ // to downloading the latest managed release binary and running setup with it.
849
+ if (
850
+ setupRes.code !== 0 &&
851
+ !downloaded &&
852
+ /unexpected argument ['"]--setup['"]|unrecognized|unknown option/i.test(
853
+ `${setupRes.stderr}\n${setupRes.stdout}`,
854
+ )
855
+ ) {
856
+ onStep?.('downloading');
857
+ const installed = await installBrowser4AgentBinary({
858
+ dataDir,
859
+ platform,
860
+ cpu,
861
+ releaseBaseUrl,
862
+ fetchImpl,
863
+ runCmd,
864
+ });
865
+ binaryPath = installed.binaryPath;
866
+ downloaded = true;
867
+
868
+ onStep?.('configuring');
869
+ setupRes = await runCmd(binaryPath, ['--setup', 'skills'], {
870
+ env,
871
+ timeoutMs: 30_000,
872
+ });
873
+ }
874
+
875
+ if (setupRes.code !== 0) {
876
+ const details = (setupRes.stderr || setupRes.stdout || '').trim();
877
+ throw new Error(
878
+ `browser4agent --setup skills failed (exit ${setupRes.code})${details ? `: ${details}` : ''}`,
879
+ );
880
+ }
881
+
882
+ onStep?.('verifying');
883
+ const status = await getBrowser4AgentStatus({
884
+ dataDir,
885
+ platform,
886
+ env,
887
+ home,
888
+ agentsHome,
889
+ mcpUrl,
890
+ probeTabs: true,
891
+ fetchImpl,
892
+ runCmd,
893
+ });
894
+
895
+ return {
896
+ ok: true,
897
+ downloaded,
898
+ binaryPath,
899
+ setupOutput: (setupRes.stdout || '').trim(),
900
+ status,
901
+ };
902
+ }