@jackwener/opencli 0.9.8 → 1.0.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.
Files changed (97) hide show
  1. package/CDP.md +1 -1
  2. package/CDP.zh-CN.md +1 -1
  3. package/CLI-ELECTRON.md +2 -2
  4. package/CLI-EXPLORER.md +4 -4
  5. package/README.md +15 -57
  6. package/README.zh-CN.md +16 -59
  7. package/SKILL.md +10 -8
  8. package/TESTING.md +7 -7
  9. package/dist/browser/daemon-client.d.ts +37 -0
  10. package/dist/browser/daemon-client.js +82 -0
  11. package/dist/browser/discover.d.ts +11 -34
  12. package/dist/browser/discover.js +15 -205
  13. package/dist/browser/errors.d.ts +6 -20
  14. package/dist/browser/errors.js +24 -63
  15. package/dist/browser/index.d.ts +2 -11
  16. package/dist/browser/index.js +5 -11
  17. package/dist/browser/mcp.d.ts +9 -18
  18. package/dist/browser/mcp.js +70 -284
  19. package/dist/browser/page.d.ts +28 -6
  20. package/dist/browser/page.js +210 -85
  21. package/dist/browser.test.js +4 -225
  22. package/dist/cli-manifest.json +167 -0
  23. package/dist/clis/neteasemusic/like.d.ts +1 -0
  24. package/dist/clis/neteasemusic/like.js +25 -0
  25. package/dist/clis/neteasemusic/lyrics.d.ts +1 -0
  26. package/dist/clis/neteasemusic/lyrics.js +47 -0
  27. package/dist/clis/neteasemusic/next.d.ts +1 -0
  28. package/dist/clis/neteasemusic/next.js +26 -0
  29. package/dist/clis/neteasemusic/play.d.ts +1 -0
  30. package/dist/clis/neteasemusic/play.js +26 -0
  31. package/dist/clis/neteasemusic/playing.d.ts +1 -0
  32. package/dist/clis/neteasemusic/playing.js +59 -0
  33. package/dist/clis/neteasemusic/playlist.d.ts +1 -0
  34. package/dist/clis/neteasemusic/playlist.js +46 -0
  35. package/dist/clis/neteasemusic/prev.d.ts +1 -0
  36. package/dist/clis/neteasemusic/prev.js +25 -0
  37. package/dist/clis/neteasemusic/search.d.ts +1 -0
  38. package/dist/clis/neteasemusic/search.js +52 -0
  39. package/dist/clis/neteasemusic/status.d.ts +1 -0
  40. package/dist/clis/neteasemusic/status.js +16 -0
  41. package/dist/clis/neteasemusic/volume.d.ts +1 -0
  42. package/dist/clis/neteasemusic/volume.js +54 -0
  43. package/dist/daemon.d.ts +13 -0
  44. package/dist/daemon.js +187 -0
  45. package/dist/doctor.d.ts +27 -61
  46. package/dist/doctor.js +70 -601
  47. package/dist/doctor.test.js +30 -170
  48. package/dist/main.js +6 -25
  49. package/dist/pipeline/executor.test.js +1 -0
  50. package/dist/pipeline/steps/browser.js +2 -2
  51. package/dist/pipeline/steps/intercept.js +1 -2
  52. package/dist/setup.d.ts +6 -0
  53. package/dist/setup.js +46 -160
  54. package/dist/types.d.ts +6 -0
  55. package/extension/icons/icon-128.png +0 -0
  56. package/extension/icons/icon-16.png +0 -0
  57. package/extension/icons/icon-32.png +0 -0
  58. package/extension/icons/icon-48.png +0 -0
  59. package/extension/manifest.json +31 -0
  60. package/extension/package.json +16 -0
  61. package/extension/src/background.ts +293 -0
  62. package/extension/src/cdp.ts +125 -0
  63. package/extension/src/protocol.ts +57 -0
  64. package/extension/store-assets/screenshot-1280x800.png +0 -0
  65. package/extension/tsconfig.json +15 -0
  66. package/extension/vite.config.ts +18 -0
  67. package/package.json +5 -5
  68. package/src/browser/daemon-client.ts +113 -0
  69. package/src/browser/discover.ts +18 -232
  70. package/src/browser/errors.ts +30 -100
  71. package/src/browser/index.ts +6 -12
  72. package/src/browser/mcp.ts +78 -278
  73. package/src/browser/page.ts +222 -88
  74. package/src/browser.test.ts +3 -233
  75. package/src/clis/chatgpt/README.md +1 -1
  76. package/src/clis/chatgpt/README.zh-CN.md +1 -1
  77. package/src/clis/neteasemusic/README.md +31 -0
  78. package/src/clis/neteasemusic/README.zh-CN.md +31 -0
  79. package/src/clis/neteasemusic/like.ts +28 -0
  80. package/src/clis/neteasemusic/lyrics.ts +53 -0
  81. package/src/clis/neteasemusic/next.ts +30 -0
  82. package/src/clis/neteasemusic/play.ts +30 -0
  83. package/src/clis/neteasemusic/playing.ts +62 -0
  84. package/src/clis/neteasemusic/playlist.ts +51 -0
  85. package/src/clis/neteasemusic/prev.ts +29 -0
  86. package/src/clis/neteasemusic/search.ts +58 -0
  87. package/src/clis/neteasemusic/status.ts +18 -0
  88. package/src/clis/neteasemusic/volume.ts +61 -0
  89. package/src/daemon.ts +217 -0
  90. package/src/doctor.test.ts +32 -193
  91. package/src/doctor.ts +74 -668
  92. package/src/main.ts +6 -23
  93. package/src/pipeline/executor.test.ts +1 -0
  94. package/src/pipeline/steps/browser.ts +2 -2
  95. package/src/pipeline/steps/intercept.ts +1 -2
  96. package/src/setup.ts +47 -183
  97. package/src/types.ts +1 -0
