page-recorder-mcp 1.3.0 → 1.4.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/README.md CHANGED
@@ -153,13 +153,15 @@ npx -y page-recorder-mcp # 或者从源码:node bridge/server.js
153
153
  ### 接入 Claude Code(MCP)
154
154
 
155
155
  ```bash
156
- # stdio 方式(推荐;如果桥接服务已经在运行,这个实例会自动转发给它)
156
+ # stdio 方式(推荐,不用先手动启动桥接服务)
157
157
  claude mcp add page-recorder -- npx -y page-recorder-mcp --stdio
158
158
 
159
159
  # 或者 HTTP 方式(需要先运行 npx -y page-recorder-mcp)
160
160
  claude mcp add --transport http page-recorder http://127.0.0.1:17321/mcp
161
161
  ```
162
162
 
163
+ stdio 方式第一次启动时会在后台起一个桥接服务,之后各个 AI 工具、各次会话都复用它,扩展一直连着,不用每次等它重连。启动过它的程序(WorkBuddy、Cursor、Claude Code 等)都退出后,后台桥接自动关闭;日志在 `~/.page-recorder/`。打开 AI 工具后第一次用时扩展可能还没连上,先只有通用工具,扩展连上后(最多 30 秒)各脚本的工具会自动出现。不想要后台进程的话加 `--no-daemon`。
164
+
163
165
  ### 接入 Accio
164
166
 
165
167
  在 Accio 里添加自定义 MCP:
@@ -175,7 +177,7 @@ claude mcp add --transport http page-recorder http://127.0.0.1:17321/mcp
175
177
  }
