jtcrpa-mcp 0.4.2 → 0.6.1

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
@@ -8,34 +8,36 @@
8
8
 
9
9
  ### 首次连接
10
10
 
11
- 1. **浏览器里找到 MCP 入口。** 在 Windows 上将**九头虫 Agent** 添加到 Chrome 或 Firefox。点击浏览器工具栏的九头虫图标打开侧边栏,再点底部的 **设置菜单 ☰ → MCP 连接**。打开页面后应能看到 **开启 MCP 连接** 开关。[设置菜单截图](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/images/settings-menu-zh.png) · [扩展安装说明](https://doc.jtcrpa.com/guide/install.html)
11
+ 1. **浏览器里找到 MCP 入口。** 在 macOS 或 Windows 上将**九头虫 Agent** 添加到 Chrome 或 Firefox。点击浏览器工具栏的九头虫图标打开侧边栏,再点底部的 **设置菜单 ☰ → MCP 连接**。打开页面后应能看到 **开启 MCP 连接** 开关。[设置菜单截图](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/images/settings-menu-zh.png) · [扩展安装说明](https://doc.jtcrpa.com/guide/install.html)
12
12
 
13
13
  如果菜单里没有这个入口,先确认扩展版本。Chrome 和 Firefox 商店发布的 `2.0.2` 都缺少 MCP。只有商店版时,可向九头虫咨询支持 MCP 的安装包。[联系九头虫](https://jtcrpa.com/contact)
14
14
 
15
- 2. **在 PowerShell 安装桥接器。** 从 Windows 开始菜单打开 PowerShell。需要 Windows PowerShell 5.1 和 Node.js 20.19.0 或更高版本。逐行运行下面的命令,第一行检查 Node.js,最后一行应显示桥接器版本号。[Node.js 下载](https://nodejs.org/en/download)
15
+ 2. **在终端安装桥接器。** 需要 Node.js 20.19.0 或更高版本。macOS 打开「终端」,Windows 打开 PowerShell 5.1。已发布的兼容版本可用下面的命令安装。[Node.js 下载](https://nodejs.org/en/download)
16
16
 
17
- ```powershell
17
+ ```sh
18
18
  node --version
19
19
  npm install -g jtcrpa-mcp
20
20
  jtcrpa-mcp --version
21
21
  ```
22
22
 
23
- 3. **把这个浏览器连上。** 回到扩展的 **MCP 连接 → 注册当前浏览器**,点击复制按钮,把整条命令粘贴到刚才的 PowerShell 并按回车。页面已填好当前扩展的 ID。回到扩展打开 **开启 MCP 连接**,浏览器询问时允许本机通信。看到 **浏览器与本机程序已连接** 再继续。
24
- 4. **把 Codex 连上。** 在同一页的 **接入外部 AI → Codex** 点击 **复制 Codex 接入命令**,在 PowerShell 粘贴并执行。运行 `codex mcp list` 应能看到 `jtcrpa`。打开一个新的 Codex 会话,下面三条消息都发在这个会话里。已安装并登录的 Codex CLI 可以在 PowerShell 输入 `codex` 打开。[安装 Codex CLI](https://developers.openai.com/codex/cli/) · [使用 Claude Code 或 DeepSeek Harness](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/usage.md#客户端配置)
23
+ 此 Codex CLI 流程需要支持浏览器实例绑定的扩展和 0.5.1 或更高版本的桥接器。开发测试可在本仓库运行 `npm run build` 后使用 `npm pack` 生成的本地安装包。
24
+
25
+ 3. **连接你要用的浏览器。** 在该浏览器的 **MCP 连接** 页面打开 **开启 MCP 连接** 开关,按提示允许本机通信,然后选择 **Codex** 查看首次接入命令。
26
+ 4. **登记 MCP 服务。** 将页面给出的整条命令粘贴到终端运行。命令核对目标浏览器后,显示浏览器名称和 MCP 服务名,然后退出。Codex 加载这项配置后,你可以在自己的对话里提出任务。首次访问后,扩展会显示访问时间。要使用另一份浏览器配置,从那份配置的扩展页接入。[安装 Codex CLI](https://developers.openai.com/codex/cli/) · [使用 Claude Code 或 DeepSeek Harness](docs/usage.md#客户端配置)
25
27
 
26
28
  ### 第一次用 MCP 采集书名和价格
27
29
 
28
- **① 打开网页,确认连到了它。** 用刚才连接的浏览器打开书店首页。如果页面显示英文,点页头的 **简体中文**。然后在 **Codex 聊天框**发送第一条消息。[打开书店练习场](https://doc.jtcrpa.com/practice/index.html)
30
+ **① 读取网页。** 在已接入九头虫 MCP 的 AI 对话中发送下面的任务。九头虫会在已绑定的浏览器中打开或复用目标页,沿用该浏览器的登录状态。如果书店显示英文,可在页头切到 **简体中文**。
29
31
 
30
- > 用九头虫 MCP 检查连接,找到我打开的书店练习场标签页。告诉我页面标题,并从页面上读出第一本书的书名和价格。
32
+ > 用九头虫打开 https://doc.jtcrpa.com/practice/index.html ,告诉我页面标题和第一本书的书名、价格。
31
33
 
32
- 返回结果应能跟页面对上,第一本是《山海之间》,价格 ¥32.00。若找错页,先核对打开练习场的浏览器和配置,再继续。
34
+ 练习场首页的第一本书是《山海之间》,价格 ¥32.00。
33
35
 
34
36
  **② 保存一条可复用的规则。** 在同一个聊天里发送第二条消息。
35
37
 
36
38
  > 把书店当前列表页的每本书采成一行,书名列叫 title,价格列叫 price,保留货币符号,只采当前页。先在页面上试采,再把规则保存为工作流「Bookshop demo」,运行时写入数据集 bookshop_demo。告诉我保存的工作流编号,等我确认再运行。
37
39
 
38
- 此时你应拿到 `workflowId`(工作流编号)。也可以在扩展的 **主工作台** 搜索 `Bookshop demo` 查看已保存的规则。
40
+ 此时你应拿到 `workflowId`(工作流编号)。也可以在扩展的 **主工作台** 搜索 `Bookshop demo` 查看已保存的规则。页面会保留,方便检查或试运行。需要关页时,可以自己关闭,也可以在对话里明确指定要关闭的页面。
39
41
 
40
42
  **③ 运行并核对数据。** 收到保存结果后,再单独发第三条消息。
41
43
 
@@ -60,34 +62,36 @@
60
62
 
61
63
  ### First-time setup
62
64
 
63
- 1. **Find MCP in the browser.** On Windows, add **Jiutouchong Agent** to Chrome or Firefox. Click its toolbar icon to open the sidebar, then choose **Settings ☰ → MCP connection** at the bottom. Look for the **Enable MCP connection** switch. [See the Settings menu](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/images/settings-menu-en.png) · [Extension installation guide](https://doc.jtcrpa.com/en/guide/install.html)
65
+ 1. **Find MCP in the browser.** On macOS or Windows, add **Jiutouchong Agent** to Chrome or Firefox. Click its toolbar icon to open the sidebar, then choose **Settings ☰ → MCP connection** at the bottom. Look for the **Enable MCP connection** switch. [See the Settings menu](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/images/settings-menu-en.png) · [Extension installation guide](https://doc.jtcrpa.com/en/guide/install.html)
64
66
 
65
67
  If the menu entry is missing, check the extension build. Version `2.0.2` from both browser stores lacks MCP. If you only have the store release, contact Jiutouchong about an MCP-enabled build. [Contact Jiutouchong](https://jtcrpa.com/en/contact)
66
68
 
67
- 2. **Install the bridge in PowerShell.** Open PowerShell from the Windows Start menu. You need Windows PowerShell 5.1 and Node.js 20.19.0 or later. Run these lines in order. The first prints your Node.js version and the last should print the bridge version. [Download Node.js](https://nodejs.org/en/download)
69
+ 2. **Install the bridge in a terminal.** Use Node.js 20.19.0 or later. Open Terminal on macOS or PowerShell 5.1 on Windows. For a published version supporting your platform, run the following commands. [Download Node.js](https://nodejs.org/en/download)
68
70
 
69
- ```powershell
71
+ ```sh
70
72
  node --version
71
73
  npm install -g jtcrpa-mcp
72
74
  jtcrpa-mcp --version
73
75
  ```
74
76
 
75
- 3. **Connect this browser.** On the extension’s **MCP connection** page, copy the command under **Register this browser**. Paste it into PowerShell and press Enter. It already contains your extension’s ID. Back in the extension, turn on **Enable MCP connection** and allow native messaging if prompted. Continue when you see **Browser connected to the local program**.
76
- 4. **Connect Codex.** On the same page, under **Connect an AI app → Codex**, click **Copy Codex setup command** and run it in PowerShell. Run `codex mcp list` and look for `jtcrpa`. Open a new Codex session for the three messages below. If the Codex CLI is installed and you’re signed in, type `codex` in PowerShell to start it. [Install the Codex CLI](https://developers.openai.com/codex/cli/) · [Use Claude Code or DeepSeek Harness](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/usage.md#client-configuration)
77
+ This Codex CLI flow requires an extension that supports browser instance binding and bridge version 0.5.1 or later. To test a development checkout, run `npm run build` and install the local package produced by `npm pack`.
78
+
79
+ 3. **Connect the browser you want to use.** In that profile, open **MCP connection**, turn on the connection switch and allow native messaging when prompted. Select **Codex** to see the first-time setup command.
80
+ 4. **Register the MCP server.** Run the setup command in your terminal. It verifies the target browser, prints its display name and MCP server name, then exits. Once Codex has loaded the configuration, enter your task in your own conversation. The extension shows the time of the first access. To use another profile, start from its extension page. [Install the Codex CLI](https://developers.openai.com/codex/cli/) · [Use Claude Code or DeepSeek Harness](docs/usage.md#client-configuration)
77
81
 
78
82
  ### Collect your first four books
79
83
 
80
- **① Open the page and check the connection.** Open the bookshop homepage in the browser you just connected. If it appears in Chinese, click **English** in the page header. Send this first message in **Codex chat**. [Open the bookshop playground](https://doc.jtcrpa.com/en/practice/index.html)
84
+ **① Read a page.** Send this task in an AI conversation connected to Jiutouchong MCP. The tool opens or reuses the page in the bound browser profile, using that profile’s sign-in state. If the bookshop appears in Chinese, select **English** in the page header.
81
85
 
82
- > Use Jiutouchong MCP to check the connection and find my open bookshop playground tab. Tell me the page title and read the first book’s title and price from the page.
86
+ > Use Jiutouchong to open https://doc.jtcrpa.com/en/practice/index.html and tell me the page title and the first book’s title and price.
83
87
 
84
- You should see *Between Mountains and Seas* at ¥32.00. If the result is from a different page, check which browser profile has the bookshop open.
88
+ The first book on the practice homepage is *Between Mountains and Seas* at ¥32.00.
85
89
 
86
90
  **② Save a reusable workflow.** Send this in the same chat.
87
91
 
88
92
  > Collect one row per book on the current listing page. Name the columns title and price and keep the currency symbol. Preview the extraction on the page, then save a workflow named “Bookshop demo” that writes to the bookshop_demo dataset when run. Give me the saved workflow ID and wait for my confirmation.
89
93
 
90
- You should receive a `workflowId`. To find the saved rule in the extension, open **Workbench** and search for `Bookshop demo`.
94
+ You should receive a `workflowId`. To find the saved rule in the extension, open **Workbench** and search for `Bookshop demo`. The tab stays open for review or a trial run. Close it yourself or explicitly ask the assistant to close that specific page.
91
95
 
92
96
  **③ Run it and check the saved rows.** Once the client reports that it saved the workflow, send a separate message.
93
97
 
package/bin/cli.mjs CHANGED
@@ -10,8 +10,10 @@ const usage = [
10
10
  ' add (--chrome-id <扩展ID> | --firefox-id <扩展ID>) [--instance <UUID>]',
11
11
  ' remove [连接编号]',
12
12
  '客户端接入',
13
+ ' connect-codex (--chrome-id <扩展ID> | --firefox-id <扩展ID>) --instance <UUID> --setup <UUID>',
13
14
  ' config (--connection <连接编号> | --instance <UUID>) [--client codex|claude|deepseek]',
14
15
  ' mcp (--connection <配置中的绑定UUID> | --instance <实例UUID>)',
16
+ ' macOS Chrome 的 add 和 connect-codex 可加 --chrome-user-data-dir <用户数据根目录>',
15
17
  '维护',
16
18
  ' uninstall 清除当前用户的本机宿主登记',
17
19
  ' --version 显示桥接器版本',
@@ -19,11 +21,13 @@ const usage = [
19
21
  function targetOptions(config) {
20
22
  const options = { connection: { type: 'string' }, instance: { type: 'string' } };
21
23
  if (config) options.client = { type: 'string' };
24
+ else options['expect-instance'] = { type: 'string' };
22
25
  const { values, tokens } = parseArgs({ args, options, tokens: true });
23
26
  if (tokens.filter(t => t.name === 'connection' || t.name === 'instance').length !== 1) {
24
27
  throw new Error('Specify one --connection or --instance target.');
25
28
  }
26
29
  if (values.instance !== undefined && !/^[a-f0-9-]{36}$/.test(values.instance)) throw new Error('Invalid instance UUID');
30
+ if (values['expect-instance'] !== undefined && (!values.connection || !/^[a-f0-9-]{36}$/.test(values['expect-instance']))) throw new Error('Invalid expected instance');
27
31
  if (values.connection !== undefined && config && !/^c[1-9]\d*$/.test(values.connection)) throw new Error('Invalid connection number');
28
32
  if (values.connection !== undefined && !config && /^c[1-9]\d*$/.test(values.connection)) {
29
33
  throw new Error('请先用 jtcrpa-mcp config --connection ' + values.connection + ' 生成带绑定 UUID 的客户端配置。');
@@ -31,16 +35,17 @@ function targetOptions(config) {
31
35
  return values;
32
36
  }
33
37
  try {
34
- if (process.platform !== 'win32') throw new Error('This release supports native Windows only.');
38
+ if (!['win32', 'darwin'].includes(process.platform)) throw new Error('This release supports macOS and Windows.');
35
39
  if (command === 'uninstall' && args.length === 1 && ['--help', '-h'].includes(args[0])) {
36
40
  console.log('Usage: jtcrpa-mcp uninstall\n清除当前用户的本机宿主登记和连接。请先关闭浏览器中的 MCP。');
37
41
  }
38
42
  else if (command === 'list') await (await import('../dist/connection-cli.js')).listCommand(args);
39
43
  else if (command === 'remove') await (await import('../dist/connection-cli.js')).removeCommand(args);
40
44
  else if (command === 'native-host') await (await import('../dist/native-host.js')).runNativeHost(args);
45
+ else if (command === 'connect-codex') await (await import('../dist/codex-setup.js')).connectCodex(args);
41
46
  else if (command === 'mcp') {
42
- const { connection, instance } = targetOptions(false);
43
- await (await import('../dist/mcp.js')).serveMcp(connection !== undefined ? { bindingId: connection } : instance);
47
+ const { connection, instance, 'expect-instance': expectedInstanceId } = targetOptions(false);
48
+ await (await import('../dist/mcp.js')).serveMcp(connection !== undefined ? { bindingId: connection, expectedInstanceId } : instance);
44
49
  }
45
50
  else if (command === 'add' || command === 'uninstall') await (await import('../dist/install.js')).manageHostRegistration(command, args);
46
51
  else if (command === 'config') {
@@ -0,0 +1,107 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ const cli = fileURLToPath(new URL('../bin/cli.mjs', import.meta.url));
7
+ function codexCommand(args) {
8
+ let executable = 'codex';
9
+ let batch = false;
10
+ if (process.platform === 'win32') {
11
+ const paths = (process.env.PATH ?? '').split(path.delimiter).map(dir => dir.replace(/^"|"$/g, '')).filter(dir => path.isAbsolute(dir));
12
+ const found = paths.flatMap(dir => ['codex.exe', 'codex.cmd', 'codex.bat'].map(file => path.join(dir, file))).find(file => fs.existsSync(file));
13
+ if (!found)
14
+ throw new Error('请先安装 Codex CLI,确保此终端能够运行 codex。');
15
+ executable = found;
16
+ batch = !found.toLowerCase().endsWith('.exe');
17
+ if (batch) {
18
+ const parts = [found, ...args];
19
+ if (parts.some(part => /["%\r\n]/.test(part)))
20
+ throw new Error('Unsupported character in Windows Codex command path or argument');
21
+ // cmd /s strips one outer quote pair. Every argument keeps its own quotes through the npm/pnpm shim.
22
+ args = ['/d', '/v:off', '/s', '/c', '"' + parts.map(part => '"' + part + '"').join(' ') + '"'];
23
+ executable = path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'cmd.exe');
24
+ }
25
+ }
26
+ return { executable, args, batch };
27
+ }
28
+ function runMcpConfig(action, options) {
29
+ const { executable, args, batch } = codexCommand(['mcp', action, ...options]);
30
+ const result = spawnSync(executable, args, {
31
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
32
+ windowsVerbatimArguments: batch, timeout: 20_000,
33
+ });
34
+ if (result.error)
35
+ throw result.error;
36
+ if (result.status !== 0)
37
+ throw new Error(result.stderr?.trim() || 'Codex MCP 配置失败。');
38
+ return result.stdout ?? '';
39
+ }
40
+ // Recreating a server with "mcp add" would drop custom settings or named tool rules.
41
+ // Only migrate our original command/args table (0.5.0 also wrote enabled=false).
42
+ function isDefaultLegacyRegistration(server) {
43
+ const { name } = server;
44
+ const file = path.join(process.env.CODEX_HOME || path.join(homedir(), '.codex'), 'config.toml');
45
+ if (!fs.existsSync(file))
46
+ return false;
47
+ const config = fs.readFileSync(file, 'utf8');
48
+ const mentions = config.match(new RegExp('(?<![\\w-])' + name + '(?![\\w-])', 'g'));
49
+ if (mentions?.length !== 1 || config.includes('mcp__' + name + '__'))
50
+ return false;
51
+ const sections = config.replace(/\r\n/g, '\n').split(/(?=^\[)/m);
52
+ const header = '[mcp_servers.' + name + ']\n';
53
+ const table = sections.find(section => section.startsWith(header));
54
+ const parent = sections.find(section => section.startsWith('[mcp_servers]\n'));
55
+ const root = sections[0]?.startsWith('[') ? '' : sections[0];
56
+ // The Codex config writer can serialize the same entry as an inline table.
57
+ const fields = table?.slice(header.length) ??
58
+ parent?.match(new RegExp('^' + name + '\\s*=\\s*\\{(.*)\\}\\s*$', 'm'))?.[1] ??
59
+ root?.match(new RegExp('^mcp_servers\\.' + name + '\\s*=\\s*\\{(.*)\\}\\s*$', 'm'))?.[1];
60
+ if (!fields)
61
+ return false;
62
+ // Values have already been checked against the registered transport by Codex.
63
+ const shape = fields.replace(/"(?:\\.|[^"\\\r\n])*"|'[^'\r\n]*'/g, '@')
64
+ .replace(/#[^\n]*/g, '').replace(/\s/g, '');
65
+ return shape.includes('enabled=false') === !server.enabled && shape.includes('command=@') && shape.includes('args=[') &&
66
+ shape.replace(/command=@|enabled=(?:true|false)|args=\[@(?:,@)*,?\]|,/g, '') === '';
67
+ }
68
+ function matchesRegistration(server, args) {
69
+ return server.transport.type === 'stdio' && server.transport.command === process.execPath &&
70
+ JSON.stringify(server.transport.args) === JSON.stringify(args);
71
+ }
72
+ function isGeneratedName(name, base) {
73
+ return name.startsWith(base) && /^(?:_(?:[2-9]|[1-9]\d+))?$/.test(name.slice(base.length));
74
+ }
75
+ function requireEnabled(server) {
76
+ if (!server.enabled)
77
+ throw new Error('Codex 中的 MCP 服务 ' + server.name + ' 已停用。请在 Codex 中启用此服务后重新接入。');
78
+ }
79
+ export function configureServer(bindingId, instanceId, browser, previous) {
80
+ const servers = JSON.parse(runMcpConfig('list', ['--json']));
81
+ const args = [cli, 'mcp', '--connection', bindingId, '--expect-instance', instanceId];
82
+ const base = 'jtcrpa_' + browser;
83
+ const legacyBase = base + '_' + bindingId.slice(0, 8);
84
+ const saved = previous && /^[a-zA-Z0-9_-]+$/.test(previous) ? previous : undefined;
85
+ const matching = servers.filter(server => matchesRegistration(server, args));
86
+ const legacy = matching.find(server => (!saved || server.name === saved) && isGeneratedName(server.name, legacyBase));
87
+ if (legacy && ((!legacy.enabled && legacy.name !== saved) || !isDefaultLegacyRegistration(legacy))) {
88
+ requireEnabled(legacy);
89
+ return legacy.name;
90
+ }
91
+ let name = saved && !isGeneratedName(saved, legacyBase) ? saved : base;
92
+ const existing = matching.find(server => server.name === name) ?? matching.find(server => isGeneratedName(server.name, base) && !isGeneratedName(server.name, legacyBase));
93
+ if (existing) {
94
+ requireEnabled(existing);
95
+ name = existing.name;
96
+ }
97
+ else {
98
+ for (let suffix = 2; servers.some(server => server.name === name); suffix++) {
99
+ name = base + '_' + suffix;
100
+ }
101
+ runMcpConfig('add', [name, '--', process.execPath, ...args]);
102
+ }
103
+ // An interrupted migration can reuse the short entry before retrying removal.
104
+ if (legacy)
105
+ runMcpConfig('remove', [legacy.name]);
106
+ return name;
107
+ }
@@ -0,0 +1,76 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { parseArgs } from 'node:util';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { checkExtensionId, sameExtension } from "./browser-identity.js";
5
+ import { addConnection, connectionFile, connectionName, readConnections } from "./connections.js";
6
+ import { configureServer } from "./codex-client.js";
7
+ import { manageHostRegistration } from "./install.js";
8
+ import { callExtension } from "./ipc.js";
9
+ import { readDiscovery } from "./paths.js";
10
+ import { validInstance } from "./protocol.js";
11
+ import { replaceFile } from "./registration-files.js";
12
+ import { withRegistrationLock } from "./registration-lock.js";
13
+ async function waitForBrowser(target, instanceId, ticket) {
14
+ const deadline = Date.now() + 120_000;
15
+ for (;;) {
16
+ try {
17
+ const discovery = readDiscovery(instanceId);
18
+ if (!sameExtension(target, discovery.caller))
19
+ throw new Error('CONNECTION_INSTANCE_MISMATCH');
20
+ const reply = await callExtension(instanceId, 'codex_setup', { ticket }, 3500);
21
+ if (reply?.instanceId !== instanceId)
22
+ throw new Error('CONNECTION_INSTANCE_MISMATCH');
23
+ return typeof reply.label === 'string' ? reply.label.replace(/[\p{C}]/gu, '').trim().slice(0, 48) : '';
24
+ }
25
+ catch (error) {
26
+ const failure = error;
27
+ if (failure.message === 'UNKNOWN_METHOD')
28
+ throw new Error('请更新九头虫扩展和桥接器,重新开启连接后再接入。');
29
+ if (failure.message === 'CODEX_SETUP_MISMATCH')
30
+ throw new Error('这条命令已失效或属于另一份浏览器配置。请从目标浏览器重新接入。');
31
+ if (!['ENOENT', 'ECONNREFUSED', 'ECONNRESET', 'EPIPE'].includes(failure.code ?? '') &&
32
+ !['BROWSER_OFFLINE', 'BRIDGE_TIMEOUT', 'BRIDGE_CLOSED'].includes(failure.message))
33
+ throw error;
34
+ if (Date.now() >= deadline)
35
+ throw new Error('等待目标浏览器超时。请回到发起接入的九头虫 MCP 页面查看状态,然后重试。');
36
+ await delay(500);
37
+ }
38
+ }
39
+ }
40
+ export async function connectCodex(args) {
41
+ const { values } = parseArgs({ args, options: { 'chrome-user-data-dir': { type: 'string' }, 'chrome-id': { type: 'string' }, 'firefox-id': { type: 'string' },
42
+ instance: { type: 'string' }, setup: { type: 'string' } } });
43
+ const chrome = values['chrome-id'], firefox = values['firefox-id'];
44
+ const { instance: instanceId, setup: ticket } = values;
45
+ if (Boolean(chrome) === Boolean(firefox) || !validInstance(instanceId) || !validInstance(ticket)) {
46
+ throw new Error('请从目标浏览器复制完整的 Codex 接入命令。');
47
+ }
48
+ const target = chrome ? { kind: 'chrome', extensionId: chrome } : { kind: 'firefox', extensionId: firefox };
49
+ checkExtensionId(target.kind, target.extensionId);
50
+ const registration = ['--' + target.kind + '-id', target.extensionId];
51
+ const directory = values['chrome-user-data-dir'];
52
+ if (directory !== undefined)
53
+ registration.push('--chrome-user-data-dir', directory);
54
+ await manageHostRegistration('add', registration);
55
+ console.log('正在等待发起接入的浏览器…');
56
+ const setup = await bindCodexBrowser(target, instanceId, ticket);
57
+ console.log(setup.displayName + ' 已就绪。Codex MCP 服务名为 ' + setup.name);
58
+ }
59
+ export async function bindCodexBrowser(target, instanceId, ticket) {
60
+ const label = await waitForBrowser(target, instanceId, ticket);
61
+ const setup = await withRegistrationLock(() => {
62
+ const store = readConnections();
63
+ const connection = addConnection(store, target, instanceId);
64
+ connection.bindingId ??= randomUUID();
65
+ // A retry after a Codex/config write failure must reuse this exact binding.
66
+ replaceFile(connectionFile(), JSON.stringify(store));
67
+ const name = configureServer(connection.bindingId, instanceId, target.kind + '_' + connection.id, connection.codexServer);
68
+ connection.codexServer = name;
69
+ connection.label = label || undefined;
70
+ replaceFile(connectionFile(), JSON.stringify(store));
71
+ const displayName = connectionName(connection);
72
+ return { name, displayName, bindingId: connection.bindingId };
73
+ });
74
+ await callExtension({ bindingId: setup.bindingId, expectedInstanceId: instanceId }, 'codex_setup', { ticket, bindingId: setup.bindingId, displayName: setup.displayName, serverName: setup.name });
75
+ return setup;
76
+ }
@@ -32,18 +32,21 @@ async function inspectConnections() {
32
32
  return listConnections(confirmed.filter(item => item !== undefined), uncertain);
33
33
  }
34
34
  function printList(list) {
35
+ const command = process.platform === 'win32' ? 'jtcrpa-mcp.cmd' : 'jtcrpa-mcp';
35
36
  if (!list.connections.length)
36
- console.log('尚未登记连接。请从插件的 MCP 页面复制 jtcrpa-mcp.cmd add 命令。');
37
+ console.log(`尚未登记连接。请从插件的 MCP 页面复制 ${command} add 命令。`);
37
38
  for (const [i, item] of list.connections.entries()) {
38
- console.log(`${i + 1}. ${item.id} ${browserNames[item.kind]} ${item.extensionId} ${states[item.status]}`);
39
+ console.log(`${i + 1}. ${item.id} ${browserNames[item.kind]} ${item.label ? item.label + ' ' : ''}${item.extensionId} ${states[item.status]}`);
39
40
  console.log(' 目标实例 ' + (item.instanceId ?? '待选择实例'));
41
+ if (item.codexServer)
42
+ console.log(' Codex 服务 ' + item.codexServer);
40
43
  for (const candidate of item.candidates.filter(x => x.instanceId !== item.instanceId)) {
41
44
  console.log(` 可选实例 ${candidate.instanceId} ${candidateState(candidate.online)}`);
42
45
  }
43
46
  if (!item.instanceId && item.candidates.length) {
44
47
  const flag = item.kind === 'chrome' ? '--chrome-id' : '--firefox-id';
45
48
  const id = item.candidates.length === 1 ? item.candidates[0].instanceId : '<上方实例UUID>';
46
- console.log(` 选择目标 jtcrpa-mcp.cmd add ${flag} ${item.extensionId} --instance ${id}`);
49
+ console.log(` 选择目标 ${command} add ${flag} ${item.extensionId} --instance ${id}`);
47
50
  }
48
51
  }
49
52
  for (const id of list.unconfirmedInstances)
@@ -6,6 +6,10 @@ import { sameExtension } from "./browser-identity.js";
6
6
  import { validInstance } from "./protocol.js";
7
7
  import { withRegistrationLock } from "./registration-lock.js";
8
8
  import { replaceFile } from "./registration-files.js";
9
+ export function connectionName(connection) {
10
+ const name = (connection.kind === 'chrome' ? 'Chrome' : 'Firefox') + ' · ' + connection.id;
11
+ return connection.label ? name + '(' + connection.label + ')' : name;
12
+ }
9
13
  export const connectionFile = () => path.join(bridgeRoot(), 'connections.json');
10
14
  export const validConnectionId = (id) => /^c[1-9]\d*$/.test(id);
11
15
  export function readConnections() {
@@ -90,8 +94,8 @@ export function listConnections(live = listRunningHosts(), uncertain = new Set()
90
94
  && (!record.instanceId || record.instanceId === host.instanceId));
91
95
  const status = selected.some(item => item.online) ? 'online'
92
96
  : awaitingHandshake || selected.some(item => item.online === null) ? 'unconfirmed' : 'offline';
93
- const { id, kind, extensionId, instanceId, bindingId } = record;
94
- return { id, kind, extensionId, instanceId, bindingId, status, candidates };
97
+ const { id, kind, extensionId, instanceId, bindingId, label, codexServer } = record;
98
+ return { id, kind, extensionId, instanceId, bindingId, label, codexServer, status, candidates };
95
99
  });
96
100
  return { connections, unconfirmedInstances: unconfirmed.map(host => host.instanceId) };
97
101
  }
package/dist/install.js CHANGED
@@ -5,6 +5,7 @@ import { execFileSync } from 'node:child_process';
5
5
  import { parseArgs } from 'node:util';
6
6
  import { bridgeRoot, listRunningHosts } from "./paths.js";
7
7
  import { HOST, validInstance } from "./protocol.js";
8
+ import { defaultChromeDataDir, resolveChromeDataDir } from "./mac-chrome.js";
8
9
  import { withRegistrationLock } from "./registration-lock.js";
9
10
  import { replaceFile } from "./registration-files.js";
10
11
  import { checkExtensionId, sameExtension } from "./browser-identity.js";
@@ -24,7 +25,8 @@ export async function clientConfig(target) {
24
25
  }
25
26
  function installationPaths() {
26
27
  const root = bridgeRoot();
27
- return { root, record: path.join(root, 'installation.json'), launcher: path.join(root, 'host.cmd') };
28
+ const launcher = process.platform === 'darwin' ? 'host.sh' : 'host.cmd';
29
+ return { root, record: path.join(root, 'installation.json'), launcher: path.join(root, launcher) };
28
30
  }
29
31
  export async function manageHostRegistration(command, args) {
30
32
  if (command === 'uninstall' && args.length)
@@ -34,17 +36,17 @@ export async function manageHostRegistration(command, args) {
34
36
  if (command === 'uninstall')
35
37
  uninstallNativeHost(paths);
36
38
  else {
37
- const { targets, instanceId } = parseBrowserTargets(args);
38
- addNativeHost(paths, targets, instanceId);
39
+ const { targets, instanceId, chromeDataDir } = parseBrowserTargets(args);
40
+ addNativeHost(paths, targets, instanceId, chromeDataDir);
39
41
  }
40
42
  });
41
43
  }
42
- function addNativeHost(paths, targets, instanceId) {
43
- if (/["%\r\n]/.test(cli + process.execPath + paths.root))
44
+ function addNativeHost(paths, targets, instanceId, chromeDataDir) {
45
+ if (process.platform === 'win32' && /["%\r\n]/.test(cli + process.execPath + paths.root))
44
46
  throw new Error('Unsupported character in installation path');
45
- const backup = captureInstallationBackup(paths, targets);
47
+ const backup = captureInstallationBackup(paths, targets, chromeDataDir);
46
48
  const previous = fs.existsSync(paths.record) ? readInstallationRecord(paths.record) : { kinds: [] };
47
- const files = sharedInstallationFiles(paths, previous, targets);
49
+ const files = sharedInstallationFiles(paths, previous, targets, chromeDataDir);
48
50
  const store = readConnections();
49
51
  const register = new Map();
50
52
  for (const target of targets) {
@@ -72,12 +74,18 @@ export async function removeConnection(expected) {
72
74
  if (revoke)
73
75
  store.observed = store.observed.filter(item => !sameExtension(before, item));
74
76
  const paths = installationPaths();
75
- const backup = captureInstallationBackup(paths, revoke ? [before] : []);
77
+ const backup = captureInstallationBackup(paths, []);
76
78
  const files = new Map([[connectionFile(), JSON.stringify(store)]]);
77
79
  if (revoke) {
78
80
  const manifest = manifestPath(paths, before.kind);
79
- if (!backup.registrations.get(before.kind))
81
+ const installation = readInstallationRecord(paths.record);
82
+ const locations = registeredDataDirs(installation, before.kind);
83
+ // Temporary development roots may have disappeared since registration.
84
+ const remaining = locations.filter(dir => dir === undefined || fs.existsSync(dir));
85
+ if (remaining.length && !remaining.some(dir => readHostRegistration(before.kind, dir) === manifest)) {
80
86
  throw new Error('本机宿主登记缺失,请重新运行 add。');
87
+ }
88
+ backup.files.set(manifest, fs.readFileSync(manifest));
81
89
  files.set(manifest, JSON.stringify(createHostManifest(paths.launcher, before, backup.files.get(manifest), 'remove'), null, 2));
82
90
  }
83
91
  commitRegistration(paths, backup, files, new Map());
@@ -85,8 +93,11 @@ export async function removeConnection(expected) {
85
93
  }
86
94
  function commitRegistration(paths, backup, files, register) {
87
95
  for (const [file, contents] of files) {
88
- if (backup.files.get(file)?.toString('utf8') === contents)
89
- files.delete(file);
96
+ if (backup.files.get(file)?.toString('utf8') !== contents)
97
+ continue;
98
+ if (process.platform === 'darwin' && file === paths.launcher && (fs.statSync(file).mode & 0o777) !== 0o700)
99
+ continue;
100
+ files.delete(file);
90
101
  }
91
102
  if (files.size === 0 && register.size === 0)
92
103
  return false;
@@ -99,21 +110,21 @@ function commitRegistration(paths, backup, files, register) {
99
110
  const updatedRegistry = [];
100
111
  try {
101
112
  for (const [file, contents] of files) {
102
- replaceFile(file, contents);
113
+ replaceFile(file, contents, file === paths.launcher ? 0o700 : 0o600);
103
114
  updatedFiles.push(file);
104
115
  }
105
116
  for (const [kind, manifest] of register) {
117
+ registerHost(kind, manifest, backup.chromeDataDir);
106
118
  updatedRegistry.push(kind);
107
- registerHost(kind, manifest);
108
119
  }
109
120
  }
110
121
  catch (error) {
111
122
  for (const kind of updatedRegistry)
112
- restoreHostRegistration(kind, backup.registrations.get(kind), manifestPath(paths, kind));
123
+ restoreHostRegistration(kind, backup.registrations.get(kind), manifestPath(paths, kind), backup.chromeDataDir);
113
124
  for (const file of updatedFiles) {
114
125
  const contents = backup.files.get(file);
115
126
  if (contents)
116
- replaceFile(file, contents);
127
+ replaceFile(file, contents, file === paths.launcher ? 0o700 : 0o600);
117
128
  else
118
129
  removeFileIfPresent(file);
119
130
  }
@@ -129,8 +140,10 @@ function uninstallNativeHost(paths) {
129
140
  const installation = readInstallationRecord(paths.record);
130
141
  for (const kind of installation.kinds) {
131
142
  const manifest = manifestPath(paths, kind);
132
- if (readHostRegistration(kind) === manifest)
133
- unregisterHost(kind);
143
+ for (const directory of registeredDataDirs(installation, kind)) {
144
+ if (readHostRegistration(kind, directory) === manifest)
145
+ unregisterHost(kind, directory);
146
+ }
134
147
  removeFileIfPresent(manifest);
135
148
  }
136
149
  fs.unlinkSync(paths.record);
@@ -140,7 +153,7 @@ function uninstallNativeHost(paths) {
140
153
  }
141
154
  function parseBrowserTargets(args) {
142
155
  const { values } = parseArgs({ args, options: {
143
- 'chrome-id': { type: 'string' }, 'firefox-id': { type: 'string' }, instance: { type: 'string' },
156
+ 'chrome-user-data-dir': { type: 'string' }, 'chrome-id': { type: 'string' }, 'firefox-id': { type: 'string' }, instance: { type: 'string' },
144
157
  } });
145
158
  const chrome = values['chrome-id'];
146
159
  const firefox = values['firefox-id'];
@@ -157,10 +170,22 @@ function parseBrowserTargets(args) {
157
170
  targets.push({ kind: 'firefox', extensionId: firefox });
158
171
  if (values.instance !== undefined && (!validInstance(values.instance) || targets.length !== 1))
159
172
  throw new Error('Specify one browser and a valid instance UUID.');
160
- return { targets, instanceId: values.instance };
173
+ const explicit = values['chrome-user-data-dir'];
174
+ if (explicit !== undefined && (!chrome || process.platform !== 'darwin')) {
175
+ throw new Error('--chrome-user-data-dir 仅适用于 macOS 上的 --chrome-id。');
176
+ }
177
+ const chromeDataDir = chrome && process.platform === 'darwin' ? resolveChromeDataDir(chrome, explicit) : undefined;
178
+ return { targets, instanceId: values.instance, chromeDataDir };
161
179
  }
162
180
  function prepareInstallationDirectory(root) {
163
- fs.mkdirSync(root, { recursive: true });
181
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
182
+ if (process.platform === 'darwin') {
183
+ fs.chmodSync(root, 0o700);
184
+ const instances = path.join(root, 'instances');
185
+ fs.mkdirSync(instances, { recursive: true, mode: 0o700 });
186
+ fs.chmodSync(instances, 0o700);
187
+ return;
188
+ }
164
189
  execFileSync('powershell.exe', [
165
190
  '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
166
191
  '-File', fileURLToPath(new URL('../windows/secure-directory.ps1', import.meta.url)),
@@ -175,7 +200,7 @@ function readInstallationRecord(file) {
175
200
  function manifestPath(paths, kind) {
176
201
  return path.join(paths.root, `${kind}.json`);
177
202
  }
178
- function captureInstallationBackup(paths, targets) {
203
+ function captureInstallationBackup(paths, targets, chromeDataDir) {
179
204
  const manifestFiles = targets.map((target) => manifestPath(paths, target.kind));
180
205
  const files = new Map();
181
206
  for (const file of [paths.launcher, paths.record, connectionFile(), ...manifestFiles]) {
@@ -183,23 +208,36 @@ function captureInstallationBackup(paths, targets) {
183
208
  }
184
209
  const registrations = new Map();
185
210
  for (const { kind } of targets) {
186
- const manifest = readHostRegistration(kind);
211
+ const manifest = readHostRegistration(kind, chromeDataDir);
187
212
  if (manifest && manifest !== manifestPath(paths, kind)) {
188
213
  throw new Error(`A different ${kind} host is registered; refusing to overwrite it.`);
189
214
  }
190
215
  registrations.set(kind, manifest);
191
216
  }
192
- return { files, registrations };
217
+ return { files, registrations, chromeDataDir };
193
218
  }
194
- function sharedInstallationFiles(paths, previous, targets) {
219
+ function registeredDataDirs(installation, kind) {
220
+ if (process.platform === 'darwin' && kind === 'chrome') {
221
+ return installation.chromeDataDirs ?? [defaultChromeDataDir()];
222
+ }
223
+ return [undefined];
224
+ }
225
+ function sharedInstallationFiles(paths, previous, targets, chromeDataDir) {
195
226
  // 批处理文件按 UTF-8 写入,先切换代码页再读取含中文的 Node / CLI 路径。
196
- const launcher = `@echo off\r\nchcp 65001 >nul\r\n"${process.execPath}" "${cli}" native-host "%~1" "%~2"\r\n`;
227
+ const quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
228
+ const launcher = process.platform === 'darwin'
229
+ ? `#!/bin/sh\nexport JTCRPA_BRIDGE_HOME=${quote(paths.root)}\nexec ${quote(process.execPath)} ${quote(cli)} native-host "$@"\n`
230
+ : `@echo off\r\nchcp 65001 >nul\r\n"${process.execPath}" "${cli}" native-host "%~1" "%~2"\r\n`;
197
231
  const requestedKinds = targets.map((target) => target.kind);
198
232
  const record = {
199
233
  kinds: [...new Set([...previous.kinds, ...requestedKinds])],
200
234
  node: process.execPath,
201
235
  cli,
202
236
  };
237
+ if (process.platform === 'darwin' && record.kinds.includes('chrome')) {
238
+ const dirs = previous.chromeDataDirs ?? (previous.kinds.includes('chrome') ? [defaultChromeDataDir()] : []);
239
+ record.chromeDataDirs = [...new Set(chromeDataDir ? [...dirs, chromeDataDir] : dirs)];
240
+ }
203
241
  return new Map([[paths.launcher, launcher], [paths.record, JSON.stringify(record)]]);
204
242
  }
205
243
  function createHostManifest(launcher, target, previous, action) {
package/dist/ipc.js CHANGED
@@ -8,6 +8,9 @@ export function callExtension(target, method, params = {}, timeoutMs = 50000) {
8
8
  const connection = typeof target === 'string' ? undefined : findBinding(target.bindingId);
9
9
  if (typeof target !== 'string' && !connection)
10
10
  throw new Error('CONNECTION_REMOVED');
11
+ const expectedInstanceId = typeof target === 'string' ? undefined : target.expectedInstanceId;
12
+ if (expectedInstanceId && connection?.instanceId !== expectedInstanceId)
13
+ throw new Error('CONNECTION_INSTANCE_MISMATCH');
11
14
  const instanceId = typeof target === 'string' ? target : connection?.instanceId;
12
15
  if (!instanceId)
13
16
  throw new Error('CONNECTION_INSTANCE_NOT_SELECTED');
@@ -21,7 +24,9 @@ export function callExtension(target, method, params = {}, timeoutMs = 50000) {
21
24
  }
22
25
  if (connection && !sameExtension(connection, record.caller))
23
26
  throw new Error('CONNECTION_INSTANCE_MISMATCH');
24
- const request = JSON.stringify({ token: record.token, method, params }) + '\n';
27
+ const request = JSON.stringify({ token: record.token, method, params,
28
+ expectedInstanceId, codexBinding: expectedInstanceId ? connection?.bindingId : undefined,
29
+ codexAccess: typeof target !== 'string' && target.reportCodexAccess || undefined }) + '\n';
25
30
  if (Buffer.byteLength(request) > MAX_BYTES - 1024) {
26
31
  reject(new Error('MESSAGE_TOO_LARGE'));
27
32
  return;
@@ -46,7 +51,7 @@ export function callExtension(target, method, params = {}, timeoutMs = 50000) {
46
51
  }
47
52
  socket.destroy();
48
53
  });
49
- socket.on('error', reject);
54
+ socket.on('error', (error) => reject(error.code === 'ENOENT' || error.code === 'ECONNREFUSED' ? new Error('BROWSER_OFFLINE') : error));
50
55
  socket.on('end', () => { if (!result.includes(10))
51
56
  reject(new Error('BRIDGE_CLOSED')); });
52
57
  socket.on('close', () => clearTimeout(timer));