@@ -1,310 +1,96 @@
1
1
  /**
2
- * Playwright MCP process manager.
3
- * Handles lifecycle management, JSON-RPC communication, and browser session orchestration.
2
+ * Browser session manager — auto-spawns daemon and provides IPage.
3
+ *
4
+ * Replaces the old PlaywrightMCP class. Still exports as PlaywrightMCP
5
+ * for backward compatibility with main.ts and other consumers.
4
6
  */
5
7
  import { spawn } from 'node:child_process';
6
- import { withTimeoutMs, DEFAULT_BROWSER_CONNECT_TIMEOUT } from '../runtime.js';
7
- import { PKG_VERSION } from '../version.js';
8
+ import { fileURLToPath } from 'node:url';
9
+ import * as path from 'node:path';
10
+ import * as fs from 'node:fs';
8
11
  import { Page } from './page.js';
9
- import { getTokenFingerprint, formatBrowserConnectError, inferConnectFailureKind } from './errors.js';
10
- import { findMcpServerPath, buildMcpLaunchSpec, resolveCdpEndpoint } from './discover.js';
11
- import { extractTabIdentities, extractTabEntries, diffTabIndexes, appendLimited } from './tabs.js';
12
- const STDERR_BUFFER_LIMIT = 16 * 1024;
13
- const INITIAL_TABS_TIMEOUT_MS = 1500;
14
- const TAB_CLEANUP_TIMEOUT_MS = 2000;
15
- // JSON-RPC helpers
16
- let _nextId = 1;
17
- export function createJsonRpcRequest(method, params = {}) {
18
- const id = _nextId++;
19
- return {
20
- id,
21
- message: JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n',
22
- };
23
- }
12
+ import { isDaemonRunning, isExtensionConnected } from './daemon-client.js';
13
+ const DAEMON_SPAWN_TIMEOUT = 10000; // 10s to wait for daemon + extension
24
14
  /**
25
- * Playwright MCP process manager.
15
+ * Browser factory: manages daemon lifecycle and provides IPage instances.
16
+ *
17
+ * Kept as `PlaywrightMCP` class name for backward compatibility.
26
18
  */