176
178
  ```
177
179
 
178
- 新录了脚本以后,在 Accio 里把 page-recorder 断开再连上,工具列表才会更新(通用的 `run_recording`、`call_api` 不受影响)。其他支持 MCP 的工具(Claude Desktop、Cursor 等)用同样的命令或 URL 添加。不支持 MCP 的工具,可以直接调下面的 REST API。
180
+ 新录了脚本以后,在 Accio 里把 page-recorder 断开再连上,工具列表才会更新(通用的 `run_recording`、`call_api` 不受影响)。其他支持 MCP 的工具(WorkBuddy、Claude Desktop、Cursor 等)用同样的命令或 URL 添加。不支持 MCP 的工具,可以直接调下面的 REST API。
179
181
 
180
182
  **只给 AI 用你需要的接口**:录制时会抓到很多接口,在「接口参数」页取消勾选不用的「AI 可调用」,MCP 里就只出现勾选的那几个工具。AI 调这些工具时,直接在开着的页面里发请求、拿结果,不操作页面。
181
183
 
@@ -184,13 +186,13 @@ claude mcp add --transport http page-recorder http://127.0.0.1:17321/mcp
184
186
  | 工具 | 作用 |
185
187
  |---|---|
186
188
  | `list_recordings` | 列出脚本库:名称、步骤、输入参数、每个接口拆出的工具 |
187
- | `get_recording` | 脚本详情:每个接口的 URL、参数、参数说明、响应结构和示例 |
189
+ | `get_recording` | 脚本详情:每个接口的 URL、参数、参数说明、响应结构和示例。内容多时先给概要(步骤、参数、接口目录)和 `result_id`,某个接口用 `read_result` 取 `path: "apis[序号]"` |
188
190
  | `run_recording` | 运行脚本,可改 `params` 和 `api_params`,返回数据。`mode`:`api` 不操作页面、直接请求关联了输入参数的接口;`ui` 回放页面操作;默认 `auto`(能直接请求就直接请求) |
189
191
  | `call_api` | 不回放页面操作,直接调用某个接口 |
190
- | `read_result` | 从上一次运行 / 调用的结果里按路径、字段、分页取一部分(不会再调接口) |
191
- | `get_script` | 获取导出的 JS 源码 |
192
+ | `read_result` | 从上一次运行 / 调用 / `get_recording` 的结果里按路径、字段、分页取一部分(不会再调接口) |
193
+ | `get_script` | 获取导出的 JS 源码:长的按行分段给(`start_line` / `line_count`),`to_file: true` 写成文件 |
192
194
  | `save_api_docs` | 把 AI 对接口的分析写回:命名、函数名、用途、参数说明 |
193
- | `export_package` / `import_package` | 导出 / 导入录制包(HTTP 方式导入要求服务设了 `--token`) |
195
+ | `export_package` / `import_package` | 导出 / 导入录制包:导出写成文件(`~/.page-recorder/exports/`)、返回路径(HTTP 方式照旧直接返回内容),导入可以传 `file`(HTTP 方式导入要求服务设了 `--token`) |
194
196
  | `<脚本>__run` | 每个脚本一个,用于整段回放 |
195
197
  | `<脚本>__<函数名>` | **每个接口一个独立工具**,例如 `product_search__searchProducts` |
196
198
 
package/bridge/server.js CHANGED
@@ -12,6 +12,7 @@ const crypto = require('crypto');
12
12
  const fs = require('fs');
13
13
  const path = require('path');
14
14
  const os = require('os');
15
+ const { spawn, execFile } = require('child_process');
15
16
 
16
17
  const ROOT = path.resolve(__dirname, '..'); // 扩展本体所在目录(npm 包根目录)
17
18
  let VERSION = '0.0.0';
@@ -39,6 +40,9 @@ if (argv[0] === '--help' || argv[0] === '-h') {
39
40
  --port <端口> 监听端口,默认 17321 PR_BRIDGE_PORT
40
41
  --host <地址> 监听地址,默认 127.0.0.1 PR_BRIDGE_HOST
41
42
  --token <口令> HTTP 调用需带 Authorization: Bearer <口令> PR_BRIDGE_TOKEN
43
+ --no-daemon --stdio 时不在后台起桥接,自己监听端口(旧做法)
44
+ --stdio 时会在后台起一个桥接,之后各个 AI 工具、各次会话都复用它,扩展不用反复重连;
45
+ 启动它的程序(WorkBuddy、Cursor 等)都退出后,后台桥接自动关闭。日志在 ~/.page-recorder/。
42
46
  改了端口的话,扩展「设置」里的桥接地址也要改成 ws://127.0.0.1:<端口>/ext;
43
47
  设置了 token 的话,桥接地址要写成 ws://127.0.0.1:<端口>/ext?token=<口令>。监听非本机地址时必须设置 token。
44
48
  多个浏览器资料(主 Chrome、指纹浏览器等)都装了扩展时可以同时连上,调用时用 browser 参数指定在哪个浏览器执行。
@@ -67,6 +71,13 @@ const PORT = Number(flag('port') || process.env.PR_BRIDGE_PORT || 17321);
67
71
  const HOST = flag('host') || process.env.PR_BRIDGE_HOST || '127.0.0.1';
68
72
  const TOKEN = flag('token') || process.env.PR_BRIDGE_TOKEN || ''; // 可选:设置后 HTTP 调用需带 Authorization: Bearer <token>
69
73
  const STDIO = argv.includes('--stdio');
74
+ const DAEMON = argv.includes('--daemon'); // stdio 实例在后台起的桥接:启动它的程序都退出后自己关闭
75
+ const NO_DAEMON = argv.includes('--no-daemon');
76
+ // 后台桥接的日志,以及本机转发用的口令文件(PR_BRIDGE_DIR 可改,测试用)
77
+ const STATE_DIR = process.env.PR_BRIDGE_DIR || path.join(os.homedir(), '.page-recorder');
78
+ const STATE_FILE = path.join(STATE_DIR, `bridge-${PORT}.json`);
79
+ // 监听端口的实例写进 STATE_FILE;转发过来的请求带上它,说明是本机 stdio 实例(AI 客户端自己起的进程)发的
80
+ const SECRET = crypto.randomBytes(24).toString('hex');
70
81
  // 不只监听本机时必须设置 token,否则局域网里任何人都能借你的浏览器登录态执行脚本
71
82
  if (!/^(127\.\d+\.\d+\.\d+|localhost|::1)$/.test(HOST) && !TOKEN) {
72
83
  process.stderr.write(`[page-recorder-bridge] 监听 ${HOST} 会暴露给本机以外的设备,必须同时设置 --token(或 PR_BRIDGE_TOKEN)\n`);
@@ -328,16 +339,26 @@ async function pickConn(method, params, browser) {
328
339
 
329
340
  // 调用扩展:本进程持有连接则直接发;否则(端口已被另一个桥接实例占用)通过 HTTP 转发给它
330
341
  // browser:多个浏览器资料都装了扩展时指定在哪个浏览器执行(instanceId 或资料名),不传则按录制自动找
342
+ // waitMs:扩展还没连上时最多等多久,默认按 service worker 最多每 30 秒唤醒一次重连来等
343
+ const EXT_WAIT_MS = 35000;
331
344
  let isPrimary = false;
332
345
  let markReady;
333
346
  const ready = new Promise((r) => { markReady = r; });
334
- async function extCall(method, params, timeoutMs, browser) {
347
+ async function extCall(method, params, timeoutMs, browser, waitMs) {
335
348
  timeoutMs = timeoutMs || 60000;
336
349
  browser = browser == null ? '' : String(browser).trim();
350
+ waitMs = waitMs == null ? EXT_WAIT_MS : waitMs;
337
351
  await ready;
338
- if (!isPrimary) return forwardToPrimary(method, params, timeoutMs, browser);
339
- // 扩展的 service worker 最多每 30 秒唤醒一次重连
340
- if (!(await waitExt(35000))) {
352
+ if (!isPrimary) {
353
+ try {
354
+ return await forwardToPrimary(method, params, timeoutMs, browser, waitMs);
355
+ } catch (e) {
356
+ // 后台桥接没了(启动它的程序都退出了、被关掉了):重新起一个再发一次
357
+ if (e.code !== 'ECONNREFUSED' || !STDIO || NO_DAEMON || !(await ensureBridge())) throw e;
358
+ return forwardToPrimary(method, params, timeoutMs, browser, waitMs);
359
+ }
360
+ }
361
+ if (!(await waitExt(waitMs))) {
341
362
  throw new Error('浏览器扩展未连接。请确认:1) Chrome 已打开并安装了 Page Recorder 扩展;2) 扩展设置中开启了“连接本地桥接服务”,地址为 ws://127.0.0.1:' + PORT + '/ext');
342
363
  }
343
364
  if (method === 'list') return listAll(params, timeoutMs, browser);
@@ -345,10 +366,17 @@ async function extCall(method, params, timeoutMs, browser) {
345
366
  }
346
367
  // 监听 0.0.0.0 / :: 时转发也走本机回环地址(Host 头校验只认本机地址)
347
368
  const WILDCARD = /^(0\.0\.0\.0|::|\[::\])$/.test(HOST);
348
- function forwardToPrimary(method, params, timeoutMs, browser) {
369
+ const BRIDGE_HOST = WILDCARD ? '127.0.0.1' : HOST;
370
+ // 发给监听端口的那个实例时带的请求头:token(设置了的话)和本机口令(读它写的 STATE_FILE)
371
+ function bridgeHeaders(extra) {
372
+ const h = Object.assign({}, extra, TOKEN ? { authorization: 'Bearer ' + TOKEN } : {});
373
+ try { h['x-page-recorder-secret'] = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')).secret; } catch (e) { /* 旧版桥接没写这个文件 */ }
374
+ return h;
375
+ }
376
+ function forwardToPrimary(method, params, timeoutMs, browser, waitMs) {
349
377
  return new Promise((resolve, reject) => {
350
- const body = JSON.stringify({ method, params, timeout: timeoutMs, browser: browser || undefined });
351
- const req = http.request({ host: WILDCARD ? '127.0.0.1' : HOST, port: PORT, path: '/api/ext', method: 'POST', headers: Object.assign({ 'content-type': 'application/json' }, TOKEN ? { authorization: 'Bearer ' + TOKEN } : {}) }, (res) => {
378
+ const body = JSON.stringify({ method, params, timeout: timeoutMs, browser: browser || undefined, wait: waitMs });
379
+ const req = http.request({ host: BRIDGE_HOST, port: PORT, path: '/api/ext', method: 'POST', headers: bridgeHeaders({ 'content-type': 'application/json' }) }, (res) => {
352
380
  let d = '';
353
381
  res.on('data', (c) => { d += c; });
354
382
  res.on('end', () => {
@@ -358,12 +386,167 @@ function forwardToPrimary(method, params, timeoutMs, browser) {
358
386
  } catch (e) { reject(new Error('桥接服务返回异常:' + d.slice(0, 200))); }
359
387
  });
360
388
  });
361
- req.on('error', (e) => reject(new Error('无法连接桥接服务:' + e.message)));
362
- req.setTimeout(timeoutMs + 5000, () => req.destroy(new Error('超时')));
389
+ req.on('error', (e) => reject(Object.assign(new Error('无法连接桥接服务:' + e.message), { code: e.code })));
390
+ req.setTimeout(waitMs + timeoutMs + 5000, () => req.destroy(new Error('超时')));
363
391
  req.end(body);
364
392
  });
365
393
  }
366
394
 
395
+ // ======================= 后台桥接(--stdio 时) =======================
396
+ // AI 客户端可能每条消息都重起一次 MCP 进程(WorkBuddy 就是这样)。桥接如果跟着 MCP 进程走,
397
+ // 扩展每次都要重连(最多 30 秒)。所以 stdio 实例在后台起一个独立的桥接,大家都转发给它;
398
+ // 每个 stdio 实例向它登记「启动自己的程序」,这些程序都退出后它自己关闭。
399
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
400
+ // 端口上有没有在应答的服务(不管是不是新版):连不上返回 false
401
+ function bridgeUp() {
402
+ return new Promise((resolve) => {
403
+ const req = http.get({ host: BRIDGE_HOST, port: PORT, path: '/api/status', headers: bridgeHeaders() }, (res) => { res.resume(); resolve(true); });
404
+ req.on('error', () => resolve(false));
405
+ req.setTimeout(1500, () => req.destroy());
406
+ });
407
+ }
408
+ function spawnDaemon() {
409
+ fs.mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
410
+ const logFile = path.join(STATE_DIR, `bridge-${PORT}.log`);
411
+ try { if (fs.statSync(logFile).size > 1e6) fs.truncateSync(logFile, 0); } catch (e) { /* 还没有日志 */ }
412
+ const out = fs.openSync(logFile, 'a');
413
+ // token 走环境变量,不出现在进程列表里
414
+ const child = spawn(process.execPath, [__filename, '--daemon', '--port', String(PORT), '--host', HOST], {
415
+ detached: true, windowsHide: true, stdio: ['ignore', out, out],
416
+ env: Object.assign({}, process.env, TOKEN ? { PR_BRIDGE_TOKEN: TOKEN } : {}),
417
+ });
418
+ child.on('error', (e) => log('后台桥接启动失败:' + e.message));
419
+ child.unref();
420
+ fs.closeSync(out);
421
+ log(`已在后台启动桥接(日志 ${logFile})`);
422
+ }
423
+ // 保证端口上有桥接:没有就在后台起一个,等它开始监听。几个调用同时来只起一次
424
+ let ensuring = null;
425
+ function ensureBridge() {
426
+ if (!ensuring) {
427
+ ensuring = (async () => {
428
+ if (await bridgeUp()) return true;
429
+ spawnDaemon();
430
+ for (const end = Date.now() + 3000; Date.now() < end;) {
431
+ await sleep(100);
432
+ if (await bridgeUp()) return true;
433
+ }
434
+ log('后台桥接 3 秒内没有启动');
435
+ return false;
436
+ })().finally(() => { ensuring = null; });
437
+ }
438
+ return ensuring;
439
+ }
440
+
441
+ // 进程表 pid -> { ppid, path },用来找是哪个程序启动了这个 MCP 进程
442
+ function processTable() {
443
+ return new Promise((resolve) => {
444
+ const table = new Map();
445
+ const parse = (out, re) => {
446
+ for (const line of String(out || '').split(/\r?\n/)) {
447
+ const m = line.match(re);
448
+ if (m) table.set(Number(m[1]), { ppid: Number(m[2]), path: m[3].trim() });
449
+ }
450
+ resolve(table);
451
+ };
452
+ if (process.platform === 'win32') {
453
+ const ps = 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId)`t$($_.ParentProcessId)`t$($_.ExecutablePath)" }';
454
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', ps], { windowsHide: true, timeout: 20000, maxBuffer: 32e6 }, (e, out) => parse(out, /^(\d+)\t(\d+)\t(.*)$/));
455
+ } else if (process.platform === 'linux') {
456
+ for (const name of fs.readdirSync('/proc').filter((x) => /^\d+$/.test(x))) {
457
+ try {
458
+ const stat = fs.readFileSync(`/proc/${name}/stat`, 'utf8');
459
+ let exe = '';
460
+ try { exe = fs.readlinkSync(`/proc/${name}/exe`); } catch (e) { /* 别人的进程读不到 */ }
461
+ table.set(Number(name), { ppid: Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]), path: exe });
462
+ } catch (e) { /* 进程刚退出 */ }
463
+ }
464
+ resolve(table);
465
+ } else {
466
+ execFile('ps', ['-A', '-o', 'pid=,ppid=,comm='], { timeout: 10000, maxBuffer: 32e6 }, (e, out) => parse(out, /^\s*(\d+)\s+(\d+)\s+(.*)$/));
467
+ }
468
+ });
469
+ }
470
+ // 启动链上的中间层:npx、node、shell 等,不算「启动它的程序」
471
+ const LAUNCHERS = new Set(['node', 'npm', 'npx', 'sh', 'bash', 'zsh', 'dash', 'fish', 'login', 'env', 'cmd', 'powershell', 'pwsh', 'conhost']);
472
+ function exeName(p) {
473
+ return path.basename(String(p).replace(/\\/g, '/')).replace(/^-/, '').replace(/\.exe$/i, '').toLowerCase();
474
+ }
475
+ // 同一个程序:macOS 看所在的 .app(主进程和各种 Helper 都在里面),其他系统看可执行文件路径
476
+ function appKey(p) {
477
+ const s = String(p).replace(/\\/g, '/').toLowerCase();
478
+ const i = s.indexOf('.app/');
479
+ return i >= 0 ? s.slice(0, i + 4) : s;
480
+ }
481
+ // 顺着父进程往上:跳过启动链上的中间层,找到第一个程序,再往上走到同一个程序的最外层进程。
482
+ // WorkBuddy 每条消息起的进程和主进程是同一个 .app,最后落到 WorkBuddy 主进程;终端里跑的 claude 就是 claude 自己
483
+ function ownerPid(table) {
484
+ const chain = [];
485
+ for (let pid = process.ppid; pid > 1 && table.has(pid) && !chain.includes(pid); pid = table.get(pid).ppid) chain.push(pid);
486
+ // npx 起的进程会把名字改成「npm exec …」
487
+ const launcher = (pid) => LAUNCHERS.has(exeName(table.get(pid).path)) || /^npm\b/i.test(table.get(pid).path);
488
+ const i = chain.findIndex((pid) => !launcher(pid));
489
+ if (i < 0) return process.ppid;
490
+ let owner = chain[i];
491
+ for (const pid of chain.slice(i + 1)) {
492
+ if (appKey(table.get(pid).path) !== appKey(table.get(owner).path)) break;
493
+ owner = pid;
494
+ }
495
+ return owner;
496
+ }
497
+ let ownerOnce = null;
498
+ function registerOwner() {
499
+ if (!ownerOnce) ownerOnce = processTable().then(ownerPid, () => process.ppid).catch(() => process.ppid);
500
+ return ownerOnce.then((owner) => new Promise((resolve) => {
501
+ const req = http.request({ host: BRIDGE_HOST, port: PORT, path: '/api/owners', method: 'POST', headers: bridgeHeaders({ 'content-type': 'application/json' }) }, (res) => { res.resume(); resolve(); });
502
+ req.on('error', () => resolve());
503
+ req.end(JSON.stringify({ pids: [process.pid, owner] }));
504
+ }));
505
+ }
506
+ // 订阅后台桥接的事件:脚本库变化、扩展连上时通知 AI 客户端重新拉工具列表。
507
+ // 断了就重连(桥接没了就重新起一个),重连上以后重新登记、通知一次
508
+ function watchBridge(reconnected) {
509
+ let retried = false;
510
+ const retry = () => setTimeout(async () => { if (await ensureBridge()) watchBridge(true); else retry(); }, 2000);
511
+ const again = () => { // end 和 error 可能都来:只重连一次
512
+ if (retried) return;
513
+ retried = true;
514
+ retry();
515
+ };
516
+ const req = http.get({ host: BRIDGE_HOST, port: PORT, path: '/api/events', headers: bridgeHeaders() }, (res) => {
517
+ if (res.statusCode !== 200) { res.resume(); return; } // 旧版桥接没有事件:不订阅
518
+ registerOwner();
519
+ if (reconnected) toolsChanged();
520
+ res.setEncoding('utf8');
521
+ let buf = '';
522
+ res.on('data', (d) => {
523
+ buf += d;
524
+ for (let i; (i = buf.indexOf('\n\n')) >= 0; buf = buf.slice(i + 2)) if (buf.slice(0, i).includes('event: tools')) toolsChanged();
525
+ });
526
+ res.on('end', again);
527
+ res.on('error', again);
528
+ });
529
+ req.on('error', again);
530
+ }
531
+
532
+ // 后台桥接:记下启动它的程序,这些程序都退出后关闭
533
+ const owners = new Set();
534
+ let everOwned = false;
535
+ function alive(pid) {
536
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
537
+ }
538
+ if (DAEMON) {
539
+ const started = Date.now();
540
+ setInterval(() => {
541
+ for (const pid of owners) if (!alive(pid)) owners.delete(pid);
542
+ // 刚起来时给 stdio 实例 30 秒登记
543
+ if (!owners.size && (everOwned || Date.now() - started > 30000)) {
544
+ log('启动桥接的程序都已退出,桥接关闭');
545
+ process.exit(0);
546
+ }
547
+ }, 2000);
548
+ }
549
+
367
550
  // ======================= MCP 工具 =======================
368
551
  const SAVE_DOCS_FORMAT = `{
369
552
  "title": "脚本中文名",
@@ -401,8 +584,8 @@ const STATIC_TOOLS = [
401
584
  },
402
585
  {
403
586
  name: 'get_recording',
404
- description: '获取某个录制脚本的详细信息:每一步操作、输入参数说明(paramHelp / paramInfo:类型、格式、全部可选项、是否必填、关联的接口字段)、每个接口的 URL / 参数 / 参数说明 / 响应结构 / 响应示例 / 用途说明。分析接口用途前先调用它。',
405
- inputSchema: { type: 'object', properties: { recording: { type: 'string', description: '脚本 id 或名称' }, browser: BROWSER_PARAM }, required: ['recording'] },
587
+ description: '获取某个录制脚本的详细信息:每一步操作、输入参数说明(paramHelp / paramInfo:类型、格式、全部可选项、是否必填、关联的接口字段)、每个接口的 URL / 参数 / 参数说明 / 响应结构 / 响应示例 / 用途说明。分析接口用途前先调用它。内容太多时先返回概要(步骤、参数、接口目录)和 result_id,某个接口的详情用 read_result 取 path="apis[序号]",也可以直接带 result_path。',
588
+ inputSchema: { type: 'object', properties: { recording: { type: 'string', description: '脚本 id 或名称' }, browser: BROWSER_PARAM, ...RESULT_PROPS }, required: ['recording'] },
406
589
  },
407
590
  {
408
591
  name: 'run_recording',
@@ -442,7 +625,7 @@ const STATIC_TOOLS = [
442
625
  },
443
626
  {
444
627
  name: 'read_result',
445
- description: '从上一次 run_recording / call_api / 接口工具的结果里取一部分,不会再调接口。结果太大时那些工具只返回压缩过的预览和 result_id,用这个工具按路径取具体数据:path 指到某个对象或数组(预览里省略的地方都写了路径),数组用 offset / limit 分页,fields 只留每一项里要的字段。例:path="responses[0].data.data.result.data.table.dataSource",fields=["itemId","itemDesc.desc[0].text","managerPrice.currentPrice"]。',
628
+ description: '从上一次 run_recording / call_api / 接口工具 / get_recording 的结果里取一部分,不会再调接口。结果太大时那些工具只返回压缩过的预览和 result_id,用这个工具按路径取具体数据:path 指到某个对象或数组(预览里省略的地方都写了路径),数组用 offset / limit 分页,fields 只留每一项里要的字段。例:path="responses[0].data.data.result.data.table.dataSource",fields=["itemId","itemDesc.desc[0].text","managerPrice.currentPrice"]。',
446
629
  inputSchema: {
447
630
  type: 'object',
448
631
  properties: {
@@ -459,8 +642,19 @@ const STATIC_TOOLS = [
459
642
  },
460
643
  {
461
644
  name: 'get_script',
462
- description: '获取录制脚本的完整 JavaScript 源码(可直接粘贴到浏览器控制台或用 Playwright page.evaluate 执行)。',
463
- inputSchema: { type: 'object', properties: { recording: { type: 'string', description: '脚本 id 或名称' }, browser: BROWSER_PARAM }, required: ['recording'] },
645
+ description: '获取录制脚本的 JavaScript 源码(可直接粘贴到浏览器控制台或用 Playwright page.evaluate 执行)。源码长时按行分段返回,开头写着总行数和下一段从哪行开始;要整份源码用 to_file=true 写成文件。',
646
+ inputSchema: {
647
+ type: 'object',
648
+ properties: {
649
+ recording: { type: 'string', description: '脚本 id 或名称' },
650
+ start_line: { type: 'number', description: '从第几行开始读,默认 1' },
651
+ line_count: { type: 'number', description: '最多读几行(还受 max_chars 限制)' },
652
+ max_chars: { type: 'number', description: `这次最多返回多少字符,默认 ${RESULT_CHARS}` },
653
+ to_file: { type: 'boolean', description: '把整份源码写到本机文件(~/.page-recorder/exports/),只返回文件路径' },
654
+ browser: BROWSER_PARAM,
655
+ },
656
+ required: ['recording'],
657
+ },
464
658
  },
465
659
  {
466
660
  name: 'save_api_docs',
@@ -477,19 +671,19 @@ const STATIC_TOOLS = [
477
671
  },
478
672
  {
479
673
  name: 'export_package',
480
- description: '把录制脚本导出成录制包(JSON,已脱敏:不含密码、登录令牌等)。可以存成 <名称>.prpkg.json 文件,用来换电脑、发给同事或备份;用 import_package 或扩展弹窗「脚本库 → 导入录制包」导回。',
674
+ description: '把录制脚本导出成录制包(JSON,已脱敏:不含密码、登录令牌等),写成本机文件(~/.page-recorder/exports/<名称>-<时间>.prpkg.json),返回文件路径和概况;包不大时也直接带上内容(通过 HTTP /mcp 调用时直接返回内容,不写文件)。用来换电脑、发给同事或备份;用 import_package(传 file)或扩展弹窗「脚本库 → 导入录制包」导回。',
481
675
  inputSchema: { type: 'object', properties: { recording: { type: 'string', description: '脚本 id 或名称' }, browser: BROWSER_PARAM }, required: ['recording'] },
482
676
  },
483
677
  {
484
678
  name: 'import_package',
485
- description: '把录制包(export_package 返回的 JSON,或扩展弹窗导出的 .prpkg.json 文件内容)导入浏览器扩展的脚本库,成为一条新脚本,返回新脚本的 id 和名称。通过 HTTP(/mcp)调用时桥接服务必须设置了 token。',
679
+ description: '把录制包(export_package 导出的文件,或扩展弹窗导出的 .prpkg.json)导入浏览器扩展的脚本库,成为一条新脚本,返回新脚本的 id 和名称。pkg(JSON 内容)和 file(文件路径)给一个,包大时用 file。通过 HTTP(/mcp)调用时桥接服务必须设置了 token。',
486
680
  inputSchema: {
487
681
  type: 'object',
488
682
  properties: {
489
683
  pkg: { type: 'object', description: '录制包 JSON:{ "format": "page-recorder-package", "version": 1, "name": …, "item": {…} }', additionalProperties: true },
684
+ file: { type: 'string', description: '录制包文件的路径(.json 结尾,如 export_package 返回的 file)' },
490
685
  browser: Object.assign({}, BROWSER_PARAM, { description: '可选。多个浏览器资料都装了扩展时,指定导入到哪个浏览器:填 instanceId 或资料名。只连着一个浏览器时不用传' }),
491
686
  },
492
- required: ['pkg'],
493
687
  },
494
688
  },
495
689
  ];
@@ -577,10 +771,29 @@ function withResultProps(schema) {
577
771
  s.properties = Object.assign({}, RESULT_PROPS, s.properties || {});
578
772
  return s;
579
773
  }
580
- async function dynamicTools() {
774
+ // tools/list 不能久等:WorkBuddy 等客户端拉工具列表约 10 秒就超时,超时后一个工具都不给 AI。
775
+ // 所以 quick(tools/list)时连等后台桥接、等扩展一共最多等 6 秒,没等到先只给固定工具:
776
+ // 扩展连上后会发 tools/list_changed;列表晚到的话先存着再发一次,客户端重新拉时直接用
777
+ const LIST_DEADLINE_MS = 6000;
778
+ let lateList = null; // { list, at }
779
+ async function dynamicTools(quick) {
581
780
  dynamicMap = new Map();
582
781
  let list = [];
583
- try { list = await extCall('list', {}, 15000); } catch (e) { return []; }
782
+ if (quick && lateList && Date.now() - lateList.at < 60000) {
783
+ list = lateList.list;
784
+ lateList = null;
785
+ } else if (quick) {
786
+ const listing = extCall('list', {}, 15000, '', 2000);
787
+ const late = {};
788
+ const got = await Promise.race([listing.catch(() => []), sleep(LIST_DEADLINE_MS).then(() => late)]);
789
+ if (got === late) {
790
+ listing.then((l) => { lateList = { list: l, at: Date.now() }; toolsChanged(); }, () => {});
791
+ return [];
792
+ }
793
+ list = got;
794
+ } else {
795
+ try { list = await extCall('list', {}, 15000); } catch (e) { return []; }
796
+ }
584
797
  const tools = [];
585
798
  const used = new Set(STATIC_TOOLS.map((t) => t.name));
586
799
  // 多个浏览器同时连着:工具说明里注明是哪个浏览器的脚本,调用时直接发给那个浏览器
@@ -633,6 +846,17 @@ function parsePkg(pkg) {
633
846
  if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg)) throw new Error('pkg 必须是录制包 JSON 对象(export_package 或弹窗「导出录制包」得到的内容)');
634
847
  return pkg;
635
848
  }
849
+ // 从文件读录制包:只读 .json 文件,报错时不带出文件内容
850
+ function readPkgFile(file) {
851
+ const f = path.resolve(String(file).replace(/^~(?=$|[\\/])/, os.homedir()));
852
+ if (!/\.json$/i.test(f)) throw new Error('录制包文件要以 .json 结尾(export_package 导出的是 .prpkg.json)');
853
+ let st;
854
+ try { st = fs.statSync(f); } catch (e) { throw new Error('读不到录制包文件:' + f); }
855
+ if (!st.isFile() || st.size > 50 * 1024 * 1024) throw new Error('不是录制包文件,或文件超过 50MB:' + f);
856
+ let pkg;
857
+ try { pkg = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { throw new Error('录制包文件不是合法的 JSON:' + f); }
858
+ return parsePkg(pkg);
859
+ }
636
860
 
637
861
  // ======================= 给 AI 的结果 =======================
638
862
  // 接口返回常常很大(一页商品十几万字符),数据还套在 JSON 字符串里(淘宝 mtop 的 data.result)。原样整段发给 AI,
@@ -936,6 +1160,59 @@ const resultNames = (own) => RESULT_ARGS.filter((k) => !(own || []).includes(k))
936
1160
  const resultOpts = (args, own) => Object.fromEntries(resultNames(own).filter((k) => args[k] != null).map((k) => [k, args[k]]));
937
1161
  const withoutResultArgs = (args, own) => { const drop = resultNames(own); return Object.fromEntries(Object.entries(args).filter(([k]) => !drop.includes(k))); };
938
1162
  const aiResult = (result, args, own) => text(aiText(result, resultOpts(args || {}, own)));
1163
+
1164
+ // get_recording:接口多、响应示例长时整份有十几万字符,客户端放不下。先给概要(步骤、参数、接口目录),
1165
+ // 完整内容留在桥接里,用 read_result 按 apis[i] 取某个接口;带了 result_path 等参数就直接按参数取
1166
+ function recordingDetail(full, args) {
1167
+ const opts = resultOpts(args);
1168
+ if (Object.keys(opts).length || jsonLen(full) <= RESULT_CHARS) return aiResult(full, args);
1169
+ const id = saveResult(full, jsonBytes(full));
1170
+ if (!id) return aiResult(full, args); // 留不下:按结构压缩的预览
1171
+ const o = { result_id: id };
1172
+ const SHOWN = ['id', 'name', 'description', 'startUrl', 'steps', 'params', 'paramHelp'];
1173
+ for (const k of SHOWN) if (full[k] !== undefined) o[k] = full[k];
1174
+ o.apis = (full.apis || []).map((a, i) => ({ path: `apis[${i}]`, fn: a.fn, name: a.name, title: a.title || undefined, ignore: a.ignore || undefined, count: a.count }));
1175
+ o.tools = (full.tools || []).map((t) => t.name);
1176
+ const rest = Object.keys(full).filter((k) => !SHOWN.includes(k) && k !== 'apis').map((k) => `"${k}"`);
1177
+ o.note = `完整内容共 ${sizeText(jsonLen(full))},这里只给概要。某个接口的 URL、参数、参数说明、响应结构、响应示例用 read_result 取:result_id="${id}",path 写上面 apis 里的 path(如 "apis[0]"),只看几项加 fields(如 ["url","params","responseSchema"])。${rest.length ? `其他部分的 path:${rest.join('、')}(paramInfo 是参数的完整说明,tools 是各接口工具的参数定义,analysisPrompt 是分析接口用的提示词)。` : ''}result_id 过期了就重新调用 get_recording 并直接带 result_path`;
1178
+ const t = JSON.stringify(o, null, 2);
1179
+ return t.length <= RESULT_CHARS ? text(t) : text(aiText(full, {}, { id, entry: savedResult(id) }));
1180
+ }
1181
+ // get_script:按行分段。开头一行注释写总行数和下一段从哪行开始
1182
+ function scriptPart(script, args) {
1183
+ const budget = Math.max(2000, Math.min(400000, Math.floor(Number(args.max_chars)) || RESULT_CHARS));
1184
+ if (args.start_line == null && args.line_count == null && script.length <= budget) return script;
1185
+ const lines = script.split('\n');
1186
+ const start = Math.min(lines.length, Math.max(1, Math.floor(Number(args.start_line)) || 1));
1187
+ const want = Math.floor(Number(args.line_count)) > 0 ? Math.floor(Number(args.line_count)) : Infinity;
1188
+ const out = [];
1189
+ let used = 0;
1190
+ for (let i = start - 1; i < lines.length && out.length < want; i++) {
1191
+ let line = lines[i];
1192
+ if (used + line.length + 1 > budget - 300) {
1193
+ if (out.length) break;
1194
+ line = clip(line, budget - 400); // 一行就超长:截断着给
1195
+ }
1196
+ out.push(line);
1197
+ used += line.length + 1;
1198
+ }
1199
+ const end = start + out.length - 1;
1200
+ const next = end < lines.length ? `接着读用 start_line=${end + 1};` : '已经到结尾;';
1201
+ return `// 源码共 ${lines.length} 行、${script.length} 字符,这里是第 ${start}-${end} 行。${next}要整份源码用 to_file=true 写成文件\n${out.join('\n')}`;
1202
+ }
1203
+ // 大块内容写成本机文件给 AI:放在 STATE_DIR/exports,文件名带时间不会覆盖
1204
+ function writeExport(name, ext, content) {
1205
+ const dir = path.join(STATE_DIR, 'exports');
1206
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
1207
+ const base = path.join(dir, `${String(name || 'recording').replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 60)}-${new Date().toISOString().replace(/\D/g, '').slice(0, 17)}`);
1208
+ for (let i = 1; ; i++) {
1209
+ const file = base + (i > 1 ? '-' + i : '') + ext;
1210
+ try {
1211
+ fs.writeFileSync(file, content, { mode: 0o600, flag: 'wx' });
1212
+ return file;
1213
+ } catch (e) { if (e.code !== 'EEXIST') throw e; }
1214
+ }
1215
+ }
939
1216
  // ctx.via:'stdio' = 本进程的 MCP stdio;'http' = /mcp 接口
940
1217
  async function callTool(name, args, ctx) {
941
1218
  args = args || {};
@@ -943,10 +1220,14 @@ async function callTool(name, args, ctx) {
943
1220
  const browser = args.browser;
944
1221
  switch (name) {
945
1222
  case 'list_recordings': return text((await extCall('list', {}, 60000, browser)).map((r) => forAi(r, false)));
946
- case 'get_recording': return text(forAi(await extCall('get', { recording: args.recording }, 60000, browser), true));
1223
+ case 'get_recording': return recordingDetail(forAi(await extCall('get', { recording: args.recording }, 60000, browser), true), args);
947
1224
  case 'get_script': {
948
1225
  const r = await extCall('script', { recording: args.recording }, 60000, browser);
949
- return text(r.script);
1226
+ if (args.to_file) {
1227
+ const lines = String(r.script || '').split('\n').length;
1228
+ return text({ file: writeExport(r.name || args.recording, '.js', r.script || ''), lines, chars: String(r.script || '').length });
1229
+ }
1230
+ return text(scriptPart(String(r.script || ''), args));
950
1231
  }
951
1232
  case 'run_recording': {
952
1233
  const timeout = Number(args.timeout_ms) || 180000;
@@ -955,7 +1236,7 @@ async function callTool(name, args, ctx) {
955
1236
  case 'call_api': return aiResult(await extCall('call', { recording: args.recording, api: args.api, args: args.args || {} }, 90000, browser), args);
956
1237
  case 'read_result': {
957
1238
  const entry = savedResult(args.result_id);
958
- if (!entry) throw new Error(`result_id ${args.result_id || '(没给)'} 已经不在了:桥接只留最近 ${RESULT_KEEP} 次、30 分钟内的结果,重启后清空。请重新调用接口`);
1239
+ if (!entry) throw new Error(`result_id ${args.result_id || '(没给)'} 已经不在了:只留最近 ${RESULT_KEEP} 次、30 分钟内的结果,MCP 进程重启后清空(有的 AI 工具每条消息都重启一次,上一条消息的结果读不到)。请重新调用并直接带 result_path / result_fields 取要的部分;get_recording 也一样,如 result_path="apis[3]"`);
959
1240
  return text(aiText(entry.raw, { result_path: args.path == null ? '' : args.path, result_fields: args.fields, result_offset: args.offset, result_limit: args.limit, result_max_chars: args.max_chars, raw: !!args.raw }, { id: String(args.result_id), entry }));
960
1241
  }
961
1242
  case 'save_api_docs': {
@@ -965,11 +1246,27 @@ async function callTool(name, args, ctx) {
965
1246
  }
966
1247
  case 'export_package': {
967
1248
  const r = await extCall('exportPackage', { recording: args.recording }, 60000, browser);
968
- return text(r && r.pkg ? r.pkg : r);
1249
+ const pkg = r && r.pkg ? r.pkg : r;
1250
+ // HTTP 调用的客户端可能在别的机器上,读不到这台机器的文件:照旧直接给内容
1251
+ if (ctx.via === 'http') return text(pkg);
1252
+ const body = JSON.stringify(pkg, null, 2);
1253
+ const events = (pkg && pkg.item && pkg.item.events) || [];
1254
+ const out = {
1255
+ file: writeExport((pkg && pkg.name) || args.recording, '.prpkg.json', body),
1256
+ name: pkg && pkg.name,
1257
+ chars: body.length,
1258
+ steps: events.filter((e) => e && e.kind === 'step').length,
1259
+ requests: events.filter((e) => e && e.kind === 'request').length,
1260
+ };
1261
+ // 包不大就顺便带上内容,省得再读文件
1262
+ if (body.length + 500 <= RESULT_CHARS) out.pkg = pkg;
1263
+ else out.note = `录制包 ${body.length} 字符,太大不直接给:内容在 file 里。导回用 import_package 传 file`;
1264
+ return text(out);
969
1265
  }
970
1266
  case 'import_package': {
971
1267
  if (ctx.via === 'http' && !TOKEN) throw new Error(IMPORT_NEEDS_TOKEN);
972
- return text(await extCall('importPackage', { pkg: parsePkg(args.pkg) }, 60000, browser));
1268
+ if (args.pkg == null && !args.file) throw new Error('pkg(录制包 JSON)和 file(录制包文件路径)给一个');
1269
+ return text(await extCall('importPackage', { pkg: args.pkg != null ? parsePkg(args.pkg) : readPkgFile(args.file) }, 60000, browser));
973
1270
  }
974
1271
  default: {
975
1272
  if (!dynamicMap.has(name)) await dynamicTools();
@@ -997,7 +1294,7 @@ async function handleRpc(msg, ctx) {
997
1294
  case 'notifications/cancelled':
998
1295
  return null;
999
1296
  case 'ping': return ok({});
1000
- case 'tools/list': return ok({ tools: STATIC_TOOLS.concat(await dynamicTools()) });
1297
+ case 'tools/list': return ok({ tools: STATIC_TOOLS.concat(await dynamicTools(true)) });
1001
1298
  case 'tools/call': {
1002
1299
  try {
1003
1300
  return ok(await callTool(params.name, params.arguments, ctx));
@@ -1015,10 +1312,10 @@ async function handleRpc(msg, ctx) {
1015
1312
  }
1016
1313
 
1017
1314
  // ======================= HTTP 服务 =======================
1018
- function readBody(req) {
1315
+ function readBody(req, max) {
1019
1316
  return new Promise((resolve, reject) => {
1020
1317
  let d = '';
1021
- req.on('data', (c) => { d += c; if (d.length > 20e6) req.destroy(); });
1318
+ req.on('data', (c) => { d += c; if (d.length > (max || 20e6)) req.destroy(); });
1022
1319
  req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { reject(new Error('请求体不是合法 JSON')); } });
1023
1320
  req.on('error', reject);
1024
1321
  });
@@ -1051,6 +1348,12 @@ function hostAllowed(req) {
1051
1348
  if (!WILDCARD) return name === HOST.toLowerCase().replace(/^\[|\]$/g, '');
1052
1349
  return Object.values(os.networkInterfaces()).some((list) => (list || []).some((x) => String(x.address).toLowerCase() === name));
1053
1350
  }
1351
+ // 本机 stdio 实例转发来的请求:带着本实例写进 STATE_FILE 的口令
1352
+ function fromStdio(req) {
1353
+ const got = Buffer.from(String(req.headers['x-page-recorder-secret'] || ''));
1354
+ const want = Buffer.from(SECRET);
1355
+ return got.length === want.length && crypto.timingSafeEqual(got, want);
1356
+ }
1054
1357
  // 请求里的 browser 参数:查询串 ?browser= 或请求体里的 browser
1055
1358
  const browserOf = (u, b) => u.searchParams.get('browser') || (b && typeof b.browser === 'string' ? b.browser : '') || '';
1056
1359
 
@@ -1075,7 +1378,8 @@ async function route(req, res) {
1075
1378
  }
1076
1379
  if (p === '/' || p === '/api' || p === '/api/status') {
1077
1380
  return sendJson(res, 200, {
1078
- ok: true, name: 'page-recorder-bridge', version: VERSION, extensionConnected: instances.size > 0,
1381
+ ok: true, name: 'page-recorder-bridge', version: VERSION, pid: process.pid, extensionConnected: instances.size > 0,
1382
+ ...(DAEMON ? { background: true, owners: [...owners] } : {}),
1079
1383
  browsers: [...instances.values()].map((c) => Object.assign(browserInfo(c), { version: c.version })),
1080
1384
  endpoints: {
1081
1385
  'GET /api/recordings': '脚本列表(含每个接口拆出的工具;多个浏览器时汇总,每条带 browser)',
@@ -1091,11 +1395,30 @@ async function route(req, res) {
1091
1395
  browserParam: '以上接口都可以带 ?browser=<instanceId 或资料名>(POST 也可以放在 body.browser):多个浏览器资料都装了扩展时用来指定在哪个浏览器执行',
1092
1396
  });
1093
1397
  }
1094
- if (p === '/api/ext' && req.method === 'POST') {
1095
- // 另一个桥接进程(stdio)转发来的调用
1398
+ if (p === '/api/events' && req.method === 'GET') {
1399
+ // stdio 实例订阅:脚本库变化、扩展连上或断开时推一条,让它通知 AI 客户端重新拉工具列表
1400
+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache' });
1401
+ res.write(': ok\n\n');
1402
+ const push = () => res.write('event: tools\ndata: {}\n\n');
1403
+ libraryListeners.add(push);
1404
+ res.on('close', () => libraryListeners.delete(push));
1405
+ return;
1406
+ }
1407
+ if (p === '/api/owners' && req.method === 'POST') {
1408
+ // stdio 实例登记启动它的程序(后台桥接在这些程序都退出后关闭)
1409
+ if (!fromStdio(req)) return sendJson(res, 403, { ok: false, error: 'forbidden' });
1096
1410
  const b = await readBody(req);
1097
- if (b.method === 'importPackage' && !TOKEN) return sendJson(res, 403, { ok: false, error: IMPORT_NEEDS_TOKEN });
1098
- return sendJson(res, 200, { ok: true, data: await extCall(b.method, b.params || {}, b.timeout, b.browser) });
1411
+ for (const pid of Array.isArray(b.pids) ? b.pids : []) {
1412
+ if (Number.isInteger(pid) && pid > 1 && !owners.has(pid)) { owners.add(pid); everOwned = true; }
1413
+ }
1414
+ return sendJson(res, 200, { ok: true });
1415
+ }
1416
+ if (p === '/api/ext' && req.method === 'POST') {
1417
+ // 另一个桥接进程(stdio)转发来的调用。导入的录制包最大 50MB(见 readPkgFile),转成 JSON 还会变长一些
1418
+ const b = await readBody(req, 64e6);
1419
+ if (b.method === 'importPackage' && !TOKEN && !fromStdio(req)) return sendJson(res, 403, { ok: false, error: IMPORT_NEEDS_TOKEN });
1420
+ const wait = Number.isFinite(b.wait) ? Math.min(Math.max(0, b.wait), EXT_WAIT_MS) : undefined;
1421
+ return sendJson(res, 200, { ok: true, data: await extCall(b.method, b.params || {}, b.timeout, b.browser, wait) });
1099
1422
  }
1100
1423
  if (p === '/api/recordings' && req.method === 'GET') return sendJson(res, 200, { ok: true, data: await extCall('list', {}, 60000, browserOf(u)) });
1101
1424
  if (p === '/api/packages' && req.method === 'POST') {
@@ -1170,14 +1493,35 @@ server.on('error', (e) => {
1170
1493
  markReady();
1171
1494
  log(`端口 ${PORT} 已被另一个桥接实例占用,本实例将转发给它`);
1172
1495
  if (!STDIO) process.exit(1);
1496
+ // 等不及的后台桥接后来起来了:照样订阅、登记,不然它没人登记会自己关掉
1497
+ if (!NO_DAEMON) watchBridge(false);
1173
1498
  } else log('服务错误:' + e.message);
1174
1499
  });
1175
- server.listen(PORT, HOST, () => {
1176
- isPrimary = true;
1177
- markReady();
1178
- log(`已启动:http://${HOST}:${PORT} (MCP: /mcp,REST: /api,扩展: ws://${HOST}:${PORT}/ext)${TOKEN ? ',已启用 token' : ''}`);
1179
- log('等待浏览器扩展连接…(扩展最多 30 秒内自动连上)');
1500
+ function listen() {
1501
+ server.listen(PORT, HOST, () => {
1502
+ isPrimary = true;
1503
+ markReady();
1504
+ try {
1505
+ fs.mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
1506
+ fs.writeFileSync(STATE_FILE, JSON.stringify({ pid: process.pid, version: VERSION, secret: SECRET }), { mode: 0o600 });
1507
+ } catch (e) { log('写入 ' + STATE_FILE + ' 失败:' + e.message); }
1508
+ log(`已启动:http://${HOST}:${PORT} (MCP: /mcp,REST: /api,扩展: ws://${HOST}:${PORT}/ext)${TOKEN ? ',已启用 token' : ''}${DAEMON ? ',后台运行' : ''}`);
1509
+ log('等待浏览器扩展连接…(扩展最多 30 秒内自动连上)');
1510
+ });
1511
+ }
1512
+ process.on('exit', () => {
1513
+ try { if (JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')).pid === process.pid) fs.unlinkSync(STATE_FILE); } catch (e) { /* 没写过或已被新实例覆盖 */ }
1180
1514
  });
1515
+ for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(0));
1516
+ if (STDIO && !NO_DAEMON) {
1517
+ // 复用或在后台起一个桥接;起不来就退回自己监听端口
1518
+ ensureBridge().then((up) => {
1519
+ if (!up) return listen();
1520
+ markReady();
1521
+ log('转发给后台桥接');
1522
+ watchBridge(false);
1523
+ });
1524
+ } else listen();
1181
1525
 
1182
1526
  // ======================= MCP stdio =======================
1183
1527
  if (STDIO) {
package/manifest.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Page Recorder · 操作与接口录制",
4
- "version": "1.3.0",
4
+ "version": "1.4.0",
5
5
  "description": "录制页面操作,抓取接口请求与返回数据,导出为可在浏览器中执行、便于 AI 理解和调用的回放脚本。",
6
6
  "permissions": [
7
7
  "storage",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "page-recorder-mcp",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Record clicks and the fetch/XHR APIs behind them in your logged-in Chrome (including cross-origin iframes), then let AI tools replay them or call the APIs directly through MCP / HTTP. Zero dependencies. 录制页面操作和接口(含跨域 iframe),让 Claude Code、Accio 等 AI 工具通过 MCP / HTTP 在你已登录的浏览器里回放,或直接调用接口。",
5
5
  "keywords": [
6
6
  "mcp",