@jackwener/opencli 0.7.8 → 0.7.9

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,644 @@
1
+ /**
2
+ * Browser interaction via Playwright MCP Bridge extension.
3
+ * Connects to an existing Chrome browser through the extension.
4
+ */
5
+ import { spawn, execSync } from 'node:child_process';
6
+ import { createHash } from 'node:crypto';
7
+ import { fileURLToPath } from 'node:url';
8
+ import * as fs from 'node:fs';
9
+ import * as os from 'node:os';
10
+ import * as path from 'node:path';
11
+ import { formatSnapshot } from './snapshotFormatter.js';
12
+ import { PKG_VERSION } from './version.js';
13
+ import { normalizeEvaluateSource } from './pipeline/template.js';
14
+ import { generateInterceptorJs, generateReadInterceptedJs } from './interceptor.js';
15
+ import { withTimeoutMs, DEFAULT_BROWSER_CONNECT_TIMEOUT } from './runtime.js';
16
+ const STDERR_BUFFER_LIMIT = 16 * 1024;
17
+ const INITIAL_TABS_TIMEOUT_MS = 1500;
18
+ const TAB_CLEANUP_TIMEOUT_MS = 2000;
19
+ let _cachedMcpServerPath;
20
+ export function getTokenFingerprint(token) {
21
+ if (!token)
22
+ return null;
23
+ return createHash('sha256').update(token).digest('hex').slice(0, 8);
24
+ }
25
+ export function formatBrowserConnectError(input) {
26
+ const stderr = input.stderr?.trim();
27
+ const suffix = stderr ? `\n\nMCP stderr:\n${stderr}` : '';
28
+ const tokenHint = input.tokenFingerprint ? ` Token fingerprint: ${input.tokenFingerprint}.` : '';
29
+ if (input.kind === 'missing-token') {
30
+ return new Error('Failed to connect to Playwright MCP Bridge: PLAYWRIGHT_MCP_EXTENSION_TOKEN is not set.\n\n' +
31
+ 'Without this token, Chrome will show a manual approval dialog for every new MCP connection. ' +
32
+ 'Copy the token from the Playwright MCP Bridge extension and set it in BOTH your shell environment and MCP client config.' +
33
+ suffix);
34
+ }
35
+ if (input.kind === 'extension-not-installed') {
36
+ return new Error('Failed to connect to Playwright MCP Bridge: the browser extension did not attach.\n\n' +
37
+ 'Make sure Chrome is running and the "Playwright MCP Bridge" extension is installed and enabled. ' +
38
+ 'If Chrome shows an approval dialog, click Allow.' +
39
+ suffix);
40
+ }
41
+ if (input.kind === 'extension-timeout') {
42
+ const likelyCause = input.hasExtensionToken
43
+ ? `The most likely cause is that PLAYWRIGHT_MCP_EXTENSION_TOKEN does not match the token currently shown by the browser extension.${tokenHint} Re-copy the token from the extension and update BOTH your shell environment and MCP client config.`
44
+ : 'PLAYWRIGHT_MCP_EXTENSION_TOKEN is not configured, so the extension may be waiting for manual approval.';
45
+ return new Error(`Timed out connecting to Playwright MCP Bridge (${input.timeout}s).\n\n` +
46
+ `${likelyCause} If a browser prompt is visible, click Allow.` +
47
+ suffix);
48
+ }
49
+ if (input.kind === 'mcp-init') {
50
+ return new Error(`Failed to initialize Playwright MCP: ${input.rawMessage ?? 'unknown error'}${suffix}`);
51
+ }
52
+ if (input.kind === 'process-exit') {
53
+ return new Error(`Playwright MCP process exited before the browser connection was established${input.exitCode == null ? '' : ` (code ${input.exitCode})`}.` +
54
+ suffix);
55
+ }
56
+ return new Error(input.rawMessage ?? 'Failed to connect to browser');
57
+ }
58
+ function inferConnectFailureKind(args) {
59
+ const haystack = `${args.rawMessage ?? ''}\n${args.stderr}`.toLowerCase();
60
+ if (!args.hasExtensionToken)
61
+ return 'missing-token';
62
+ if (haystack.includes('extension connection timeout') || haystack.includes('playwright mcp bridge'))
63
+ return 'extension-not-installed';
64
+ if (args.rawMessage?.startsWith('MCP init failed:'))
65
+ return 'mcp-init';
66
+ if (args.exited)
67
+ return 'process-exit';
68
+ return 'extension-timeout';
69
+ }
70
+ // JSON-RPC helpers
71
+ let _nextId = 1;
72
+ function createJsonRpcRequest(method, params = {}) {
73
+ const id = _nextId++;
74
+ return {
75
+ id,
76
+ message: JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n',
77
+ };
78
+ }
79
+ /**
80
+ * Page abstraction wrapping JSON-RPC calls to Playwright MCP.
81
+ */
82
+ export class Page {
83
+ _request;
84
+ constructor(_request) {
85
+ this._request = _request;
86
+ }
87
+ async call(method, params = {}) {
88
+ const resp = await this._request(method, params);
89
+ if (resp.error)
90
+ throw new Error(`page.${method}: ${resp.error.message ?? JSON.stringify(resp.error)}`);
91
+ // Extract text content from MCP result
92
+ const result = resp.result;
93
+ if (result?.content) {
94
+ const textParts = result.content.filter((c) => c.type === 'text');
95
+ if (textParts.length === 1) {
96
+ let text = textParts[0].text;
97
+ // MCP browser_evaluate returns: "[JSON]\n### Ran Playwright code\n```js\n...\n```"
98
+ // Strip the "### Ran Playwright code" suffix to get clean JSON
99
+ const codeMarker = text.indexOf('### Ran Playwright code');
100
+ if (codeMarker !== -1) {
101
+ text = text.slice(0, codeMarker).trim();
102
+ }
103
+ // Also handle "### Result\n[JSON]" format (some MCP versions)
104
+ const resultMarker = text.indexOf('### Result\n');
105
+ if (resultMarker !== -1) {
106
+ text = text.slice(resultMarker + '### Result\n'.length).trim();
107
+ }
108
+ try {
109
+ return JSON.parse(text);
110
+ }
111
+ catch {
112
+ return text;
113
+ }
114
+ }
115
+ }
116
+ return result;
117
+ }
118
+ // --- High-level methods ---
119
+ async goto(url) {
120
+ await this.call('tools/call', { name: 'browser_navigate', arguments: { url } });
121
+ }
122
+ async evaluate(js) {
123
+ // Normalize IIFE format to function format expected by MCP browser_evaluate
124
+ const normalized = normalizeEvaluateSource(js);
125
+ return this.call('tools/call', { name: 'browser_evaluate', arguments: { function: normalized } });
126
+ }
127
+ async snapshot(opts = {}) {
128
+ const raw = await this.call('tools/call', { name: 'browser_snapshot', arguments: {} });
129
+ if (opts.raw)
130
+ return raw;
131
+ if (typeof raw === 'string')
132
+ return formatSnapshot(raw, opts);
133
+ return raw;
134
+ }
135
+ async click(ref) {
136
+ await this.call('tools/call', { name: 'browser_click', arguments: { element: 'click target', ref } });
137
+ }
138
+ async typeText(ref, text) {
139
+ await this.call('tools/call', { name: 'browser_type', arguments: { element: 'type target', ref, text } });
140
+ }
141
+ async pressKey(key) {
142
+ await this.call('tools/call', { name: 'browser_press_key', arguments: { key } });
143
+ }
144
+ async wait(options) {
145
+ if (typeof options === 'number') {
146
+ await this.call('tools/call', { name: 'browser_wait_for', arguments: { time: options } });
147
+ }
148
+ else {
149
+ // Pass directly to native wait_for, which supports natively awaiting text strings without heavy DOM polling
150
+ await this.call('tools/call', { name: 'browser_wait_for', arguments: options });
151
+ }
152
+ }
153
+ async tabs() {
154
+ return this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'list' } });
155
+ }
156
+ async closeTab(index) {
157
+ await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'close', ...(index !== undefined ? { index } : {}) } });
158
+ }
159
+ async newTab() {
160
+ await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'new' } });
161
+ }
162
+ async selectTab(index) {
163
+ await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'select', index } });
164
+ }
165
+ async networkRequests(includeStatic = false) {
166
+ return this.call('tools/call', { name: 'browser_network_requests', arguments: { includeStatic } });
167
+ }
168
+ async consoleMessages(level = 'info') {
169
+ return this.call('tools/call', { name: 'browser_console_messages', arguments: { level } });
170
+ }
171
+ async scroll(direction = 'down', _amount = 500) {
172
+ await this.call('tools/call', { name: 'browser_press_key', arguments: { key: direction === 'down' ? 'PageDown' : 'PageUp' } });
173
+ }
174
+ async autoScroll(options = {}) {
175
+ const times = options.times ?? 3;
176
+ const delayMs = options.delayMs ?? 2000;
177
+ const js = `
178
+ async () => {
179
+ const maxTimes = ${times};
180
+ const maxWaitMs = ${delayMs};
181
+ for (let i = 0; i < maxTimes; i++) {
182
+ const lastHeight = document.body.scrollHeight;
183
+ window.scrollTo(0, lastHeight);
184
+ await new Promise(resolve => {
185
+ let timeoutId;
186
+ const observer = new MutationObserver(() => {
187
+ if (document.body.scrollHeight > lastHeight) {
188
+ clearTimeout(timeoutId);
189
+ observer.disconnect();
190
+ setTimeout(resolve, 100); // Small debounce for rendering
191
+ }
192
+ });
193
+ observer.observe(document.body, { childList: true, subtree: true });
194
+ timeoutId = setTimeout(() => {
195
+ observer.disconnect();
196
+ resolve(null);
197
+ }, maxWaitMs);
198
+ });
199
+ }
200
+ }
201
+ `;
202
+ await this.evaluate(js);
203
+ }
204
+ async installInterceptor(pattern) {
205
+ await this.evaluate(generateInterceptorJs(JSON.stringify(pattern), {
206
+ arrayName: '__opencli_xhr',
207
+ patchGuard: '__opencli_interceptor_patched',
208
+ }));
209
+ }
210
+ async getInterceptedRequests() {
211
+ const result = await this.evaluate(generateReadInterceptedJs('__opencli_xhr'));
212
+ return result || [];
213
+ }
214
+ }
215
+ /**
216
+ * Playwright MCP process manager.
217
+ */
218
+ export class PlaywrightMCP {
219
+ static _activeInsts = new Set();
220
+ static _cleanupRegistered = false;
221
+ static _registerGlobalCleanup() {
222
+ if (this._cleanupRegistered)
223
+ return;
224
+ this._cleanupRegistered = true;
225
+ const cleanup = () => {
226
+ for (const inst of this._activeInsts) {
227
+ if (inst._proc && !inst._proc.killed) {
228
+ try {
229
+ inst._proc.kill('SIGKILL');
230
+ }
231
+ catch { }
232
+ }
233
+ }
234
+ };
235
+ process.on('exit', cleanup);
236
+ process.on('SIGINT', () => { cleanup(); process.exit(130); });
237
+ process.on('SIGTERM', () => { cleanup(); process.exit(143); });
238
+ }
239
+ _proc = null;
240
+ _buffer = '';
241
+ _pending = new Map();
242
+ _initialTabIdentities = [];
243
+ _closingPromise = null;
244
+ _state = 'idle';
245
+ _page = null;
246
+ get state() {
247
+ return this._state;
248
+ }
249
+ _sendRequest(method, params = {}) {
250
+ return new Promise((resolve, reject) => {
251
+ if (!this._proc?.stdin?.writable) {
252
+ reject(new Error('Playwright MCP process is not writable'));
253
+ return;
254
+ }
255
+ const { id, message } = createJsonRpcRequest(method, params);
256
+ this._pending.set(id, { resolve, reject });
257
+ this._proc.stdin.write(message, (err) => {
258
+ if (!err)
259
+ return;
260
+ this._pending.delete(id);
261
+ reject(err);
262
+ });
263
+ });
264
+ }
265
+ _rejectPendingRequests(error) {
266
+ const pending = [...this._pending.values()];
267
+ this._pending.clear();
268
+ for (const waiter of pending)
269
+ waiter.reject(error);
270
+ }
271
+ _resetAfterFailedConnect() {
272
+ const proc = this._proc;
273
+ this._page = null;
274
+ this._proc = null;
275
+ this._buffer = '';
276
+ this._initialTabIdentities = [];
277
+ this._rejectPendingRequests(new Error('Playwright MCP connect failed'));
278
+ PlaywrightMCP._activeInsts.delete(this);
279
+ if (proc && !proc.killed) {
280
+ try {
281
+ proc.kill('SIGKILL');
282
+ }
283
+ catch { }
284
+ }
285
+ }
286
+ async connect(opts = {}) {
287
+ if (this._state === 'connected' && this._page)
288
+ return this._page;
289
+ if (this._state === 'connecting')
290
+ throw new Error('Playwright MCP is already connecting');
291
+ if (this._state === 'closing')
292
+ throw new Error('Playwright MCP is closing');
293
+ if (this._state === 'closed')
294
+ throw new Error('Playwright MCP session is closed');
295
+ const mcpPath = findMcpServerPath();
296
+ if (!mcpPath)
297
+ throw new Error('Playwright MCP server not found. Install: npm install -D @playwright/mcp');
298
+ PlaywrightMCP._registerGlobalCleanup();
299
+ PlaywrightMCP._activeInsts.add(this);
300
+ this._state = 'connecting';
301
+ const timeout = opts.timeout ?? DEFAULT_BROWSER_CONNECT_TIMEOUT;
302
+ return new Promise((resolve, reject) => {
303
+ const isDebug = process.env.DEBUG?.includes('opencli:mcp');
304
+ const debugLog = (msg) => isDebug && console.error(`[opencli:mcp] ${msg}`);
305
+ const useExtension = !!process.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN;
306
+ const extensionToken = process.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN;
307
+ const tokenFingerprint = getTokenFingerprint(extensionToken);
308
+ let stderrBuffer = '';
309
+ let settled = false;
310
+ const settleError = (kind, extra = {}) => {
311
+ if (settled)
312
+ return;
313
+ settled = true;
314
+ this._state = 'idle';
315
+ clearTimeout(timer);
316
+ this._resetAfterFailedConnect();
317
+ reject(formatBrowserConnectError({
318
+ kind,
319
+ timeout,
320
+ hasExtensionToken: !!extensionToken,
321
+ tokenFingerprint,
322
+ stderr: stderrBuffer,
323
+ exitCode: extra.exitCode,
324
+ rawMessage: extra.rawMessage,
325
+ }));
326
+ };
327
+ const settleSuccess = (pageToResolve) => {
328
+ if (settled)
329
+ return;
330
+ settled = true;
331
+ this._state = 'connected';
332
+ clearTimeout(timer);
333
+ resolve(pageToResolve);
334
+ };
335
+ const timer = setTimeout(() => {
336
+ debugLog('Connection timed out');
337
+ settleError(inferConnectFailureKind({
338
+ hasExtensionToken: !!extensionToken,
339
+ stderr: stderrBuffer,
340
+ }));
341
+ }, timeout * 1000);
342
+ const mcpArgs = buildMcpArgs({
343
+ mcpPath,
344
+ executablePath: process.env.OPENCLI_BROWSER_EXECUTABLE_PATH,
345
+ });
346
+ if (process.env.OPENCLI_VERBOSE) {
347
+ console.error(`[opencli] Mode: ${useExtension ? 'extension' : 'standalone'}`);
348
+ if (useExtension)
349
+ console.error(`[opencli] Extension token: fingerprint ${tokenFingerprint}`);
350
+ }
351
+ debugLog(`Spawning node ${mcpArgs.join(' ')}`);
352
+ this._proc = spawn('node', mcpArgs, {
353
+ stdio: ['pipe', 'pipe', 'pipe'],
354
+ env: { ...process.env },
355
+ });
356
+ // Increase max listeners to avoid warnings
357
+ this._proc.setMaxListeners(20);
358
+ if (this._proc.stdout)
359
+ this._proc.stdout.setMaxListeners(20);
360
+ const page = new Page((method, params = {}) => this._sendRequest(method, params));
361
+ this._page = page;
362
+ this._proc.stdout?.on('data', (chunk) => {
363
+ this._buffer += chunk.toString();
364
+ const lines = this._buffer.split('\n');
365
+ this._buffer = lines.pop() ?? '';
366
+ for (const line of lines) {
367
+ if (!line.trim())
368
+ continue;
369
+ debugLog(`RECV: ${line}`);
370
+ try {
371
+ const parsed = JSON.parse(line);
372
+ if (typeof parsed?.id === 'number') {
373
+ const waiter = this._pending.get(parsed.id);
374
+ if (waiter) {
375
+ this._pending.delete(parsed.id);
376
+ waiter.resolve(parsed);
377
+ }
378
+ }
379
+ }
380
+ catch (e) {
381
+ debugLog(`Parse error: ${e}`);
382
+ }
383
+ }
384
+ });
385
+ this._proc.stderr?.on('data', (chunk) => {
386
+ const text = chunk.toString();
387
+ stderrBuffer = appendLimited(stderrBuffer, text, STDERR_BUFFER_LIMIT);
388
+ debugLog(`STDERR: ${text}`);
389
+ });
390
+ this._proc.on('error', (err) => {
391
+ debugLog(`Subprocess error: ${err.message}`);
392
+ this._rejectPendingRequests(new Error(`Playwright MCP process error: ${err.message}`));
393
+ settleError('process-exit', { rawMessage: err.message });
394
+ });
395
+ this._proc.on('close', (code) => {
396
+ debugLog(`Subprocess closed with code ${code}`);
397
+ this._rejectPendingRequests(new Error(`Playwright MCP process exited before response${code == null ? '' : ` (code ${code})`}`));
398
+ if (!settled) {
399
+ settleError(inferConnectFailureKind({
400
+ hasExtensionToken: !!extensionToken,
401
+ stderr: stderrBuffer,
402
+ exited: true,
403
+ }), { exitCode: code });
404
+ }
405
+ });
406
+ // Initialize: send initialize request
407
+ debugLog('Waiting for initialize response...');
408
+ this._sendRequest('initialize', {
409
+ protocolVersion: '2024-11-05',
410
+ capabilities: {},
411
+ clientInfo: { name: 'opencli', version: PKG_VERSION },
412
+ }).then((resp) => {
413
+ debugLog('Got initialize response');
414
+ if (resp.error) {
415
+ settleError(inferConnectFailureKind({
416
+ hasExtensionToken: !!extensionToken,
417
+ stderr: stderrBuffer,
418
+ rawMessage: `MCP init failed: ${resp.error.message}`,
419
+ }), { rawMessage: resp.error.message });
420
+ return;
421
+ }
422
+ const initializedMsg = JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n';
423
+ debugLog(`SEND: ${initializedMsg.trim()}`);
424
+ this._proc?.stdin?.write(initializedMsg);
425
+ // Use tabs as a readiness probe and for tab cleanup bookkeeping.
426
+ debugLog('Fetching initial tabs count...');
427
+ withTimeoutMs(page.tabs(), INITIAL_TABS_TIMEOUT_MS, 'Timed out fetching initial tabs').then((tabs) => {
428
+ debugLog(`Tabs response: ${typeof tabs === 'string' ? tabs : JSON.stringify(tabs)}`);
429
+ this._initialTabIdentities = extractTabIdentities(tabs);
430
+ settleSuccess(page);
431
+ }).catch((err) => {
432
+ debugLog(`Tabs fetch error: ${err.message}`);
433
+ settleSuccess(page);
434
+ });
435
+ }).catch((err) => {
436
+ debugLog(`Init promise rejected: ${err.message}`);
437
+ settleError('mcp-init', { rawMessage: err.message });
438
+ });
439
+ });
440
+ }
441
+ async close() {
442
+ if (this._closingPromise)
443
+ return this._closingPromise;
444
+ if (this._state === 'closed')
445
+ return;
446
+ this._state = 'closing';
447
+ this._closingPromise = (async () => {
448
+ try {
449
+ // Extension mode opens bridge/session tabs that we can clean up best-effort.
450
+ if (this._page && this._proc && !this._proc.killed) {
451
+ try {
452
+ const tabs = await withTimeoutMs(this._page.tabs(), TAB_CLEANUP_TIMEOUT_MS, 'Timed out fetching tabs during cleanup');
453
+ const tabEntries = extractTabEntries(tabs);
454
+ const tabsToClose = diffTabIndexes(this._initialTabIdentities, tabEntries);
455
+ for (const index of tabsToClose) {
456
+ try {
457
+ await this._page.closeTab(index);
458
+ }
459
+ catch { }
460
+ }
461
+ }
462
+ catch { }
463
+ }
464
+ if (this._proc && !this._proc.killed) {
465
+ this._proc.kill('SIGTERM');
466
+ const exited = await new Promise((res) => {
467
+ let done = false;
468
+ const finish = (value) => {
469
+ if (done)
470
+ return;
471
+ done = true;
472
+ res(value);
473
+ };
474
+ this._proc?.once('exit', () => finish(true));
475
+ setTimeout(() => finish(false), 3000);
476
+ });
477
+ if (!exited && this._proc && !this._proc.killed) {
478
+ try {
479
+ this._proc.kill('SIGKILL');
480
+ }
481
+ catch { }
482
+ }
483
+ }
484
+ }
485
+ finally {
486
+ this._rejectPendingRequests(new Error('Playwright MCP session closed'));
487
+ this._page = null;
488
+ this._proc = null;
489
+ this._state = 'closed';
490
+ PlaywrightMCP._activeInsts.delete(this);
491
+ }
492
+ })();
493
+ return this._closingPromise;
494
+ }
495
+ }
496
+ function extractTabEntries(raw) {
497
+ if (Array.isArray(raw)) {
498
+ return raw.map((tab, index) => ({
499
+ index,
500
+ identity: [
501
+ tab?.id ?? '',
502
+ tab?.url ?? '',
503
+ tab?.title ?? '',
504
+ tab?.name ?? '',
505
+ ].join('|'),
506
+ }));
507
+ }
508
+ if (typeof raw === 'string') {
509
+ return raw
510
+ .split('\n')
511
+ .map(line => line.trim())
512
+ .filter(Boolean)
513
+ .map(line => {
514
+ // Match actual Playwright MCP format: "- 0: (current) [title](url)" or "- 1: [title](url)"
515
+ const mcpMatch = line.match(/^-\s+(\d+):\s*(.*)$/);
516
+ if (mcpMatch) {
517
+ return {
518
+ index: parseInt(mcpMatch[1], 10),
519
+ identity: mcpMatch[2].trim() || `tab-${mcpMatch[1]}`,
520
+ };
521
+ }
522
+ // Legacy format: "Tab 0 ..."
523
+ const legacyMatch = line.match(/Tab\s+(\d+)\s*(.*)$/);
524
+ if (legacyMatch) {
525
+ return {
526
+ index: parseInt(legacyMatch[1], 10),
527
+ identity: legacyMatch[2].trim() || `tab-${legacyMatch[1]}`,
528
+ };
529
+ }
530
+ return null;
531
+ })
532
+ .filter((entry) => entry !== null);
533
+ }
534
+ return [];
535
+ }
536
+ function extractTabIdentities(raw) {
537
+ return extractTabEntries(raw).map(tab => tab.identity);
538
+ }
539
+ function diffTabIndexes(initialIdentities, currentTabs) {
540
+ if (initialIdentities.length === 0 || currentTabs.length === 0)
541
+ return [];
542
+ const remaining = new Map();
543
+ for (const identity of initialIdentities) {
544
+ remaining.set(identity, (remaining.get(identity) ?? 0) + 1);
545
+ }
546
+ const tabsToClose = [];
547
+ for (const tab of currentTabs) {
548
+ const count = remaining.get(tab.identity) ?? 0;
549
+ if (count > 0) {
550
+ remaining.set(tab.identity, count - 1);
551
+ continue;
552
+ }
553
+ tabsToClose.push(tab.index);
554
+ }
555
+ return tabsToClose.sort((a, b) => b - a);
556
+ }
557
+ function appendLimited(current, chunk, limit) {
558
+ const next = current + chunk;
559
+ if (next.length <= limit)
560
+ return next;
561
+ return next.slice(-limit);
562
+ }
563
+ function buildMcpArgs(input) {
564
+ const args = [input.mcpPath];
565
+ if (!process.env.CI) {
566
+ // Local: always connect to user's running Chrome via MCP Bridge extension
567
+ args.push('--extension');
568
+ }
569
+ // CI: standalone mode — @playwright/mcp launches its own browser (headed by default).
570
+ // xvfb provides a virtual display for headed mode in GitHub Actions.
571
+ if (input.executablePath) {
572
+ args.push('--executable-path', input.executablePath);
573
+ }
574
+ return args;
575
+ }
576
+ export const __test__ = {
577
+ createJsonRpcRequest,
578
+ extractTabEntries,
579
+ diffTabIndexes,
580
+ appendLimited,
581
+ buildMcpArgs,
582
+ withTimeoutMs,
583
+ };
584
+ function findMcpServerPath() {
585
+ if (_cachedMcpServerPath !== undefined)
586
+ return _cachedMcpServerPath;
587
+ const envMcp = process.env.OPENCLI_MCP_SERVER_PATH;
588
+ if (envMcp && fs.existsSync(envMcp)) {
589
+ _cachedMcpServerPath = envMcp;
590
+ return _cachedMcpServerPath;
591
+ }
592
+ // Check local node_modules first (@playwright/mcp is the modern package)
593
+ const localMcp = path.resolve('node_modules', '@playwright', 'mcp', 'cli.js');
594
+ if (fs.existsSync(localMcp)) {
595
+ _cachedMcpServerPath = localMcp;
596
+ return _cachedMcpServerPath;
597
+ }
598
+ // Check project-relative path
599
+ const __dirname2 = path.dirname(fileURLToPath(import.meta.url));
600
+ const projectMcp = path.resolve(__dirname2, '..', 'node_modules', '@playwright', 'mcp', 'cli.js');
601
+ if (fs.existsSync(projectMcp)) {
602
+ _cachedMcpServerPath = projectMcp;
603
+ return _cachedMcpServerPath;
604
+ }
605
+ // Check common locations
606
+ const candidates = [
607
+ path.join(os.homedir(), '.npm', '_npx'),
608
+ path.join(os.homedir(), 'node_modules', '.bin'),
609
+ '/usr/local/lib/node_modules',
610
+ ];
611
+ // Try npx resolution (legacy package name)
612
+ try {
613
+ const result = execSync('npx -y --package=@playwright/mcp which mcp-server-playwright 2>/dev/null', { encoding: 'utf-8', timeout: 10000 }).trim();
614
+ if (result && fs.existsSync(result)) {
615
+ _cachedMcpServerPath = result;
616
+ return _cachedMcpServerPath;
617
+ }
618
+ }
619
+ catch { }
620
+ // Try which
621
+ try {
622
+ const result = execSync('which mcp-server-playwright 2>/dev/null', { encoding: 'utf-8', timeout: 5000 }).trim();
623
+ if (result && fs.existsSync(result)) {
624
+ _cachedMcpServerPath = result;
625
+ return _cachedMcpServerPath;
626
+ }
627
+ }
628
+ catch { }
629
+ // Search in common npx cache
630
+ for (const base of candidates) {
631
+ if (!fs.existsSync(base))
632
+ continue;
633
+ try {
634
+ const found = execSync(`find "${base}" -name "cli.js" -path "*playwright*mcp*" 2>/dev/null | head -1`, { encoding: 'utf-8', timeout: 5000 }).trim();
635
+ if (found) {
636
+ _cachedMcpServerPath = found;
637
+ return _cachedMcpServerPath;
638
+ }
639
+ }
640
+ catch { }
641
+ }
642
+ _cachedMcpServerPath = null;
643
+ return _cachedMcpServerPath;
644
+ }