27
19
  export class PlaywrightMCP {
28
- static _activeInsts = new Set();
29
- static _cleanupRegistered = false;
30
- static _registerGlobalCleanup() {
31
- if (this._cleanupRegistered)
32
- return;
33
- this._cleanupRegistered = true;
34
- const cleanup = () => {
35
- for (const inst of this._activeInsts) {
36
- if (inst._proc && !inst._proc.killed) {
37
- try {
38
- inst._proc.kill('SIGKILL');
39
- }
40
- catch { }
41
- }
42
- }
43
- };
44
- process.on('exit', cleanup);
45
- process.on('SIGINT', () => { cleanup(); process.exit(130); });
46
- process.on('SIGTERM', () => { cleanup(); process.exit(143); });
47
- }
48
- _proc = null;
49
- _buffer = '';
50
- _pending = new Map();
51
- _initialTabIdentities = [];
52
- _closingPromise = null;
53
20
  _state = 'idle';
54
21
  _page = null;
22
+ _daemonProc = null;
55
23
  get state() {
56
24
  return this._state;
57
25
  }
58
- _sendRequest(method, params = {}) {
59
- return new Promise((resolve, reject) => {
60
- if (!this._proc?.stdin?.writable) {
61
- reject(new Error('Playwright MCP process is not writable'));
62
- return;
63
- }
64
- const { id, message } = createJsonRpcRequest(method, params);
65
- this._pending.set(id, { resolve, reject });
66
- this._proc.stdin.write(message, (err) => {
67
- if (!err)
68
- return;
69
- this._pending.delete(id);
70
- reject(err);
71
- });
72
- });
73
- }
74
- _rejectPendingRequests(error) {
75
- const pending = [...this._pending.values()];
76
- this._pending.clear();
77
- for (const waiter of pending)
78
- waiter.reject(error);
79
- }
80
- _resetAfterFailedConnect() {
81
- const proc = this._proc;
82
- this._page = null;
83
- this._proc = null;
84
- this._buffer = '';
85
- this._initialTabIdentities = [];
86
- this._rejectPendingRequests(new Error('Playwright MCP connect failed'));
87
- PlaywrightMCP._activeInsts.delete(this);
88
- if (proc && !proc.killed) {
89
- try {
90
- proc.kill('SIGKILL');
91
- }
92
- catch { }
93
- }
94
- }
95
26
  async connect(opts = {}) {
96
27
  if (this._state === 'connected' && this._page)
97
28
  return this._page;
98
29
  if (this._state === 'connecting')
99
- throw new Error('Playwright MCP is already connecting');
30
+ throw new Error('Already connecting');
100
31
  if (this._state === 'closing')
101
- throw new Error('Playwright MCP is closing');
32
+ throw new Error('Session is closing');
102
33
  if (this._state === 'closed')
103
- throw new Error('Playwright MCP session is closed');
104
- const mcpPath = findMcpServerPath();
105
- PlaywrightMCP._registerGlobalCleanup();
106
- PlaywrightMCP._activeInsts.add(this);
34
+ throw new Error('Session is closed');
107
35
  this._state = 'connecting';
108
- const timeout = opts.timeout ?? DEFAULT_BROWSER_CONNECT_TIMEOUT;
109
- return new Promise((resolve, reject) => {
110
- const isDebug = process.env.DEBUG?.includes('opencli:mcp');
111
- const debugLog = (msg) => isDebug && console.error(`[opencli:mcp] ${msg}`);
112
- const { endpoint: cdpEndpoint, requestedCdp } = resolveCdpEndpoint();
113
- const useExtension = !requestedCdp;
114
- const extensionToken = process.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN;
115
- const tokenFingerprint = getTokenFingerprint(extensionToken);
116
- let stderrBuffer = '';
117
- let settled = false;
118
- const settleError = (kind, extra = {}) => {
119
- if (settled)
120
- return;
121
- settled = true;
122
- this._state = 'idle';
123
- clearTimeout(timer);
124
- this._resetAfterFailedConnect();
125
- reject(formatBrowserConnectError({
126
- kind,
127
- timeout,
128
- hasExtensionToken: !!extensionToken,
129
- tokenFingerprint,
130
- stderr: stderrBuffer,
131
- exitCode: extra.exitCode,
132
- rawMessage: extra.rawMessage,
133
- }));
134
- };
135
- const settleSuccess = (pageToResolve) => {
136
- if (settled)
137
- return;
138
- settled = true;
139
- this._state = 'connected';
140
- clearTimeout(timer);
141
- resolve(pageToResolve);
142
- };
143
- const timer = setTimeout(() => {
144
- debugLog('Connection timed out');
145
- settleError(inferConnectFailureKind({
146
- hasExtensionToken: !!extensionToken,
147
- stderr: stderrBuffer,
148
- isCdpMode: requestedCdp,
149
- }));
150
- }, timeout * 1000);
151
- const launchSpec = buildMcpLaunchSpec({
152
- mcpPath,
153
- executablePath: process.env.OPENCLI_BROWSER_EXECUTABLE_PATH,
154
- cdpEndpoint,
155
- });
156
- if (process.env.OPENCLI_VERBOSE) {
157
- console.error(`[opencli] Mode: ${requestedCdp ? 'CDP' : useExtension ? 'extension' : 'standalone'}`);
158
- if (useExtension)
159
- console.error(`[opencli] Extension token: fingerprint ${tokenFingerprint}`);
160
- if (launchSpec.usedNpxFallback) {
161
- console.error('[opencli] Playwright MCP not found locally; bootstrapping via npx @playwright/mcp@latest');
162
- }
163
- }
164
- debugLog(`Spawning ${launchSpec.command} ${launchSpec.args.join(' ')}`);
165
- this._proc = spawn(launchSpec.command, launchSpec.args, {
166
- stdio: ['pipe', 'pipe', 'pipe'],
167
- env: { ...process.env },
168
- });
169
- // Increase max listeners to avoid warnings
170
- this._proc.setMaxListeners(20);
171
- if (this._proc.stdout)
172
- this._proc.stdout.setMaxListeners(20);
173
- const page = new Page((method, params = {}) => this._sendRequest(method, params));
174
- this._page = page;
175
- this._proc.stdout?.on('data', (chunk) => {
176
- this._buffer += chunk.toString();
177
- const lines = this._buffer.split('\n');
178
- this._buffer = lines.pop() ?? '';
179
- for (const line of lines) {
180
- if (!line.trim())
181
- continue;
182
- debugLog(`RECV: ${line}`);
183
- try {
184
- const parsed = JSON.parse(line);
185
- if (typeof parsed?.id === 'number') {
186
- const waiter = this._pending.get(parsed.id);
187
- if (waiter) {
188
- this._pending.delete(parsed.id);
189
- waiter.resolve(parsed);
190
- }
191
- }
192
- }
193
- catch (e) {
194
- debugLog(`Parse error: ${e}`);
195
- }
196
- }
197
- });
198
- this._proc.stderr?.on('data', (chunk) => {
199
- const text = chunk.toString();
200
- stderrBuffer = appendLimited(stderrBuffer, text, STDERR_BUFFER_LIMIT);
201
- debugLog(`STDERR: ${text}`);
202
- });
203
- this._proc.on('error', (err) => {
204
- debugLog(`Subprocess error: ${err.message}`);
205
- this._rejectPendingRequests(new Error(`Playwright MCP process error: ${err.message}`));
206
- settleError('process-exit', { rawMessage: err.message });
207
- });
208
- this._proc.on('close', (code) => {
209
- debugLog(`Subprocess closed with code ${code}`);
210
- this._rejectPendingRequests(new Error(`Playwright MCP process exited before response${code == null ? '' : ` (code ${code})`}`));
211
- if (!settled) {
212
- settleError(inferConnectFailureKind({
213
- hasExtensionToken: !!extensionToken,
214
- stderr: stderrBuffer,
215
- exited: true,
216
- isCdpMode: requestedCdp,
217
- }), { exitCode: code });
218
- }
219
- });
220
- // Initialize: send initialize request
221
- debugLog('Waiting for initialize response...');
222
- this._sendRequest('initialize', {
223
- protocolVersion: '2024-11-05',
224
- capabilities: {},
225
- clientInfo: { name: 'opencli', version: PKG_VERSION },
226
- }).then((resp) => {
227
- debugLog('Got initialize response');
228
- if (resp.error) {
229
- settleError(inferConnectFailureKind({
230
- hasExtensionToken: !!extensionToken,
231
- stderr: stderrBuffer,
232
- rawMessage: `MCP init failed: ${resp.error.message}`,
233
- isCdpMode: requestedCdp,
234
- }), { rawMessage: resp.error.message });
235
- return;
236
- }
237
- const initializedMsg = JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n';
238
- debugLog(`SEND: ${initializedMsg.trim()}`);
239
- this._proc?.stdin?.write(initializedMsg);
240
- // Use tabs as a readiness probe and for tab cleanup bookkeeping.
241
- debugLog('Fetching initial tabs count...');
242
- withTimeoutMs(page.tabs(), INITIAL_TABS_TIMEOUT_MS, 'Timed out fetching initial tabs').then((tabs) => {
243
- debugLog(`Tabs response: ${typeof tabs === 'string' ? tabs : JSON.stringify(tabs)}`);
244
- this._initialTabIdentities = extractTabIdentities(tabs);
245
- settleSuccess(page);
246
- }).catch((err) => {
247
- debugLog(`Tabs fetch error: ${err.message}`);
248
- settleSuccess(page);
249
- });
250
- }).catch((err) => {
251
- debugLog(`Init promise rejected: ${err.message}`);
252
- settleError('mcp-init', { rawMessage: err.message });
253
- });
254
- });
36
+ try {
37
+ await this._ensureDaemon();
38
+ this._page = new Page();
39
+ this._state = 'connected';
40
+ return this._page;
41
+ }
42
+ catch (err) {
43
+ this._state = 'idle';
44
+ throw err;
45
+ }
255
46
  }
256
47
  async close() {
257
- if (this._closingPromise)
258
- return this._closingPromise;
259
48
  if (this._state === 'closed')
260
49
  return;
261
50
  this._state = 'closing';
262
- this._closingPromise = (async () => {
263
- try {
264
- // Extension mode opens bridge/session tabs that we can clean up best-effort.
265
- if (this._page && this._proc && !this._proc.killed) {
266
- try {
267
- const tabs = await withTimeoutMs(this._page.tabs(), TAB_CLEANUP_TIMEOUT_MS, 'Timed out fetching tabs during cleanup');
268
- const tabEntries = extractTabEntries(tabs);
269
- const tabsToClose = diffTabIndexes(this._initialTabIdentities, tabEntries);
270
- for (const index of tabsToClose) {
271
- try {
272
- await this._page.closeTab(index);
273
- }
274
- catch { }
275
- }
276
- }
277
- catch { }
278
- }
279
- if (this._proc && !this._proc.killed) {
280
- this._proc.kill('SIGTERM');
281
- const exited = await new Promise((res) => {
282
- let done = false;
283
- const finish = (value) => {
284
- if (done)
285
- return;
286
- done = true;
287
- res(value);
288
- };
289
- this._proc?.once('exit', () => finish(true));
290
- setTimeout(() => finish(false), 3000);
291
- });
292
- if (!exited && this._proc && !this._proc.killed) {
293
- try {
294
- this._proc.kill('SIGKILL');
295
- }
296
- catch { }
297
- }
298
- }
299
- }
300
- finally {
301
- this._rejectPendingRequests(new Error('Playwright MCP session closed'));
302
- this._page = null;
303
- this._proc = null;
304
- this._state = 'closed';
305
- PlaywrightMCP._activeInsts.delete(this);
306
- }
307
- })();
308
- return this._closingPromise;
51
+ // We don't kill the daemon — it auto-exits on idle.
52
+ // Just clean up our reference.
53
+ this._page = null;
54
+ this._state = 'closed';
55
+ }
56
+ async _ensureDaemon() {
57
+ if (await isDaemonRunning())
58
+ return;
59
+ // Find daemon relative to this file — works for both:
60
+ // npx tsx src/main.ts → src/browser/mcp.ts → src/daemon.ts
61
+ // node dist/main.js → dist/browser/mcp.js → dist/daemon.js
62
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
63
+ const parentDir = path.resolve(__dirname, '..');
64
+ const daemonTs = path.join(parentDir, 'daemon.ts');
65
+ const daemonJs = path.join(parentDir, 'daemon.js');
66
+ const isTs = fs.existsSync(daemonTs);
67
+ const daemonPath = isTs ? daemonTs : daemonJs;
68
+ if (process.env.OPENCLI_VERBOSE) {
69
+ console.error(`[opencli] Starting daemon (${isTs ? 'ts' : 'js'})...`);
70
+ }
71
+ // Use the current runtime to spawn daemon — avoids slow npx resolution.
72
+ // If already running under tsx (dev), process.execPath is tsx's node.
73
+ // If running compiled (node dist/), process.execPath is node.
74
+ this._daemonProc = spawn(process.execPath, [daemonPath], {
75
+ detached: true,
76
+ stdio: 'ignore',
77
+ env: { ...process.env },
78
+ });
79
+ this._daemonProc.unref();
80
+ // Wait for daemon to be ready AND extension to connect
81
+ const deadline = Date.now() + DAEMON_SPAWN_TIMEOUT;
82
+ while (Date.now() < deadline) {
83
+ await new Promise(resolve => setTimeout(resolve, 300));
84
+ if (await isExtensionConnected())
85
+ return;
86
+ }
87
+ // Daemon might be up but extension not connected — give a useful error
88
+ if (await isDaemonRunning()) {
89
+ throw new Error('Daemon is running but the Browser Extension is not connected.\n' +
90
+ 'Please install and enable the opencli Browser Bridge extension in Chrome.');
91
+ }
92
+ throw new Error('Failed to start opencli daemon. Try running manually:\n' +
93
+ ` node ${daemonPath}\n` +
94
+ 'Make sure port 19825 is available.');
309
95
  }
310
96
  }
@@ -1,14 +1,23 @@
1
1
  /**
2
- * Page abstraction wrapping JSON-RPC calls to Playwright MCP.
2
+ * Page abstraction implements IPage by sending commands to the daemon.
3
+ *
4
+ * All browser operations are ultimately 'exec' (JS evaluation via CDP)
5
+ * plus a few native Chrome Extension APIs (tabs, cookies, navigate).
6
+ *
7
+ * IMPORTANT: After goto(), we remember the tabId returned by the navigate
8
+ * action and pass it to all subsequent commands. This avoids the issue
9
+ * where resolveTabId() in the extension picks a chrome:// or
10
+ * chrome-extension:// tab that can't be debugged.
3
11
  */
4
12
  import type { IPage } from '../types.js';
5
13
  /**
6
- * Page abstraction wrapping JSON-RPC calls to Playwright MCP.
14
+ * Page implements IPage by talking to the daemon via HTTP.
7
15
  */
8
16
  export declare class Page implements IPage {
9
- private _request;
10
- constructor(_request: (method: string, params?: Record<string, unknown>) => Promise<Record<string, unknown>>);
11
- call(method: string, params?: Record<string, unknown>): Promise<any>;
17
+ /** Active tab ID, set after navigate and used in all subsequent commands */
18
+ private _tabId;
19
+ /** Helper: spread tabId into command params if we have one */
20
+ private _tabOpt;
12
21
  goto(url: string): Promise<void>;
13
22
  evaluate(js: string): Promise<any>;
14
23
  snapshot(opts?: {
@@ -31,7 +40,20 @@ export declare class Page implements IPage {
31
40
  selectTab(index: number): Promise<void>;
32
41
  networkRequests(includeStatic?: boolean): Promise<any>;
33
42
  consoleMessages(level?: string): Promise<any>;
34
- scroll(direction?: string, _amount?: number): Promise<void>;
43
+ /**
44
+ * Capture a screenshot via CDP Page.captureScreenshot.
45
+ * @param options.format - 'png' (default) or 'jpeg'
46
+ * @param options.quality - JPEG quality 0-100
47
+ * @param options.fullPage - capture full scrollable page
48
+ * @param options.path - save to file path (returns base64 if omitted)
49
+ */
50
+ screenshot(options?: {
51
+ format?: 'png' | 'jpeg';
52
+ quality?: number;
53
+ fullPage?: boolean;
54
+ path?: string;
55
+ }): Promise<string>;
56
+ scroll(direction?: string, amount?: number): Promise<void>;
35
57
  autoScroll(options?: {
36
58
  times?: number;
37
59
  delayMs?: number;